I am working on a project where I need to send verification link to user. So encrypted his username using AES encrytion. My code works fine, i.e, encryption and decrytpion are working fine but only in the program when I tested it. I encrypted a string and then decrypted it. It works fine ‘locally’.
The problem is, when I send email with activation link and click on it, it gives me error:
javax.crypto.BadPaddingException: Given final block not properly padded
My code is as shown below:
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;
}
}
I got it to run using the Base64 encoder/decoder of Bouncy Castle libraries, no problem at all. Check your input/output and use a valid base 64 encoder/decoder, not a Sun internal one with unspecified input/output.
Warning: as you use unspecified character encoding it will use the platform specific one, so your input/output may be different on separate systems. Try and use Charset.forName(“UTF8”) for the most compatible character encoding (in the String constructor and
toBytesmethod).