背景:現在有個需求是寫個介面接收其他系統的已加密資訊,需要解密再處理
已知加密演算法是:
AES/ECB/pkcs5padding/128位資料塊/密碼:12345678901234567890123456789012/ base64輸出 / utf8字符集
在在線解密網站上測驗:

這個配置可以正常解密
然后我開始嘗試java實作
主要代碼如下:
private static String key = "12345678901234567890123456789012";
private static String mode = "AES/ECB/PKCS5Padding";
public static String decodeMsg(String msg) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException, InvalidKeySpecException {
Cipher cipher = Cipher.getInstance(mode);
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key));// 初始化
byte[] msgbyte = base64(msg);
byte[] result = cipher.doFinal(msgbyte);
return new String(result); // 解密
}
public static byte[] base64(String str) {
return Base64.getDecoder().decode(str);
}
private static SecretKeySpec getSecretKey(final String password) {
//回傳生成指定演算法密鑰生成器的 KeyGenerator 物件
KeyGenerator kg = null;
try {
kg = KeyGenerator.getInstance("AES");
byte[] keyBytes = password.getBytes();
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(keyBytes);
//AES 要求密鑰長度為 128
kg.init(128, secureRandom);
//生成一個密鑰
SecretKey secretKey = kg.generateKey();
return new SecretKeySpec(secretKey.getEncoded(), "AES");// 轉換為AES專用密鑰
} catch (NoSuchAlgorithmException ex) {
//Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
測驗時一直在拋出例外
javax.crypto.BadPaddingException: Given final block not properly padded
本人第一次搞AES,對于這塊不太熟悉,實在是看不出問題在哪。
uj5u.com熱心網友回復:
樓主怎么解決這個問題的 ,我也是出現了一樣的錯誤,請教!轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/284496.html
標籤:Java相關
上一篇:【急】java 生成檔案指定了GBK,可仍然生成了UTF-8格式的檔案
下一篇:jetty 9 的JSTL 錯誤 java.nio.channels.CancelledKeyException org.apache.jasper.Jaspe