import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;
import java.util.*;
import java.security.spec.*;

public class Sobre
{

   public static boolean manipulate(String e) throws Exception
	{
		File f = new File(e);
		File fm = new File(e+"-manipulated");
		FileInputStream fis = new FileInputStream(f);
		FileOutputStream fos = new FileOutputStream(fm);

		boolean hicetrampas = false;

		int c = 0;
		int b = 0;


		while ( (b=fis.read()) >= 0 ) {

			if ( ! hicetrampas && ( (c++ % 7) == 0 ) ) {
			       	b = (b+1) % Byte.MAX_VALUE ;
				hicetrampas = true;
			}
			fos.write(b);
		}
		fis.close();
		fos.close();

		f.delete();
		fm.renameTo(f);

		if (hicetrampas) System.out.println("Malory: hehehe!!!");	
		return hicetrampas;

	}
   
   // Sintaxi: java Sobre arxiu_a_xifrar arxiu_xifrat arxiu_desxifrat
   // arxiu_a_xifrar = args[0]
   // arxiu_xifrat = args[1]
   // arxiu_desxifrat = args[2]
   
   public static void main(String[] args)
     {
	try
	  {

	     if (args.length < 2 ) { 
		     System.out.println("Sintaxi:\n"+
				"java Sobre arxiu_a_xifrar arxiu_xifrat arxiu_desxifrat");
		     		System.exit(1);
	     }
   
	     
	     String fileorg = args[0];
	     String filecrypt = args[1];
	     String filedecrypt =args[2];

	     java.util.Random r = new java.util.Random();

	     File trans = new File("trans");

	     // crear clave parejas (RSA)
	     
	     KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
	     
	     KeyPair myPair = kpg.genKeyPair();
	     KeyPair otherPair = kpg.genKeyPair();

	     // sender
	     
	     MySobre sobre = new MySobre(
			     fileorg,
			     filecrypt,
			     otherPair.getPublic(),
			     myPair.getPrivate()
	     );


	     ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(trans));
	     oos.writeObject(sobre.getDadesSobre());
	     oos.close();

	     // send it via email!!!
	     // ===>
	     // malory
	     if ( r.nextInt(3) == 0 ) manipulate(filecrypt);
	     // <===
	     // get it via email!!!
	     
	     ObjectInputStream ois = new ObjectInputStream(new FileInputStream(trans));
	     DadesSobre ds = (DadesSobre)ois.readObject();
	     ois.close();

	     //receiver

	     MySobre newsobre = new MySobre( 
    			     ds,
    			     filedecrypt,
			     myPair.getPublic(),
			     otherPair.getPrivate()
	     );
	     System.out.println("signatura corecta");

	     trans.delete();

	  }
	catch(Exception e)
	  {
	     e.printStackTrace();
	  }
     }
}

