一、前言
由于與其它系統(tǒng)接口對接,需要進(jìn)行加密處理。
對接系統(tǒng)采用AES加密方式,作為接收方獲取加密內(nèi)容,通過AES解密拿到數(shù)據(jù)。
解密過程中遇到報(bào)錯如下:
java.security.InvalidKeyException: Invalid AES key length: 20 bytes
二、Invalid AES key length: 20 bytes的解決方法
出現(xiàn)此錯誤,主要原因是秘鑰長度不符合要求所導(dǎo)致的。
AES允許128位,192位或256位密鑰長度。 這也就意味著秘鑰只能是16,24或32個字節(jié)。
話不多說,代碼呈現(xiàn)如下:文章來源:http://www.zghlxwxcb.cn/news/detail-735243.html
public class AESUtil {
private static final String AES = "AES";
private static final String UTF8 = "UTF-8";
private static final String CIPHERALGORITHM = "AES/ECB/PKCS5Padding";
private static final String Key = "9!#95hsup*&$1zq79$%a";
/**
* AES加密
*
* @param content
* @return
* @throws Exception
*/
public static String encrypt(String content) {
try {
byte[] encodeFormat = Key.getBytes();
SecretKeySpec key = new SecretKeySpec(encodeFormat, AES);
// Cipher對象實(shí)際完成加密操作
Cipher cipher = Cipher.getInstance(CIPHERALGORITHM);
// 加密內(nèi)容進(jìn)行編碼
byte[] byteContent = content.getBytes(UTF8);
// 用密匙初始化Cipher對象
cipher.init(Cipher.ENCRYPT_MODE, key);
// 正式執(zhí)行加密操作
byte[] result = cipher.doFinal(byteContent);
return Hex.encodeHexString(result);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* AES解密
*
* @param contents
* @return
* @throws Exception
*/
public static String decrypt(String content) {
try {
// 密文使用Hex解碼
byte[] byteContent = Hex.decodeHex(content.toCharArray());
byte[] encodeFormat = Key.getBytes();
SecretKeySpec key = new SecretKeySpec(encodeFormat, AES);
// Cipher對象實(shí)際完成加密操作
Cipher cipher = Cipher.getInstance(AES);
// 用密匙初始化Cipher對象
cipher.init(Cipher.DECRYPT_MODE, key);
// 正式執(zhí)行解密操作
byte[] result = cipher.doFinal(byteContent);
return new String(result, UTF8);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
執(zhí)行報(bào)錯,因?yàn)?code>KEY的值是9!#95hsup*&$1zq79$%a,長度為20,如果長度修改成16,KEY值為9!#95hsup*&$1zq7,執(zhí)行就正常了。文章來源地址http://www.zghlxwxcb.cn/news/detail-735243.html
到了這里,關(guān)于AES解密報(bào)錯java.security.InvalidKeyException: Invalid AES key length: xx bytes的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!