How to encrypt and decrypt a String in Apex using the Crypto class

Please provide apex code examples to encrypt and decrypt a string using all of the supported encryption algorithms (AES128, AES192, and AES256). I searched for clear and concise code examples on this site, but found none (if you know of an answer with all said examples, please point me that way). I have tried to encrypt a String with the Crypto class, but was unsuccessful. Instead of debugging my code, I think it will be more helpful to look at some working examples.

Thanks 😀


The below wiki gives good set of examples for crypto classes

A sample scenario from above article

// Generate an AES key for the purpose of this sample. 
// Normally this key should be stored in a protected custom setting 
// or an encrypted field on a custom object
Blob cryptoKey = Crypto.generateAesKey(256);

// Generate the data to be encrypted.
 Blob data = Blob.valueOf('Test data to encrypted');
// Encrypt the data and have generate the initialization vector
Blob encryptedData = Crypto.encryptWithManagedIV('AES256', cryptoKey, data);
// Decrypt the data - the first 16 bytes contain the initialization vector
 Blob decryptedData = Crypto.decryptWithManagedIV('AES256', cryptoKey, encryptedData);

// Decode the decrypted data for subsequent use
 String decryptedDataString = decryptedData.toString();

Here is below blog that points a use case of how to store once we encrypt data in sfdc

Basically there are two versions


Here SFDC itself handles vector generation


Here one needs to include vector also as parameter for encryption.

Source : Link , Question Author : edgartheunready , Answer Author : Community

Leave a Comment