Skip to content

Instantly share code, notes, and snippets.

@iamcryptoki
Last active September 19, 2020 03:42
Show Gist options
  • Save iamcryptoki/dae412eb88068dd27c01567422b599a6 to your computer and use it in GitHub Desktop.
Save iamcryptoki/dae412eb88068dd27c01567422b599a6 to your computer and use it in GitHub Desktop.
Encrypt and decrypt data in Salesforce using Apex Crypto class.
// Generate your own initialization vector
Blob iv = Blob.valueOf('Lorem ipsum dolor sit amet');
// Generate an AES key
Blob key = Crypto.generateAesKey(256);
// Generate the data to be encrypted
Blob data = Blob.valueof('Encrypt everything!');
// Encrypt the data
Blob encrypted = Crypto.encrypt('AES256', key, iv, data);
// Decrypt the data
Blob decrypted = Crypto.decrypt('AES256', key, iv, encrypted);
// Decode the decrypted data
String decryptedStringData = decrypted.toString();
// Check the authenticity of data
System.assertEquals('Encrypt everything!', decryptedStringData);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment