aes加密在linux下會生成隨機key的解決辦法

魔豆發表於2016-10-09

直接貼程式碼了:

package com.segerp.tygl.weixin.common;

import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;

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

/**
 * 字串加密解密類
 * */
public class AesStrUtils {

    //private static final String SECRETKEY = "F0D7432CFDB62E21F8DF70CF47F06948";
    private static final String SECRETKEY = "BB6D93B3BD1FB173DDADB78748E0C6D3";

    public static void main(String[] args) throws Exception {
        // 加密
        String encryptResultStr = encryptStr("123", SECRETKEY);
        System.out.println("加密後:" + encryptResultStr);
        // 解密
        String decryptResultStr = decryptStr(encryptResultStr, SECRETKEY);
        System.out.println("解密後:" + decryptResultStr);

    }

    /**
     * 字串加密
     * 
     * @param srcStr
     *            加密字串
     * @param password
     *            加密金鑰
     * */
    public static String encryptStr(String srcStr, String password) {
        byte[] encryptResult = encryptData_AES(srcStr, password);
        String encryptResultStr = parseByte2HexStr(encryptResult);
        return encryptResultStr;
    }

    /**
     * 字串解密
     * 
     * @param srcStr
     *            解密字串
     * @param password
     *            加密金鑰
     * */
    public static String decryptStr(String srcStr, String password) {
        String returnValue = "";
        try {
            byte[] decryptFrom = parseHexStr2Byte(srcStr);
            byte[] decryptResult = decryptData_AES(decryptFrom, password);
            returnValue = new String(decryptResult, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return returnValue;
    }

    /**
     * 將二進位制轉換成16進位制
     * 
     * @param buf
     * @return
     */
    private static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 加密
     * 
     * @param content
     *            需要加密的內容
     * @param password
     *            加密密碼
     * @return
     */
    private static byte[] encryptData_AES(String content, String password) {
        try {
            //SecretKey secretKey = getKey(password);
            //byte[] enCodeFormat = secretKey.getEncoded();
            byte[] enCodeFormat = parseHexStr2Byte(password);
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");// 建立密碼器
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
            byte[] result = cipher.doFinal(byteContent);
            return result; // 加密
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 將16進位制轉換為二進位制
     * 
     * @param hexStr
     * @return
     */
    private static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
                    16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    /**
     * 生成指定字串的金鑰
     * 
     * @param secret  要生成金鑰的字元
     * @return secretKey 生成後的金鑰
     * @throws GeneralSecurityException
     */
    private static SecretKey getKey(String secret) throws GeneralSecurityException {
        try {           
              KeyGenerator _generator = KeyGenerator.getInstance("AES");  
              SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");  
              secureRandom.setSeed(secret.getBytes());  
              _generator.init(128,secureRandom);  
              return _generator.generateKey();  
          }  catch (Exception e) {  
               throw new RuntimeException("初始化金鑰出現異常");  
          }  
    }

    /**
     * 解密
     * 
     * @param content
     *            待解密內容
     * @param password
     *            解密金鑰
     * @return
     */
    private static byte[] decryptData_AES(byte[] content, String password) {
        try {
            //SecretKey secretKey = getKey(password);
            //byte[] enCodeFormat = secretKey.getEncoded();
            byte[] enCodeFormat = parseHexStr2Byte(password);
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");// 建立密碼器
            cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
            byte[] result = cipher.doFinal(content);
            return result; // 加密
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}

 

getKey這個方法後來沒有用了,因為網上提供的方法在linux下生成的種子還是會一直變
我就在想,反正要提供種子,不如在windows環境下,生成一個key,把生成的key做為種子,反正生成的key是不會變的
在linux環境下試了一下,確實可以,搞定!

相關文章