Menu
subscribe our youtube channel popup

Data Encryption in Salesforce Apex

Security is a major concern in today’s digital environment, particularly when handling sensitive data.  The cloud-based CRM platform Salesforce has strong solutions to help protect data while it’s in transit and at rest.  However, developers must take proactive steps to guarantee that sensitive data is shielded from unwanted access; data security is not simply about utilising Salesforce’s built-in features. We’ll go into great detail on Apex data encryption in this blog post, including how to use Salesforce’s Apex programming language to safely store and handle sensitive data. 

What is Data Encryption?

Data encryption is the process of implementing an encryption key and an algorithm to transform sensitive data into a format that is unreadable. The intention is to make sure that without the right decryption key, even if other people attempt to view the data, they will be unable to understand it. Data encryption helps protect information from threats like data breaches, hacking, and unauthorized access.

Why is Data Encryption Important in Apex?

Salesforce is frequently used to store sensitive client data such as personally identifiable information (PII), financial details, and proprietary information. If this data is not properly safeguarded, it may result in security breaches, loss of customer trust, and legal consequences. Apex developers must ensure that any sensitive data processed or stored is encrypted both during transit and at rest to prevent unwanted access.

How to Encrypt and Decrypt Data in Salesforce Apex

Salesforce uses AES (Advanced Encryption Standard) encryption in CBC (Cipher Block Chaining) mode with PKCS5 padding for encrypting data, supporting AES128, AES192, and AES256 key lengths. 

About Crypto class

Salesforce provides a class called Crypto that contains several methods to encrypt and decrypt data in Apex. Provides methods for creating digests, message authentication codes, and signatures, as well as encrypting and decrypting information.

Each method in this class supports a unique set of AES encryption algorithms, depending on its purpose. To confirm which algorithms are available for the action you want to do.

Crypto Methods:

1. Encryption and Decryption Methods

These methods are used for encrypting and decrypting data using symmetric keys.

a. encrypt(algorithmName, privateKey, initializationVector, clearText)

Purpose: Encrypts data using a symmetric key algorithm. Use this method when you want to specify your own initialization vector.

Parameters:

algorithmName: The encryption algorithm (e.g., AES128, AES192, AES256).

privateKey: Private key text. The length of privateKey must match the size required by algorithmName: 128 bits, 192 bits, or 256 bits, which is 16 bytes, 24 bytes, or 32 bytes, respectively. You can use a third-party application or the generateAesKey method to generate this key for you.

initializationVector: 128-bit initialization vector. The initialization vector must be 128 bits (16 bytes).

clearText: The data you want to encrypt.

Returns: Encrypted data as a Blob.

Example

public static void encryptData(){
            Blob exampleIv = Blob.valueOf('1234567890123456');
            Blob key = Crypto.generateAesKey(128);
            String data = 'Apex Hours a Salesforce Learning Site where you can found certification preparation tips, Salesforce best practices and Salesforce related news and features.';
            Blob encrypted = Crypto.encrypt('AES128', key, exampleIv, Blob.valueOf(data));
            System.debug('The Encrypted data is ' + EncodingUtil.base64Encode(encrypted));
            return;
        }

This Apex method encrypts a string using the AES-128 encryption algorithm. It generates a 128-bit key, uses a fixed initialization vector (exampleIv), and encrypts the input data. The encrypted result is then converted to a Base64-encoded string and printed in the debug logs.

In the Below screenshot, you can find the encrypted data for the given Input.

b. decrypt(algorithmName, privateKey, initializationVector, encryptedText)

Purpose: Decrypts data encrypted with a symmetric key. Use this method to decrypt blobs encrypted using a third-party application or the encrypt method.

Parameters:

algorithmName: The encryption algorithm used (e.g., AES128, AES192, AES256).

privateKey: Private key text. The length of privateKey must match the size required by algorithmName: 128 bits, 192 bits, or 256 bits, which is 16 bytes, 24 bytes, or 32 bytes, respectively. You can use a third-party application or the generateAesKey method to generate this key.

initializationVector: Any 128 bit (16 byte) string to provide the initial state to this method. The initialization vector must be 128 bits (16 bytes.)

encryptedText: The encrypted data as a Blob or the Content you want to decrypt

Returns: Decrypted data as a Blob.

public static void encryptAndDecryptData(){
            Blob exampleIv = Blob.valueOf('1234567890123456');
            Blob key = Crypto.generateAesKey(128);
            String data = 'Apex Hours a Salesforce Learning Site where you can found certification preparation tips, Salesforce best practices and Salesforce related news and features.';
            Blob encrypted = Crypto.encrypt('AES128', key, exampleIv, Blob.valueOf(data));
            System.debug('The Encrypted data is ' + EncodingUtil.base64Encode(encrypted));
                
            Blob decrypted = Crypto.decrypt('AES128', key, exampleIv, encrypted);
            String decryptedString = decrypted.toString();
            System.debug('The Decrypted data is ' + decryptedString);
 
            return;
        }

To decrypt the encrypted data, you must pass the same initialization vector (IV), key, and algorithm type that were used during the encryption process.

2. Hashing Methods

These methods generate hash values for data integrity and security.

a. generateDigest(algorithmName, input)

Purpose: Generates a hash (digest) of the input data.

Parameters:

Purpose: Generates a hash (digest) of the input data.

algorithmName: The hashing algorithm (e.g., MD5, SHA1, SHA256, SHA512).

input: The data to hash (as a Blob).

Returns: Hash value as a Blob.

 public static void testGenerateDigest(){
            Blob targetBlob = Blob.valueOf('ExampleMD5String');
            Blob hash = Crypto.generateDigest('MD5', targetBlob);
            String result = EncodingUtil.base64Encode(hash);
            System.debug('Value: ' + result);
        }
b. generateMac(algorithmName, input, privateKey)

Purpose: Generates a Message Authentication Code (MAC) using a keyed-hash algorithm.

Parameters:

algorithmName: The MAC algorithm (e.g., hmacMD5, hmacSHA1, hmacSHA256 and hmacSHA512).

input: The data to hash (as a Blob).

privateKey: The secret key for the MAC.

Returns: MAC value as a Blob.

public static void generateMAC() {
            String salt = String.valueOf(Crypto.getRandomInteger());
            String key = 'key';
            Blob data = crypto.generateMac('HmacSHA256', 
                                            Blob.valueOf(salt), 
                                            Blob.valueOf(key));
            System.debug('Generated MAC: ');        
            System.debug(EncodingUtil.base64Encode(data));
        }

3. Key Generation Methods

These methods generate cryptographic keys for encryption and decryption.

a. generateAesKey(size)

Purpose: Generates a symmetric key for AES encryption.

Parameters:

size: The key size in bits (e.g., 128, 192, 256).

Returns: A Blob containing the generated key.
Example: 

public static void generateAESKey() {
          Blob key = Crypto.generateAesKey(128);
          System.debug('Generated AES Key: ');
          String strKey = EncodingUtil.base64Encode(key);
          System.debug(strKey);
          
        }
b. getRandomInteger()

Purpose: This method can help us to generate the random integer Number. 

Parameters:

There are no parameters required for this method.
Returns: It returns the integer value.

public static void generateRandomNumber() {
                  Integer i1 = Crypto.getRandomInteger();
                  Integer i2 = Crypto.getRandomInteger();
                  System.debug('Integer 1: ' + i1);
                  System.debug('Integer 2: ' + i2);
            }

Encrypt and Decrypt Exceptions

The following exceptions can be thrown for these methods:

  • decrypt
  • encrypt
  • decryptWithManagedIV
  • encryptWithManagedIV
ExceptionMessageDescription
InvalidParameterValueUnable to parse the initialization vector from encrypted data.Thrown if you’re using managed initialization vectors, and the cipher text is less than 16 bytes.
Invalid algorithm algoName. Must be one of AES128, AES192, or AES256.Thrown if the algorithm name isn’t one of the valid values.
Invalid private key. Must be size bytes.Thrown if the size of the private key doesn’t match the specified algorithm.
Invalid initialization vector. Must be 16 bytes.Thrown if the initialization vector isn’t 16 bytes.
Invalid data. Input data is size bytes, which exceeds the limit of 1,048,576 bytes.Thrown if the data is greater than 1 MB. For decryption, 1,048,608 bytes are allowed for the initialization vector header, plus any additional padding the encryption added to align to block size.
NullPointerExceptionArgument can’t be null.Thrown if one of the required method arguments is null.
SecurityExceptionGiven final block isn’t properly padded.Thrown if the data isn’t properly block-aligned or similar issues occur during encryption or decryption.
SecurityExceptionMessage VariesThrown if something goes wrong during either encryption or decryption.

This blog covered the basics of encryption and decryption using the Crypto class in Salesforce Apex. For more details, check out the link https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_classes_restful_crypto.htm#apex_System_Crypto_getRandomInteger and stay tuned for the next blog. Happy coding! 🙂

Satyam parasa
Satyam parasa

Satyam Parasa is a Salesforce and Mobile application developer. Passionate about learning new technologies, he is the founder of Flutterant.com, where he shares his knowledge and insights.

Articles: 37

Leave a Reply

Your email address will not be published. Required fields are marked *