[SalesForce] Error while encrypting

I am getting the below error while encrypting data.

System.InvalidParameterValueException: Invalid private key. Must be 16 bytes.: Class.System.Crypto.encryptWithManagedIV: line 50, column 1

Here is my code,

trigger Account_Encrypt_Trigger on Account (before insert,before update) {
    //Blob cryptoKey = Crypto.generateAesKey(128);
    Blob PrivateKey = EncodingUtil.base64Decode('Secretkey');
    Blob data = Blob.valueOf('testuser');
    Blob encryptedData = Crypto.encryptWithManagedIV('AES128',PrivateKey,data);
    Blob decryptedData = Crypto.decryptWithManagedIV('AES128',PrivateKey, encryptedData);
    String EncryptedDataString = EncodingUtil.base64Encode(encryptedData);
    String decryptedDataString = EncodingUtil.base64Encode(decryptedData);
    //String EncryptedDataString = encryptedData.toString();
    //String decryptedDataString = decryptedData.toString();
    system.debug('This is encrypted data   '+ EncryptedDataString);
    system.debug('This is decrypted Data   '+ decryptedDataString);
}

Could someone please help me fix this issue.

Best Answer

Check the Blob size that comes back from:

Blob PrivateKey = EncodingUtil.base64Decode('Secretkey');

It should be 16 bytes. With the sample code you have the length is only 6, but I suspect that is because you haven't put the actual key in the question.

In contrast, the following executes in anonymous apex:

Blob PrivateKey = Crypto.generateAesKey(128);
System.debug(PrivateKey.size());
System.assertEquals(16, PrivateKey.size());

Blob data = Blob.valueOf('testuser');
Blob encryptedData = Crypto.encryptWithManagedIV('AES128',PrivateKey,data);
Blob decryptedData = Crypto.decryptWithManagedIV('AES128',PrivateKey, encryptedData);
String EncryptedDataString = EncodingUtil.base64Encode(encryptedData);
String decryptedDataString = EncodingUtil.base64Encode(decryptedData);
//String EncryptedDataString = encryptedData.toString();
//String decryptedDataString = decryptedData.toString();
system.debug('This is encrypted data   '+ EncryptedDataString);
system.debug('This is decrypted Data   '+ decryptedDataString);

From the documentation for encryptWithManagedIV:

The initialization vector is stored as the first 128 bits (16 bytes) of the encrypted Blob.

Related Topic