大坑!使用SecureRandom默認的加密方式即SHA1PRNG生成的密碼有誤,即使使用相同的password來生成,不同runtime或時刻生成的隨機密碼也有可能不同,造成的錯誤為javax.crypto.BadPaddingException: pad block corrupted。即key不同!!!
可用的方法:
1 public static String encrypt(final String plainMessage, 2 final String symKeyHex) { 3 final byte[] symKeyData = DatatypeConverter.parseHexBinary(symKeyHex); 4 5 final byte[] encodedMessage = plainMessage.getBytes(Charset 6 .forName("UTF-8")); 7 try { 8 final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 9 final int blockSize = cipher.getBlockSize(); 10 11 // create the key 12 final SecretKeySpec symKey = new SecretKeySpec(symKeyData, "AES"); 13 14 // generate random IV using block size (possibly create a method for 15 // this) 16 final byte[] ivData = new byte[blockSize]; 17 final SecureRandom rnd = SecureRandom.getInstance("SHA1PRNG"); 18 rnd.nextBytes(ivData); 19 final IvParameterSpec iv = new IvParameterSpec(ivData); 20 21 cipher.init(Cipher.ENCRYPT_MODE, symKey, iv); 22 23 final byte[] encryptedMessage = cipher.doFinal(encodedMessage); 24 25 // concatenate IV and encrypted message 26 final byte[] ivAndEncryptedMessage = new byte[ivData.length 27 + encryptedMessage.length]; 28 System.arraycopy(ivData, 0, ivAndEncryptedMessage, 0, blockSize); 29 System.arraycopy(encryptedMessage, 0, ivAndEncryptedMessage, 30 blockSize, encryptedMessage.length); 31 32 final String ivAndEncryptedMessageBase64 = DatatypeConverter 33 .printBase64Binary(ivAndEncryptedMessage); 34 35 return ivAndEncryptedMessageBase64; 36 } catch (InvalidKeyException e) { 37 throw new IllegalArgumentException( 38 "key argument does not contain a valid AES key"); 39 } catch (GeneralSecurityException e) { 40 throw new IllegalStateException( 41 "Unexpected exception during encryption", e); 42 } 43 } 44 45 public static String decrypt(final String ivAndEncryptedMessageBase64, 46 final String symKeyHex) { 47 final byte[] symKeyData = DatatypeConverter.parseHexBinary(symKeyHex); 48 49 final byte[] ivAndEncryptedMessage = DatatypeConverter 50 .parseBase64Binary(ivAndEncryptedMessageBase64); 51 try { 52 final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 53 final int blockSize = cipher.getBlockSize(); 54 55 // create the key 56 final SecretKeySpec symKey = new SecretKeySpec(symKeyData, "AES"); 57 58 // retrieve random IV from start of the received message 59 final byte[] ivData = new byte[blockSize]; 60 System.arraycopy(ivAndEncryptedMessage, 0, ivData, 0, blockSize); 61 final IvParameterSpec iv = new IvParameterSpec(ivData); 62 63 // retrieve the encrypted message itself 64 final byte[] encryptedMessage = new byte[ivAndEncryptedMessage.length 65 - blockSize]; 66 System.arraycopy(ivAndEncryptedMessage, blockSize, 67 encryptedMessage, 0, encryptedMessage.length); 68 69 cipher.init(Cipher.DECRYPT_MODE, symKey, iv); 70 71 final byte[] encodedMessage = cipher.doFinal(encryptedMessage); 72 73 // concatenate IV and encrypted message 74 final String message = new String(encodedMessage, 75 Charset.forName("UTF-8")); 76 77 return message; 78 } catch (InvalidKeyException e) { 79 throw new IllegalArgumentException( 80 "key argument does not contain a valid AES key"); 81 } catch (BadPaddingException e) { 82 // you'd better know about padding oracle attacks 83 return null; 84 } catch (GeneralSecurityException e) { 85 throw new IllegalStateException( 86 "Unexpected exception during decryption", e); 87 } 88 }
1 Usage: 2 3 String plain = "Zaphod's just zis guy, ya knöw?"; 4 String encrypted = encrypt(plain, "000102030405060708090A0B0C0D0E0F"); 5 System.out.println(encrypted); 6 String decrypted = decrypt(encrypted, "000102030405060708090A0B0C0D0E0F"); 7 if (decrypted != null && decrypted.equals(plain)) { 8 System.out.println("Hey! " + decrypted); 9 } else { 10 System.out.println("Bummer!"); 11 }
一)什么是AES?
高級加密標准(英語:Advanced Encryption Standard,縮寫:AES),是一種區塊加密標准。這個標准用來替代原先的DES,已經被多方分析且廣為全世界所使用。
那么為什么原來的DES會被取代呢,,原因就在於其使用56位密鑰,比較容易被破解。而AES可以使用128、192、和256位密鑰,並且用128位分組加密和解密數據,相對來說安全很多。完善的加密算法在理論上是無法破解的,除非使用窮盡法。使用窮盡法破解密鑰長度在128位以上的加密數據是不現實的,僅存在理論上的可能性。統計顯示,即使使用目前世界上運算速度最快的計算機,窮盡128位密鑰也要花上幾十億年的時間,更不用說去破解采用256位密鑰長度的AES算法了。
目前世界上還有組織在研究如何攻破AES這堵堅厚的牆,但是因為破解時間太長,AES得到保障,但是所用的時間不斷縮小。隨着計算機計算速度的增快,新算法的出現,AES遭到的攻擊只會越來越猛烈,不會停止的。
AES現在廣泛用於金融財務、在線交易、無線通信、數字存儲等領域,經受了最嚴格的考驗,但說不定哪天就會步DES的后塵。
二)JAES加密
先來一段加密代碼,說明請看注釋:
1 /** 2 * AES加密字符串 3 * 4 * @param content 5 * 需要被加密的字符串 6 * @param password 7 * 加密需要的密碼 8 * @return 密文 9 */ 10 public static byte[] encrypt(String content, String password) { 11 try { 12 KeyGenerator kgen = KeyGenerator.getInstance("AES");// 創建AES的Key生產者 13 14 kgen.init(128, new SecureRandom(password.getBytes()));// 利用用戶密碼作為隨機數初始化出 15 // 128位的key生產者 16 //加密沒關系,SecureRandom是生成安全隨機數序列,password.getBytes()是種子,只要種子相同,序列就一樣,所以解密只要有password就行 17 18 SecretKey secretKey = kgen.generateKey();// 根據用戶密碼,生成一個密鑰 19 20 byte[] enCodeFormat = secretKey.getEncoded();// 返回基本編碼格式的密鑰,如果此密鑰不支持編碼,則返回 21 // null。 22 23 SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");// 轉換為AES專用密鑰 24 25 Cipher cipher = Cipher.getInstance("AES");// 創建密碼器 26 27 byte[] byteContent = content.getBytes("utf-8"); 28 29 cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化為加密模式的密碼器 30 31 byte[] result = cipher.doFinal(byteContent);// 加密 32 33 return result; 34 35 } catch (NoSuchPaddingException e) { 36 e.printStackTrace(); 37 } catch (NoSuchAlgorithmException e) { 38 e.printStackTrace(); 39 } catch (UnsupportedEncodingException e) { 40 e.printStackTrace(); 41 } catch (InvalidKeyException e) { 42 e.printStackTrace(); 43 } catch (IllegalBlockSizeException e) { 44 e.printStackTrace(); 45 } catch (BadPaddingException e) { 46 e.printStackTrace(); 47 } 48 return null; 49 }
三)AES解密
1 /** 2 * 解密AES加密過的字符串 3 * 4 * @param content 5 * AES加密過過的內容 6 * @param password 7 * 加密時的密碼 8 * @return 明文 9 */ 10 public static byte[] decrypt(byte[] content, String password) { 11 try { 12 KeyGenerator kgen = KeyGenerator.getInstance("AES");// 創建AES的Key生產者 13 kgen.init(128, new SecureRandom(password.getBytes())); 14 SecretKey secretKey = kgen.generateKey();// 根據用戶密碼,生成一個密鑰 15 byte[] enCodeFormat = secretKey.getEncoded();// 返回基本編碼格式的密鑰 16 SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");// 轉換為AES專用密鑰 17 Cipher cipher = Cipher.getInstance("AES");// 創建密碼器 18 cipher.init(Cipher.DECRYPT_MODE, key);// 初始化為解密模式的密碼器 19 byte[] result = cipher.doFinal(content); 20 return result; // 明文 21 22 } catch (NoSuchAlgorithmException e) { 23 e.printStackTrace(); 24 } catch (NoSuchPaddingException e) { 25 e.printStackTrace(); 26 } catch (InvalidKeyException e) { 27 e.printStackTrace(); 28 } catch (IllegalBlockSizeException e) { 29 e.printStackTrace(); 30 } catch (BadPaddingException e) { 31 e.printStackTrace(); 32 } 33 return null; 34 }
四)測試
1 public static void main(String[] args) { 2 String content = "美女,約嗎?"; 3 String password = "123"; 4 System.out.println("加密之前:" + content); 5 6 // 加密 7 byte[] encrypt = AesTest.encrypt(content, password); 8 System.out.println("加密后的內容:" + new String(encrypt)); 9 10 // 解密 11 byte[] decrypt = AesTest.decrypt(encrypt, password); 12 System.out.println("解密后的內容:" + new String(decrypt)); 13 }
輸出結果:
加密之前:美女,約嗎?
加密后的內容:P�d�g�K�3�g�����,Ꝏ?U納�
解密后的內容:美女,約嗎?
可見,如果直接輸出解密后的內容是一個亂碼。我們需要把它的進制轉換一下。
五)進制轉換
進制轉換的工具類:
1 /** 2 * 進制轉換工具類 3 * @author tanjierong 4 * 5 */ 6 public class ParseSystemUtil { 7 8 /**將二進制轉換成16進制 9 * @param buf 10 * @return 11 */ 12 public static String parseByte2HexStr(byte buf[]) { 13 StringBuffer sb = new StringBuffer(); 14 for (int i = 0; i < buf.length; i++) { 15 String hex = Integer.toHexString(buf[i] & 0xFF); 16 if (hex.length() == 1) { 17 hex = '0' + hex; 18 } 19 sb.append(hex.toUpperCase()); 20 } 21 return sb.toString(); 22 } 23 24 /**將16進制轉換為二進制 25 * @param hexStr 26 * @return 27 */ 28 public static byte[] parseHexStr2Byte(String hexStr) { 29 if (hexStr.length() < 1) 30 return null; 31 byte[] result = new byte[hexStr.length()/2]; 32 for (int i = 0;i< hexStr.length()/2; i++) { 33 int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16); 34 int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16); 35 result[i] = (byte) (high * 16 + low); 36 } 37 return result; 38 } 39 }
六)重新編寫測試
1 public static void main(String[] args) { 2 String content = "美女,約嗎?"; 3 String password = "123"; 4 System.out.println("加密之前:" + content); 5 // 加密 6 byte[] encrypt = AesTest.encrypt(content, password); 7 System.out.println("加密后的內容:" + new String(encrypt)); 8 9 //如果想要加密內容不顯示亂碼,可以先將密文轉換為16進制 10 String hexStrResult = ParseSystemUtil.parseByte2HexStr(encrypt); 11 System.out.println("16進制的密文:" + hexStrResult); 12 13 //如果的到的是16進制密文,別忘了先轉為2進制再解密 14 byte[] twoStrResult = ParseSystemUtil.parseHexStr2Byte(hexStrResult); 15 16 // 解密 17 byte[] decrypt = AesTest.decrypt(encrypt, password); 18 System.out.println("解密后的內容:" + new String(decrypt)); 19 }
輸出內容:
加密之前:美女,約嗎?
加密后的內容:P�d�g�K�3�g�����,Ꝏ?U納�
16進制的密文:50FE6401E867A34BD533FE67BB85EDABFED62CEA9D8E3F5516E7B48D01F21A5F
解密后的內容:美女,約嗎?