.
此時就一定要使用如下代碼步驟 :
1.SecureRandom的key定下來.
SecureRandom 實現完全隨操作系統本身的內部狀態,除非調用方在調用 getInstance 方法之後又調用了 setSeed 方法;
該實現在 windows 上每次生成的 key 都相同,但是在 solaris 或部分 linux 系統上則不同.
public static SecretKey getKey(String strKey) { try { KeyGenerator _generator = KeyGenerator.getInstance( "AES" ); SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" ); secureRandom.setSeed(strKey.getBytes()); _generator.init(128,secureRandom); return _generator.generateKey(); } catch (Exception e) { throw new RuntimeException( " 初始化密鑰出現異常 " ); } }
2. 16進制轉換為2進制 互轉
* 因為加密后的byte數組是不能強制轉換成字符串的,
* 換言之:字符串和byte數組在這種情況下不是互逆的;
* 要避免這種情況,我們需要做一些修訂,可以考慮將二進制數據轉換成十六進制表示
3. BASE64加解密
這個原因和2有點類似,仿佛有點多余,也許能省下這一步.
4. 如果不這么做
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
at chb.test.crypto.AESUtils.crypt(AESUtils.java:386)
at chb.test.crypto.AESUtils.AesDecrypt(AESUtils.java:254)
at chb.test.crypto.AESUtils.main(AESUtils.java:40)
而我自己遇上的情況比這更糟,同樣的windows環境,
用apache的httppost發送加密報文在tomcat服務端進行解密就會報以上異常,
但是用java原生態的UrlConnection發送加密報文在tomcat服務端進行解密一切正常.
可能是apache對發送的流填充模式不同吧@@!
代碼示例
package com.testdemo.validate.endecrypt; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; public class AESTool { private final static String encoding = "UTF-8"; /** * AES加密 * * @param content * @param password * @return */ public static String encryptAES(String content, String password) { byte[] encryptResult = encrypt(content, password); String encryptResultStr = parseByte2HexStr(encryptResult); // BASE64位加密 encryptResultStr = encryptBASE64(encryptResultStr); return encryptResultStr; } /** * AES解密 * * @param encryptResultStr * @param password * @return */ public static String decryptAES(String encryptResultStr, String password) { // BASE64位解密 String decrpt = decryptBASE64(encryptResultStr); byte[] decryptFrom = parseHexStr2Byte(decrpt); byte[] decryptResult = decrypt(decryptFrom, password); return new String(decryptResult); } /** * 加密字符串 */ public static String encryptBASE64(String str) { BASE64Encoder base64encoder = new BASE64Encoder(); String result = str; if (str != null && str.length() > 0) { try { byte[] encodeByte = str.getBytes(encoding); result = base64encoder.encode(encodeByte); } catch (Exception e) { e.printStackTrace(); } } //base64加密超過一定長度會自動換行 需要去除換行符 return result.replaceAll("\r\n", "").replaceAll("\r", "").replaceAll("\n", ""); } /** * 解密字符串 */ public static String decryptBASE64(String str) { BASE64Decoder base64decoder = new BASE64Decoder(); try { byte[] encodeByte = base64decoder.decodeBuffer(str); return new String(encodeByte); } catch (IOException e) { e.printStackTrace(); return str; } } /** * 加密 * * @param content 需要加密的內容 * @param password 加密密碼 * @return */ private static byte[] encrypt(String content, String password) { try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); //防止linux下 隨機生成key SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" ); secureRandom.setSeed(password.getBytes()); kgen.init(128, secureRandom); //kgen.init(128, new SecureRandom(password.getBytes())); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); 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 (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return null; } /**解密 * @param content 待解密內容 * @param password 解密密鑰 * @return */ private static byte[] decrypt(byte[] content, String password) { try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); //防止linux下 隨機生成key SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" ); secureRandom.setSeed(password.getBytes()); kgen.init(128, secureRandom); //kgen.init(128, new SecureRandom(password.getBytes())); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); 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 (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return null; } /**將二進制轉換成16進制 * @param buf * @return */ public 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(); } /**將16進制轉換為二進制 * @param hexStr * @return */ public 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; } public static void test1() { String content = "test"; String password = "12345678"; // 加密 System.out.println("加密前:" + content); String encryptResult = encryptAES(content, password); System.out.println("加密后: "+ encryptResult); // 解密 System.out.println("解密前: "+ encryptResult); String decryptResult = decryptAES(encryptResult, password); System.out.println("解密后:" + new String(decryptResult)); } public static void main(String[] args) { test1(); } }
http://konglx.iteye.com/blog/954085
http://www.cnblogs.com/freeliver54/archive/2011/10/08/2202136.html java源碼下載
