import java.io.*; 
import java.security.*; 
import javax.crypto.*; 
import sun.misc.*;
import javax.swing.*;


public class JCE_3DES
	{	
		public static void main(String args[]) throws Exception
			{ 
				Object[] option={"Encrypt","Decrypt"};
				String selectedAction;
				while(true)
					{	selectedAction = (String)JOptionPane.showInputDialog(null,"Select:","3DES",JOptionPane.QUESTION_MESSAGE,null,option,option[0]);
						if (selectedAction!=null) break;
					}
				
				
						
				Security.addProvider(new com.sun.crypto.provider.SunJCE());
				
				Cipher cipher=Cipher.getInstance("DESEDE/ECB/PKCS5Padding"); 
								
				Key key; 
				
				try
					{ ObjectInputStream in=new ObjectInputStream(new FileInputStream("3des.key")); 
						key=(Key)in.readObject(); 
						in.close();
					}
				catch(FileNotFoundException fnfe) 
					{ KeyGenerator generator= KeyGenerator.getInstance("DESEDE"); 

					generator.init(new SecureRandom()); 
						key=generator.generateKey();
						
						ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("3des.key")); 
						out.writeObject(key); 
						out.close(); 
					} 
				
				
				
				if(selectedAction.equals("Encrypt")) 
						{ 
							cipher.init(Cipher.ENCRYPT_MODE,key); 
							
							String text=null;
							while(true)
								{	text=new JOptionPane().showInputDialog("TESTO IN CHIARO");
									if (text!=null) break;
								};
							
							cipher.init(Cipher.ENCRYPT_MODE,key); 
							byte[] stringBytes=text.getBytes("UTF8"); 
							byte[] raw=cipher.doFinal(stringBytes); 
							BASE64Encoder encoder = new BASE64Encoder(); 
							String base64 = encoder.encode(raw); 
							
							new JOptionPane().showMessageDialog(null,"TESTO IN CHIARO: "+text+"\nLunghezza chiave 3DES [byte]: "+key.getEncoded().length+"\nChiave 3DES [RAW]: "+key.getEncoded()+"\nTESTO CIFRATO: "+base64);
							System.out.println("TESTO CIFRATO: "+base64);
						} 

				else 
						{ cipher.init(Cipher.DECRYPT_MODE,key); 
							
							String text=null;
							while(true)
								{	text=new JOptionPane().showInputDialog("TESTO CIFRATO:");
									if (text!=null) break;
								};
								
								
							BASE64Decoder decoder = new BASE64Decoder(); 
							byte[] raw = decoder.decodeBuffer(text); 
							byte[] stringBytes = cipher.doFinal(raw); 
							String result = new String(stringBytes,"UTF8"); 
							
							new JOptionPane().showMessageDialog(null,"TESTO CIFRATO: "+text+"\nLunghezza chiave 3DES [byte]: "+key.getEncoded().length+"\nChiave 3DES [RAW]: "+key.getEncoded()+"\nTESTO IN CHIARO: "+result);						
							System.out.println("TESTO IN CHIARO: "+result);
						} 
				
				System.exit(0);
			} 
	}

			

