Tag Archives: Encrypt

Encrypt and Decrypt a String in Apex

Sample Code:

//Data to encrypt
Blob data = Blob.valueOf('Biswajeet Samal');
//Generate an AES key for the encryption. 
Blob cryptoValue = Crypto.generateAesKey(256);
//Encrypt the data
Blob encryptedData = Crypto.encryptWithManagedIV('AES256', cryptoValue, data);
//Decrypt the data - the first 16 bytes contain the initialization vector
Blob decryptedData = Crypto.decryptWithManagedIV('AES256', cryptoValue, encryptedData);
//Get decrypted data 
String decryptedDataString = decryptedData.toString();
System.debug(decryptedDataString);