gpt4 book ai didi

Java AES 解密异常 : javax. crypto.BadPaddingException:

转载 作者:行者123 更新时间:2023-11-30 01:41:53 32 4
gpt4 key购买 nike

    public static String encrypt(String strToEncrypt) {
SecureRandom secureRandom = new SecureRandom();
byte[] key = new byte[16];
secureRandom.nextBytes(key);
if (strToEncrypt != null) {
try {
IvParameterSpec ivspec = new IvParameterSpec(key);
SecretKeySpec keySpec = new SecretKeySpec(Constants.secretKey.getBytes(Constants.UTF_8), Constants.AES);
Cipher cipher = Cipher.getInstance(Constants.AES_CBC_PKCS5PADDING);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivspec);
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
} catch (Exception ex) {
LOGGER.error(CommonUtil.exceptionErrorPrefixSuffix("Encryption Exception in DoEncryption::encrypt", ex));
}
}
return null;
}

public static String decrypt(String id) throws UnsupportedEncodingException {
String decryptedId = null;
SecureRandom secureRandom = new SecureRandom();
byte[] key = new byte[16];
secureRandom.nextBytes(key);
SecretKeySpec keySpec = new SecretKeySpec(Constants.secretKey.getBytes(Constants.UTF_8),Constants.AES);
byte[] decodedCiphertext = Base64.getDecoder().decode(id);
try {
IvParameterSpec ivspec = new IvParameterSpec(key);
Cipher cipher = Cipher.getInstance(Constants.AES_CBC_PKCS5PADDING);
cipher.init(Cipher.DECRYPT_MODE, keySpec , ivspec);
byte[] original = cipher.doFinal(decodedCiphertext);
decryptedId = new String(original);
return decryptedId;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}

加密工作正常。但在解密时它会抛出异常。

javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption. at cipher.doFinal(decodedCiphertext);

提前致谢。

最佳答案

这里的问题是您在加密和解密方法中随机生成 key 。但由于您使用的是 AES 算法(对称算法),因此您应该在加密和解密时保持相同的 key 。

关于Java AES 解密异常 : javax. crypto.BadPaddingException:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59646316/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com