I'm creating community site and storing the password in cookies in the form of encryption. Now I've to decrypt that password. but decryption is not working. getting below error.

System.SecurityException: Given final block not properly padded Class.System.Crypto.decryptWithManagedIV: line 60, column 1

Apex class code:

public PageReference directlogin(){ 
    Cookie getPasswd = ApexPages.currentPage().getCookies().get('password');
    String decryptedPassword= null;
    if(getPasswd !=null){
        Blob cryptoKey = Crypto.generateAesKey(256);
        Blob datac = EncodingUtil.base64Decode(getPasswd.getValue());
            Blob decryptedData = Crypto.decryptWithManagedIV('AES256', cryptoKey, datac); // here error throwing
            decryptedPassword = decryptedData.toString();
        }catch(Exception e){
    return null;

1 Answer 1


You're generating a random key every time the method is called. In order for the decryption to be successful, you need to use the same key instead. You should store this key either in a custom setting or elsewhere. Do not store the key in a cookie, since it would be visible to the user.

  • you are really great to capture the error. Appreciate you. Thank you.
    – user29314
    Dec 14, 2017 at 9:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .