Crypto Class

Provides methods for creating digests, message authentication codes, and signatures, as well as encrypting and decrypting information.

Namespace

System

Usage

The methods in the Crypto class can be used for securing content in Lightning Platform, or for integrating with external services such as Google or Amazon WebServices (AWS).

Encrypt and Decrypt Exceptions

The following exceptions can be thrown for these methods:
  • decrypt
  • encrypt
  • decryptWithManagedIV
  • encryptWithManagedIV
Exception Message Description
InvalidParameterValue Unable to parse initialization vector from encrypted data. Thrown if you're using managed initialization vectors, and the cipher text is less than 16 bytes.
InvalidParameterValue Invalid algorithm algoName. Must be AES128, AES192, or AES256. Thrown if the algorithm name isn't one of the valid values.
InvalidParameterValue Invalid private key. Must be size bytes. Thrown if size of the private key doesn't match the specified algorithm.
InvalidParameterValue Invalid initialization vector. Must be 16 bytes. Thrown if the initialization vector isn't 16 bytes.
InvalidParameterValue Invalid data. Input data is size bytes, which exceeds the limit of 1048576 bytes. Thrown if the data is greater than 1 MB. For decryption, 1048608 bytes are allowed for the initialization vector header, plus any additional padding the encryption added to align to block size.
NullPointerException Argument cannot be null. Thrown if one of the required method arguments is null.
SecurityException Given final block not properly padded. Thrown if the data isn't properly block-aligned or similar issues occur during encryption or decryption.
SecurityException Message Varies Thrown if something goes wrong during either encryption or decryption.

Crypto Methods

The following are methods for Crypto. All methods are static.

decrypt(algorithmName, privateKey, initializationVector, cipherText)

Decrypts the Blob cipherText using the specified algorithm, private key, and initialization vector. Use this method to decrypt blobs encrypted using a third party application or the encrypt method.

Signature

public static Blob decrypt(String algorithmName, Blob privateKey, Blob initializationVector, Blob cipherText)

Parameters

algorithmName
Type: String
privateKey
Type: Blob
initializationVector
Type: Blob
cipherText
Type: Blob

Return Value

Type: Blob

Usage

Valid values for algorithmName are:
  • AES128
  • AES192
  • AES256
These are all industry standard Advanced Encryption Standard (AES) algorithms with different size keys. They use cipher block chaining (CBC) and PKCS5 padding.

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

The initialization vector must be 128 bits (16 bytes.)

Example

Blob exampleIv = Blob.valueOf('Example of IV123');
Blob key = Crypto.generateAesKey(128);
Blob data = Blob.valueOf('Data to be encrypted');
Blob encrypted = Crypto.encrypt('AES128', key, exampleIv, data);

Blob decrypted = Crypto.decrypt('AES128', key, exampleIv, encrypted);
String decryptedString = decrypted.toString();
System.assertEquals('Data to be encrypted', decryptedString);

decryptWithManagedIV(algorithmName, privateKey, IVAndCipherText)

Decrypts the Blob IVAndCipherText using the specified algorithm and private key. Use this method to decrypt blobs encrypted using a third party application or the encryptWithManagedIV method.

Signature

public static Blob decryptWithManagedIV(String algorithmName, Blob privateKey, Blob IVAndCipherText)

Parameters

algorithmName
Type: String
privateKey
Type: Blob
IVAndCipherText
Type: Blob
The first 128 bits (16 bytes) of IVAndCipherText must contain the initialization vector.

Return Value

Type: Blob

Usage

Valid values for algorithmName are:
  • AES128
  • AES192
  • AES256
These are all industry standard Advanced Encryption Standard (AES) algorithms with different size keys. They use cipher block chaining (CBC) and PKCS5 padding.

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

Example

Blob key = Crypto.generateAesKey(128);
Blob data = Blob.valueOf('Data to be encrypted');
Blob encrypted = Crypto.encryptWithManagedIV('AES128', key, data);

Blob decrypted = Crypto.decryptWithManagedIV('AES128', key, encrypted);
String decryptedString = decrypted.toString();
System.assertEquals('Data to be encrypted', decryptedString);

encrypt(algorithmName, privateKey, initializationVector, clearText)

Encrypts the Blob clearText using the specified algorithm, private key and initialization vector. Use this method when you want to specify your own initialization vector.

Signature

public static Blob encrypt(String algorithmName, Blob privateKey, Blob initializationVector, Blob clearText)

Parameters

algorithmName
Type: String
privateKey
Type: Blob
initializationVector
Type: Blob
clearText
Type: Blob

Return Value

Type: Blob

Usage

The initialization vector must be 128 bits (16 bytes.) Use either a third-party application or the decrypt method to decrypt blobs encrypted using this method. Use the encryptWithManagedIV method if you want Salesforce to generate the initialization vector for you. It is stored as the first 128 bits (16 bytes) of the encrypted Blob.

Valid values for algorithmName are:
  • AES128
  • AES192
  • AES256
These are all industry standard Advanced Encryption Standard (AES) algorithms with different size keys. They use cipher block chaining (CBC) and PKCS5 padding.

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

Example

Blob exampleIv = Blob.valueOf('Example of IV123');
Blob key = Crypto.generateAesKey(128);
Blob data = Blob.valueOf('Data to be encrypted');
Blob encrypted = Crypto.encrypt('AES128', key, exampleIv, data);

Blob decrypted = Crypto.decrypt('AES128', key, exampleIv, encrypted);
String decryptedString = decrypted.toString();
System.assertEquals('Data to be encrypted', decryptedString);

encryptWithManagedIV(algorithmName, privateKey, clearText)

Encrypts the Blob clearText using the specified algorithm and private key. Use this method when you want Salesforce to generate the initialization vector for you.

Signature

public static Blob encryptWithManagedIV(String algorithmName, Blob privateKey, Blob clearText)

Parameters

algorithmName
Type: String
privateKey
Type: Blob
clearText
Type: Blob

Return Value

Type: Blob

Usage

The initialization vector is stored as the first 128 bits (16 bytes) of the encrypted Blob. Use either third-party applications or the decryptWithManagedIV method to decrypt blobs encrypted with this method. Use the encrypt method if you want to generate your own initialization vector.

Valid values for algorithmName are:
  • AES128
  • AES192
  • AES256
These are all industry standard Advanced Encryption Standard (AES) algorithms with different size keys. They use cipher block chaining (CBC) and PKCS5 padding.

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

Example

Blob key = Crypto.generateAesKey(128);
Blob data = Blob.valueOf('Data to be encrypted');
Blob encrypted = Crypto.encryptWithManagedIV('AES128', key, data);

Blob decrypted = Crypto.decryptWithManagedIV('AES128', key, encrypted);
String decryptedString = decrypted.toString();
System.assertEquals('Data to be encrypted', decryptedString);

generateAesKey(size)

Generates an Advanced Encryption Standard (AES) key.

Signature

public static Blob generateAesKey(Integer size)

Parameters

size
Type: Integer
The key's size in bits. Valid values are:
  • 128
  • 192
  • 256

Return Value

Type: Blob

Example

Blob key = Crypto.generateAesKey(128);

generateDigest(algorithmName, input)

Computes a secure, one-way hash digest based on the supplied input string and algorithm name.

Signature

public static Blob generateDigest(String algorithmName, Blob input)

Parameters

algorithmName
Type: String
Valid values for algorithmName are:
  • MD5
  • SHA1
  • SHA-256
  • SHA-512
input
Type: Blob

Return Value

Type: Blob

Example

Blob targetBlob = Blob.valueOf('ExampleMD5String');
Blob hash = Crypto.generateDigest('MD5', targetBlob);

generateMac(algorithmName, input, privateKey)

Computes a message authentication code (MAC) for the input string, using the private key and the specified algorithm.

Signature

public static Blob generateMac(String algorithmName, Blob input, Blob privateKey)

Parameters

algorithmName
Type: String
The valid values for algorithmName are:
  • hmacMD5
  • hmacSHA1
  • hmacSHA256
  • hmacSHA512
input
Type: Blob
privateKey
Type: Blob
The value of privateKey does not need to be in decoded form. The value cannot exceed 4 KB.

Return Value

Type: Blob

Example

String salt = String.valueOf(Crypto.getRandomInteger());
String key = 'key';
Blob data = crypto.generateMac('HmacSHA256',
Blob.valueOf(salt), Blob.valueOf(key));

getRandomInteger()

Returns a random Integer.

Signature

public static Integer getRandomInteger()

Return Value

Type: Integer

Example

Integer randomInt = Crypto.getRandomInteger();

getRandomLong()

Returns a random Long.

Signature

public static Long getRandomLong()

Return Value

Type: Long

Example

Long randomLong = Crypto.getRandomLong();

sign(algorithmName, input, privateKey)

Computes a unique digital signature for the input string, using the specified algorithm and the supplied private key.

Signature

public static Blob sign(String algorithmName, Blob input, Blob privateKey)

Parameters

algorithmName
Type: String
The algorithm name. The valid values for algorithmName are RSA-SHA1, RSA-SHA256, or RSA.

RSA-SHA1 is an RSA signature (with an asymmetric key pair) of a SHA1 hash.

RSA-SHA256 is an RSA signature of a SHA256 hash.

RSA is the same as RSA-SHA1.

input
Type: Blob
The data to sign.
privateKey
Type: Blob
The value of privateKey must be decoded using the EncodingUtilbase64Decode method, and should be in RSA's PKCS #8 (1.2) Private-Key Information Syntax Standard form. The value cannot exceed 4 KB.

Return Value

Type: Blob

Example

The following snippet shows how to call the sign method.

String algorithmName = 'RSA';
String key = '';
Blob privateKey = EncodingUtil.base64Decode(key);
Blob input = Blob.valueOf('12345qwerty');
Crypto.sign(algorithmName, input, privateKey);

signWithCertificate(algorithmName, input, certDevName)

Computes a unique digital signature for the input string, using the specified algorithm and the supplied certificate and key pair.

Signature

public static Blob signWithCertificate(String algorithmName, Blob input, String certDevName)

Parameters

algorithmName
Type: String
The algorithm name. The valid values for algorithmName are RSA-SHA1, RSA-SHA256, or RSA.

RSA-SHA1 is an RSA signature (with an asymmetric key pair) of a SHA1 hash.

RSA-SHA256 is an RSA signature of a SHA256 hash.

RSA is the same as RSA-SHA1.

input
Type: Blob
The data to sign.
certDevName
Type: String
The Unique Name for a certificate stored in the Salesforce organization’s Certificate and Key Management page to use for signing.

To access the Certificate and Key Management page from Setup, enter Certificate and Key Management in the Quick Find box, then select Certificate and Key Management.

Return Value

Type: Blob

Example

The following snippet is an example of the method for signing the content referenced by data.

Blob data = Blob.valueOf('12345qwerty');
System.Crypto.signWithCertificate('RSA-SHA256', data, 'signingCert'); 

signXML(algorithmName, node, idAttributeName, certDevName)

Envelops the signature into an XML document.

Signature

public Void signXML(String algorithmName, Dom.XmlNode node, String idAttributeName, String certDevName)

Parameters

algorithmName
Type: String
The algorithm name. Valid names are RSA-SHA1, RSA-SHA256, or RSA.

RSA-SHA1 is an RSA signature (with an asymmetric key pair) of an SHA1 hash.

RSA-SHA256 is an RSA signature of an SHA256 hash.

RSA is the same as RSA-SHA1.

node
Type: Dom.XmlNode
The XML node to sign and insert the signature into.
idAttributeName
Type: String
The full name (including the namespace) of the attribute on the node (XmlNode) to use as the reference ID. If null, this method uses the ID attribute on the node. If there is no ID attribute, Salesforce generates a new ID and adds it to the node.
certDevName
Type: String
The unique name for a certificate stored in the Salesforce org’s Certificate and Key Management page to use for signing.

To access the Certificate and Key Management page from Setup, enter Certificate and Key Management in the Quick Find box, then select Certificate and Key Management.

Return Value

Type: void

Example

The following is an example declaration and initialization.

Dom.Document doc = new dom.Document();
doc.load(...);
System.Crypto.signXml('RSA-SHA256', doc.getRootElement(), null, 'signingCert'); 
return doc.toXmlString();  

signXML(algorithmName, node, idAttributeName, certDevName, refChild)

Inserts the signature envelope before the specified child node.

Signature

public static void signXml(String algorithmName, Dom.XmlNode node, String idAttributeName, String certDevName, Dom.XmlNode refChild)

Parameters

algorithmName
Type: String
The RSA encryption algorithm name. Valid names are RSA-SHA1, RSA-SHA256, or RSA.

RSA-SHA1 is an RSA signature (with an asymmetric key pair) of an SHA1 hash.

RSA-SHA256 is an RSA signature of an SHA256 hash.

RSA is the same as RSA-SHA1.

node
Type: Dom.XmlNode
The XML node to sign and insert the signature into.
idAttributeName
Type: String
The full name (including the namespace) of the attribute on the node (XmlNode) to use as the reference ID. If null, this method uses the ID attribute on the node. If there is no ID attribute, Salesforce generates a new ID and adds it to the node.
certDevName
Type: String
The unique name for a certificate stored in the Salesforce org’s Certificate and Key Management page to use for signing.

To access the Certificate and Key Management page from Setup, enter Certificate and Key Management in the Quick Find box, then select Certificate and Key Management.

refChild
Dom.XmlNode
The XML node before which to insert the signature. If refChild is null, the signature is added at the end.

Return Value

Type: Void