25 ส.ค. 2554

TripDESEncrypter

import java.awt.Desktop;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.KeySpec;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Scanner;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class TripDESEncrypter {
	private static final String PBEWITH_MD5AND_DES = "PBEWithMD5AndDES";
	private static final String DEFAULT_ENCODE = "UTF-8";
	private String SECRET_STRING;
	private String DATA;
	private String PATHDATA;

	public void setSECRET_STRING(String sECRET_STRING) {
		SECRET_STRING = sECRET_STRING;
	}
	private Cipher ecipher;
	private Cipher dcipher;

	public TripDESEncrypter() throws IOException{
		try {
			Runtime.getRuntime().exec("cmd /c cls");
		} catch (IOException e) {
			e.printStackTrace();
		}
		Scanner scanner = new Scanner (System.in);
		String pathintial = "data.txt";
		 PATHDATA = new File(pathintial).getAbsolutePath();
		 DATA = getDataInitial().trim();
		 if(DATA.equals("")){
			 System.out.println("No data in: "+PATHDATA);
			 Desktop desktop = null;
		 		if (Desktop.isDesktopSupported()) {
		 			desktop = Desktop.getDesktop();
		 		}
		 		try {
		 			desktop.open(new File(pathintial));
		 		} catch (IOException e) {}
		 }
		 System.out.println("Check data in: "+PATHDATA);
         System.out.print("Menu: 1.Encrypt String 2.Decrypt String 3.Exit:");
         int menu = 0 ;
         try {
        	 menu = scanner.nextInt();
		} catch (Exception e) {
			new TripDESEncrypter();
		}
         switch(menu){
         	case 1:EncryptInput();break;
         	case 2:DecryptInput();break;
         	default:System.exit(0);
         }
	}
	private void DecryptInput() throws IOException {
		Scanner scanner = new Scanner (System.in);
		System.out.print("Decrypt SECRET KEY: ");
		String secret = scanner.nextLine();
		System.out.print("Encode: 1:TIS-620 2.ISO-9002 3.UTF-8(Default) Other typing: ");
		String encode = "";
		int choose = 0;
		try {
			choose = scanner.nextInt();
				switch(choose){
		     	case 1:encode = "TIS-620";doTripDecrypt(secret, encode );
		     	case 2:encode = "ISO-9002";doTripDecrypt(secret, encode);
		     	case 3:encode = "UTF-8";doTripDecrypt(secret,encode );
		     	default:encode = "UTF-8";doTripDecrypt(secret,encode );
			}
		} catch (Exception e) {
			encode = scanner.nextLine();
			doTripDecrypt(secret, encode);
		}
	}
	private void doTripDecrypt(String secret,String encode){
		setSECRET_STRING(secret);
		InitTripProcess();
		String out = "";
		out+="SECRET KEY: "+secret;
		out+="\nString: "+decrypt(DATA,encode);
//		System.out.println(out);
		Date today;
		String output;
		SimpleDateFormat formatter;
		formatter = new SimpleDateFormat("dd MM yy HH-m-ss");
		long time = System.currentTimeMillis();
		today = new Date(time);
		output = formatter.format(today);
		Writetxtfile("Decrypt"+output,out);
	}
	private void EncryptInput() throws IOException{
		Scanner scanner = new Scanner (System.in);
		System.out.print("Encrypt SECRET KEY: ");
		String secret = scanner.nextLine();
		System.out.print("Encode: 1.TIS-620 2.ISO-9002 3.UTF-8(Default) Other typing: ");
		String encode = "";
		int choose = 0;
		try {
			choose = scanner.nextInt();
			switch(choose){
	     	case 1:encode = "TIS-620";doTripEncrypt(secret, encode );
	     	case 2:encode = "ISO-9002";doTripEncrypt(secret, encode);
	     	case 3:encode = "UTF-8";doTripEncrypt(secret,encode );
	     	default:encode = "UTF-8";doTripEncrypt(secret,encode );
		}
		} catch (Exception e) {
			encode = scanner.nextLine();
			doTripEncrypt(secret, encode);
		}
	}
	private void doTripEncrypt(String secret,String encode){
		setSECRET_STRING(secret);
		InitTripProcess();
		String out = "";
		out+="SECRET KEY: "+secret;
		out+="\nString: "+encrypt(DATA,encode);
//		System.out.println(out);
		Date today;
		String output;
		SimpleDateFormat formatter;
		formatter = new SimpleDateFormat("dd MM yy HH-m-ss");
		long time = System.currentTimeMillis();
		today = new Date(time);
		output = formatter.format(today);
		Writetxtfile("Encrypt"+output,out);
	}
	private void InitTripProcess(){
		try{
			byte[] salt = {
			(byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
			(byte)0x56, (byte)0x34, (byte)0xE3, (byte)0x03
		};
		int iterationCount = 19;
		
		KeySpec keySpec = new PBEKeySpec(SECRET_STRING.toCharArray(), salt, iterationCount);
		SecretKey key = SecretKeyFactory.getInstance(PBEWITH_MD5AND_DES).generateSecret(keySpec);
		
		ecipher = Cipher.getInstance(key.getAlgorithm());
		dcipher = Cipher.getInstance(key.getAlgorithm());
		
		AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
		
		ecipher.init(Cipher.ENCRYPT_MODE, key , paramSpec);
		dcipher.init(Cipher.DECRYPT_MODE, key , paramSpec);

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

	private String encryptData(String s,String encode){
		try{
			byte[] b = s.getBytes(encode);
			byte[] enc = ecipher.doFinal(b);
		return new BASE64Encoder().encode(enc);
		}catch(Exception e){
			System.out.println("Error Endode "+encode+" ");
			try {
				EncryptInput();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	private String decryptData(String s,String encode){
		try{
			byte[] dec = new BASE64Decoder().decodeBuffer(s);
			byte[] b = dcipher.doFinal(dec);
			return new String(b,encode);
		}catch(Exception e){
			System.out.println("Error Endode "+encode+" ");
			try {
				DecryptInput();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}
	public void Writetxtfile(String filename,String str){
		if(filename.lastIndexOf(".txt")<0)
			filename="C:/Temp/Trip/"+filename+".txt";
		else
			filename="C:/Temp/Trip/"+filename;
		File trip = new File("C:/Temp/Trip");
		if(!trip.exists())
			trip.mkdirs();
    	FileWriter write = null;
		try {
			write = new FileWriter(filename);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
        try {
            write.write(str);
        } catch (FileNotFoundException e) {
        	e.printStackTrace();
        } catch (IOException e) {
        	e.printStackTrace();
        } finally {
            try {
                if (write != null) {
                	String finishfile = new File(filename).getAbsolutePath();
                	System.out.println("File to: "+finishfile);
                	write.close();
            		Desktop desktop = null;
            		if (Desktop.isDesktopSupported()) {
            			desktop = Desktop.getDesktop();
            		}
            		try {
            			desktop.open(new File(finishfile));
            		} catch (IOException e) {}
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
			new TripDESEncrypter();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public String getDataInitial(){
		StringBuffer result = new StringBuffer();
		 try{
			  FileInputStream fstream = new FileInputStream(PATHDATA);
			  DataInputStream in = new DataInputStream(fstream);
			  BufferedReader br = new BufferedReader(new InputStreamReader(in));
			  String strLine;
			  while ((strLine = br.readLine()) != null)   {
				  result.append(strLine);
			  }
				  in.close();
		    }catch (Exception e){
			  System.err.println("Error: " + e.getMessage());
			  System.exit(0);
			  }
			return result.toString();
	  }
	public String encrypt(String s){
		return encryptData(s,DEFAULT_ENCODE);
	}

	public String encrypt(String s,String encode){
		return encryptData(s,encode);
	}

	public String decrypt(String s){
		return decryptData(s,DEFAULT_ENCODE);
	}

	public String decrypt(String s,String encode){
		return decryptData(s,encode);
	}
	public static void main(String[] args) {
		try {
			new TripDESEncrypter();
		} catch (IOException e) {
			System.exit(0);
		}
	}
}