【发布时间】:2012-07-21 08:40:24
【问题描述】:
我正在处理一个需要向用户发送验证链接的项目。因此使用 AES 加密对他的用户名进行了加密。我的代码工作正常,即加密和解密工作正常,但仅在我测试时在程序中工作。我加密了一个字符串,然后解密它。它在“本地”运行良好。
问题是,当我发送带有激活链接的电子邮件并单击它时,它给了我错误:
javax.crypto.BadPaddingException: Given final block not properly padded
我的代码如下图:
public class AES {
private static final String algo="AES";
private static final byte[] keyValue=
new byte[]{somekey};
private static Key generateKey() throws Exception{
Key key= new SecretKeySpec(keyValue, algo);
return key;
}
public static String encrypt(String email) throws Exception{
Key key=generateKey();
Cipher c=Cipher.getInstance(algo);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal=c.doFinal(email.getBytes());
String encryptedEmail= new BASE64Encoder().encode(encVal);
return encryptedEmail;
}
public static String decrypt(String encryptedEmail) throws Exception{
Key key=generateKey();
Cipher c=Cipher.getInstance(algo);
c.init(Cipher.DECRYPT_MODE, key);
byte[] decodeEmail= new BASE64Decoder().decodeBuffer(encryptedEmail);
byte[] decodedEmail=c.doFinal(decodeEmail);
String decryptedEmail= new String(decodedEmail);
return decryptedEmail;
}
}
【问题讨论】:
-
有人可以帮助我吗?求求你了,很紧急!
-
BadPaddingException被抛出每当算法的输入有任何问题(在你的情况下是密钥或密文)。您是否比较了 base 64 编码/解码的输出?您不应该使用内部 Sun 类,而是尝试使用 Bouncy Castle 或 Apache 库。 -
您解决了这个问题吗?如果是这样,您能否指出做了什么并接受或发布答案?
标签: java encryption aes