AES中的填充异常错误

时间:2012-07-21 08:40:24

标签: java encryption aes

我正在开展一个项目,我需要向用户发送验证链接。因此使用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;
    }

}

2 个答案:

答案 0 :(得分:2)

我使用Bouncy Castle库的Base64编码器/解码器运行它,完全没问题。检查您的输入/输出并使用有效的base 64编码器/解码器,而不是具有未指定输入/输出的Sun内部编码器/解码器。

警告:当您使用未指定的字符编码时,它将使用特定于平台的字符编码,因此您的输入/输出可能在不同的系统上有所不同。尝试使用Charset.forName(“UTF8”)进行最兼容的字符编码(在String构造函数和toBytes方法中)。

答案 1 :(得分:0)

您的代码似乎没有在加密或解密时设置填充。最好在两端显式设置填充。您似乎也没有设置模式,需要再次明确地完成。

我建议将“AES / CBC / PKCS5Padding”作为一个明显的选择。

相关问题