Tạo tâp tin Properties chứ thông số cấu hình ứng dúng nếu có password thì sẽ mã hóa nó lại thành một tập tin key. | Java Create File Properties and Encrypted Password.

Đây là cũng một lớp do mình tạo trong lúc nghâm cứu rãnh rỗi, lớp này cho phép tạo một tập tin lưu lại các thông số của ứng dụng vào một tập tin Properties, để khí ứng dụng chạy thì sẽ sử dụng lại các thông số trong tập tin này, ngoài ra có thể thiết lập mã hóa nếu các thông số ứng dụng cần bảo mật ví dụ như password chẳng hạn. Bạn này thấy hữu ích thì cut về xài nha.

Cryptography Utilities
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package citi_support_tools;

import java.io.File;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.util.Properties;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 *
 * @author bnson
 */
public class CryptoUtils {

    private static final String AES = "AES";
    private String KEY_FILE = "properties/sec.key";
    private String PWD_FILE = "properties/sec.properties";
    String clearPwd;   

    public CryptoUtils() {
       
    }

    //-----------------------
    public void setPass(String pass) {
        this.clearPwd = pass;
        Properties p1 = new Properties();
        p1.put("user","Real");
        String encryptedPwd;
        try {
            encryptedPwd = CryptoUtils.encrypt(clearPwd, new File(KEY_FILE));
            p1.put("pwd", encryptedPwd);
            p1.store(new FileWriter(PWD_FILE), "");
        } catch (GeneralSecurityException ex) {
            Logger.getLogger(CryptoUtils.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(CryptoUtils.class.getName()).log(Level.SEVERE, null, ex);
        }


    }
   
    public String getPass() {
        String tmp = "";
        Properties p2 = new Properties();
        String encryptedPwd;
        try {
            p2.load(new FileReader(PWD_FILE));
            encryptedPwd = p2.getProperty("pwd");
            tmp = CryptoUtils.decrypt(encryptedPwd, new File(KEY_FILE));
            //System.out.println(encryptedPwd);
            //System.out.println(CryptoUtils.decrypt(encryptedPwd, new File(KEY_FILE)));           
        } catch (GeneralSecurityException ex) {
            Logger.getLogger(CryptoUtils.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(CryptoUtils.class.getName()).log(Level.SEVERE, null, ex);
        }

        return tmp;
    }
    //-----------------------
    public void setAccountFPT(String host, String port, String user ,String pass, String pathFolder) {
        this.clearPwd = pass;
        Properties p1 = new Properties();
        p1.put("host", host);
        p1.put("port", port);
        p1.put("userAcc",user);
        p1.put("path",pathFolder);
        String encryptedPwd;
        try {
            encryptedPwd = CryptoUtils.encrypt(clearPwd, new File(KEY_FILE.replace("sec.key","sec_001.key")));
            p1.put("pwdAcc", encryptedPwd);
            p1.store(new FileWriter(PWD_FILE.replace("sec.properties","sec_001.properties")), "");
        } catch (GeneralSecurityException ex) {
            Logger.getLogger(CryptoUtils.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(CryptoUtils.class.getName()).log(Level.SEVERE, null, ex);
        }

    }   
   
    public String getAccountFPT() {
        String tmp = "";
        Properties p2 = new Properties();
        String encryptedPwd;
        try {
            p2.load(new FileReader(PWD_FILE.replace("sec.properties","sec_001.properties")));
            encryptedPwd = p2.getProperty("pwdAcc");
            if (!"".equals(p2.getProperty("host")) && p2.getProperty("host") != null) {
                tmp = p2.getProperty("host")+ "`"+ p2.getProperty("port") + "`" + p2.getProperty("userAcc") + "`" + p2.getProperty("path") + "`" + CryptoUtils.decrypt(encryptedPwd, new File(KEY_FILE.replace("sec.key","sec_001.key")));
            }
            //System.out.println(encryptedPwd);
            //System.out.println(CryptoUtils.decrypt(encryptedPwd, new File(KEY_FILE)));           
        } catch (GeneralSecurityException ex) {
            Logger.getLogger(CryptoUtils.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(CryptoUtils.class.getName()).log(Level.SEVERE, null, ex);
        }

        return tmp;
    }   
   
    //-----------------------
    public void setMail(String smtpServer, String from, String to, String cc, String authen_account, String authen_pass) {
        this.clearPwd = authen_pass;
       
        Properties p1 = new Properties();
        p1.put("smtpServer", smtpServer);
        p1.put("from",from);
        p1.put("to",to);
        p1.put("cc",cc);
        p1.put("authen_account",authen_account);
       
        String encryptedPwd;
       
       
        try {
            encryptedPwd = CryptoUtils.encrypt(clearPwd, new File(KEY_FILE.replace("sec.key","sec_002.key")));
            p1.put("pwdAcc", encryptedPwd);
            p1.store(new FileWriter(PWD_FILE.replace("sec.properties","sec_002.properties")), "");
        } catch (GeneralSecurityException ex) {
            Logger.getLogger(CryptoUtils.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(CryptoUtils.class.getName()).log(Level.SEVERE, null, ex);
        }

    }   
   
    public String getMail() {
        String tmp = "";
        Properties p2 = new Properties();
        String encryptedPwd;
        try {
            p2.load(new FileReader(PWD_FILE.replace("sec.properties","sec_002.properties")));
            encryptedPwd = p2.getProperty("pwdAcc");
            if (!"".equals(p2.getProperty("smtpServer")) && p2.getProperty("smtpServer") != null) {
                tmp = p2.getProperty("smtpServer")+ "`"
                        + p2.getProperty("from") + "`"
                        + p2.getProperty("to") + "`"
                        + p2.getProperty("cc") + "`"
                        + p2.getProperty("authen_account") + "`"
                        + CryptoUtils.decrypt(encryptedPwd, new File(KEY_FILE.replace("sec.key","sec_002.key")));
            }
            //System.out.println(encryptedPwd);
            //System.out.println(CryptoUtils.decrypt(encryptedPwd, new File(KEY_FILE)));           
        } catch (GeneralSecurityException ex) {
            Logger.getLogger(CryptoUtils.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(CryptoUtils.class.getName()).log(Level.SEVERE, null, ex);
        }

        return tmp;
    }       
   
    //-----------------------
   
    /**
     * encrypt a value and generate a keyfile if the keyfile is not found then a
     * new one is created
     *
     * @throws GeneralSecurityException
     * @throws IOException
     */
    private static String encrypt(String value, File keyFile)
            throws GeneralSecurityException, IOException {
       
        System.out.println("File encrypte: " + keyFile.getAbsolutePath());
        if (!keyFile.exists()) {
           
            KeyGenerator keyGen = KeyGenerator.getInstance(CryptoUtils.AES);
            keyGen.init(128);
            SecretKey sk = keyGen.generateKey();
            FileWriter fw = new FileWriter(keyFile);
            fw.write(byteArrayToHexString(sk.getEncoded()));
            fw.flush();
            fw.close();
        }

        SecretKeySpec sks = getSecretKeySpec(keyFile);
        Cipher cipher = Cipher.getInstance(CryptoUtils.AES);
        cipher.init(Cipher.ENCRYPT_MODE, sks, cipher.getParameters());
        byte[] encrypted = cipher.doFinal(value.getBytes());
        return byteArrayToHexString(encrypted);
    }

    /**
     * decrypt a value
     *
     * @throws GeneralSecurityException
     * @throws IOException
     */
    private static String decrypt(String message, File keyFile)
            throws GeneralSecurityException, IOException {
        SecretKeySpec sks = getSecretKeySpec(keyFile);
        Cipher cipher = Cipher.getInstance(CryptoUtils.AES);
        cipher.init(Cipher.DECRYPT_MODE, sks);
        byte[] decrypted = cipher.doFinal(hexStringToByteArray(message));
        return new String(decrypted);
    }

    private static SecretKeySpec getSecretKeySpec(File keyFile)
            throws NoSuchAlgorithmException, IOException {
        byte[] key = readKeyFile(keyFile);
        SecretKeySpec sks = new SecretKeySpec(key, CryptoUtils.AES);
        return sks;
    }

    private static byte[] readKeyFile(File keyFile)
            throws FileNotFoundException {
        Scanner scanner =
                new Scanner(keyFile).useDelimiter("\\Z");
        String keyValue = scanner.next();
        scanner.close();
        return hexStringToByteArray(keyValue);
    }

    private static String byteArrayToHexString(byte[] b) {
        StringBuilder sb = new StringBuilder(b.length * 2);
        for (int i = 0; i < b.length; i++) {
            int v = b[i] & 0xff;
            if (v < 16) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(v));
        }
        return sb.toString().toUpperCase();
    }

    private static byte[] hexStringToByteArray(String s) {
        byte[] b = new byte[s.length() / 2];
        for (int i = 0; i < b.length; i++) {
            int index = i * 2;
            int v = Integer.parseInt(s.substring(index, index + 2), 16);
            b[i] = (byte) v;
        }
        return b;
    }
}







No comments:

Post a Comment