Newer Version Available
Crypto Class
Namespace
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).
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, check each method.
Encrypt and Decrypt Exceptions
- decrypt
- encrypt
- decryptWithManagedIV
- encryptWithManagedIV
| Exception | Message | Description |
|---|---|---|
| InvalidParameterValue | Unable 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. | |
| NullPointerException | Argument can’t be null. | Thrown if one of the required method arguments is null. |
| SecurityException | Given final block isn’t 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. |
These exceptions are a subset of the exceptions that can be thrown from the System namespace. Refer to Exception Class and Built-In Exceptions
The Crypto class uses AES / CBC / PKCS7 padding, which is vulnerable to a Padding Oracle attack. You can protect against a Padding Oracle attack using the Encrypt-then-MAC method. In this method, you encrypt the cipher text and MAC separately:
- For encryption, first encrypt the data with AES using one encryption key. Then, with a different encryption key, use the generateMac(algorithmName, input, privateKey) method to generate a message authentication code (MAC) for the cipher text. Append the MAC to the cipher text before sending it to its recipient.
- For decryption, start by checking the authenticity and integrity of the cipher text by using the verifyHMac(algorithmName, data, privateKey, macToVerify) method. If either the authenticity or integrity check fails, throw an exception and don’t decrypt the cipher text. The decryption of the cipher text must only happen in a second step, after the message authenticity and integrity has been verified.
Other Errors
Under rare conditions you may encounter the invalid_client error from the JSON Web Tokens (JWT) service.
| Error | Message | Description |
|---|---|---|
| invalid_client | The actual text varies, but describes the inability to validate the client credentials. | The JWT public certificate in the Salesforce Connected Application doesn’t appear to match the known private key. |
For Shield Platform Encryption, this error can happen when you use a custom JWT implementation that uses the P11363 format, and you also want to use the ECDSA-SHA256 algorithm. The solution is to specify the ECDSA-SHA256-PLAIN algorithm instead. The ECDSA-SHA256-PLAIN is available to the several sign() and verify() methods.
For example, in order to comply with your program requirements, you sign your token using the Elliptic Curve Digital Signature Algorithm (ECDSA) with the P-256 curve. This algorithm is in the P11363 format, so when you try to use Crypto.verify() using the ECDSA SHA256, you receive a response containing invalid_client. You change ECDSA-SHA256 to ECDSA-SHA256-PLAIN and the error is resolved.
Crypto Methods
The following are methods for Crypto. All methods are static.
decrypt(algorithmName, privateKey, initializationVector, cipherText)
Signature
public static Blob decrypt(String algorithmName, Blob privateKey, Blob initializationVector, Blob cipherText)
Parameters
- algorithmName
- Type: String
- Must be one of these industry-standard Advanced Encryption Standard (AES) algorithms
with different size keys. The algorithms use cipher block chaining (CBC) and PKCS7
padding.
- AES128
- AES192
- AES256
- privateKey
- Type: Blob
- 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
- Type: Blob
- Any 128 bit (16 byte) string to provide the initial state to this method. The initialization vector must be 128 bits (16 bytes.)
- cipherText
- Type: Blob
- The content to decrypt.
Example
You can use your preferred Salesforce development environment to test this function. Create the following Apex class:
1public class TestDecrypt {
2
3 public void testDecrypt(){
4 // 16-byte string
5 Blob exampleIv = Blob.valueOf('Example of IV123');
6 Blob key = Crypto.generateAesKey(128);
7 Blob data = Blob.valueOf('Data to be encrypted');
8 Blob encrypted = Crypto.encrypt('AES128', key, exampleIv, data);
9
10 Blob decrypted = Crypto.decrypt('AES128', key, exampleIv, encrypted);
11 String decryptedString = decrypted.toString();
12 System.debug('Decrypted Value: ' + decryptedString);
13 Assert.areEqual('Data to be encrypted', decryptedString, 'Error: not equal!');
14 return;
15 }
16 }To invoke this method, run the following:
1TestDecrypt td = new TestDecrypt();
2td.testDecrypt();decryptWithManagedIV(algorithmName, privateKey, IVAndCipherText)
Signature
public static Blob decryptWithManagedIV(String algorithmName, Blob privateKey, Blob IVAndCipherText)
Parameters
- algorithmName
- Type: String
- Must be one of these industry-standard Advanced Encryption Standard (AES) algorithms
with different size keys. The algorithms use cipher block chaining (CBC) and PKCS7
padding.
- AES128
- AES192
- AES256
- privateKey
- Type: Blob
- 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.
- IVAndCipherText
- Type: Blob
- A concatenation of the initialization vector and the encrypted text you want to decrypt. The initialization vector must be 128 bits (16 bytes), and be the first 16 bytes of IVAndCipherText.
Example
You can use your preferred Salesforce development environment to test this function. Create the following Apex class:
1public class TestDecryptWithManagedIV {
2
3 public void testDecryptWithManagedIV(){
4 String algorithmName = 'AES128';
5 // 16-byte IV
6 String exampleIV = 'Example of IV24';
7 Blob key = Crypto.generateAesKey(128);
8 Blob data = Blob.valueOf(exampleIV + 'Data to be encrypted');
9 Blob encrypted = Crypto.encryptWithManagedIV(algorithmName, key, data);
10 Blob decrypted = Crypto.decryptWithManagedIV(algorithmName, key, encrypted);
11 String decryptedString = decrypted.toString();
12 Assert.areEqual(exampleIV + 'Data to be encrypted', decryptedString, 'Error: the strings are not equal!');
13
14 }
15 }To invoke this method, run the following:
1TestDecryptWithManagedIV tdiv = new TestDecryptWithManagedIV();
2tdiv.testDecryptWithManagedIV();encrypt(algorithmName, privateKey, initializationVector, clearText)
Signature
public static Blob encrypt(String algorithmName, Blob privateKey, Blob initializationVector, Blob clearText)
Parameters
- algorithmName
- Type: String
- Algorithm for encrypting clearText.
- Must be one of these industry-standard Advanced Encryption Standard (AES) algorithms
with different size keys. The algorithms use cipher block chaining (CBC) and PKCS7
padding.
- AES128
- AES192
- AES256
- privateKey
- Type: Blob
- 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
- Type: Blob
- 128-bit initialization vector. The initialization vector must be 128 bits (16 bytes).
- clearText
- Type: Blob
- The content you want to encrypt.
Example
You can use your preferred Salesforce development environment to test this function. Create the following Apex class:
1public class TestEncrypt {
2
3 public void testEncrypt(){
4 Blob exampleIv = Blob.valueOf('Example of IV123');
5 Blob key = Crypto.generateAesKey(128);
6 Blob data = Blob.valueOf('Encryption Example Text.');
7 Blob encrypted = Crypto.encrypt('AES128', key, exampleIv, data);
8
9 Blob decrypted = Crypto.decrypt('AES128', key, exampleIv, encrypted);
10 String decryptedString = decrypted.toString();
11 Assert.areEqual('Encryption Example Text.', decryptedString, 'Error: the values are not equal!');
12 return;
13 }
14 }To invoke this method, run the following:
1TestEncrypt te = new TestEncrypt();
2te.testEncrypt();encryptWithManagedIV(algorithmName, privateKey, clearText)
Signature
public static Blob encryptWithManagedIV(String algorithmName, Blob privateKey, Blob clearText)
Parameters
- algorithmName
- Type: String
- The algorithm for encrypting clearText. Must be one of these
industry-standard Advanced Encryption Standard (AES) algorithms with different size
keys. The algorithms use cipher block chaining (CBC) and PKCS7 padding.
- AES128
- AES192
- AES256
- privateKey
- Type: Blob
- 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.
- clearText
- Type: Blob
- The content you want to encrypt.
Return Value
Type: Blob
Contains the encrypted contents of clearText.
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.
Example
You can use your preferred Salesforce development environment to test this function. Create the following Apex class:
1public class TestEncryptWithManagedIV {
2
3 public void testEncryptWithManagedIV(){
4 String algorithmName = 'AES128';
5 // 16-byte IV
6 String exampleIV = 'Example of IV24';
7 Blob key = Crypto.generateAesKey(128);
8 Blob data = Blob.valueOf(exampleIV + 'Data to be encrypted');
9 Blob encrypted = Crypto.encryptWithManagedIV(algorithmName, key, data);
10 Blob decrypted = Crypto.decryptWithManagedIV(algorithmName, key, encrypted);
11 String decryptedString = decrypted.toString();
12 Assert.areEqual(exampleIV + 'Data to be encrypted', decryptedString, 'Error: the strings are not equal!');
13
14 }
15 }To invoke this method, run the following:
1TestEncryptWithManagedIV teiv = new TestEncryptWithManagedIV();
2teiv.testEncryptWithManagedIV();generateAesKey(size)
Signature
public static Blob generateAesKey(Integer size)
Parameters
- size
- Type: Integer
- The key's size in bits. Valid values are:
- 128
- 192
- 256
Example
You can use your preferred Salesforce development environment to test this function. Create the following Apex class:
1public class TestGenerateAESKey {
2
3 public void testGenerateAESKey() {
4 Blob key = Crypto.generateAesKey(128);
5 System.debug('Generated AES Key: ');
6 String strKey = EncodingUtil.base64Encode(key);
7 System.debug(strKey);
8
9 }
10 }To invoke this method, run the following:
1TestGenerateAESKey tgaes = new TestGenerateAESKey();
2tgaes.testGenerateAESKey();generateDigest(algorithmName, input)
Signature
public static Blob generateDigest(String algorithmName, Blob input)
Parameters
Example
You can use your preferred Salesforce development environment to test this function. Create the following Apex class:
1public class TestGenerateDigest {
2
3 public void testGenerateDigest(){
4 Blob targetBlob = Blob.valueOf('ExampleMD5String');
5 Blob hash = Crypto.generateDigest('MD5', targetBlob);
6 String result = EncodingUtil.base64Encode(hash);
7 System.debug('Value: ' + result);
8 }
9 }To invoke this method, run the following:
1TestGenerateDigest tgd = new TestGenerateDigest();
2tgd.testGenerateDigest();generateMac(algorithmName, input, privateKey)
Signature
public static Blob generateMac(String algorithmName, Blob input, Blob privateKey)
Parameters
- algorithmName
- Type: String
- These are valid values for algorithmName.
- hmacMD5
- hmacSHA1
- hmacSHA256
- hmacSHA512
- input
- Type: Blob
- The content for which you want to generate the MAC.
- privateKey
- Type: Blob
- The key to use to generate the MAC. You may supply a private key that has been encoded using Base64 encoding. However if you do, then you must also supply the Base64-encoded private key when verifying the MAC using the verifyHMac method. The value of privateKey can’t exceed 4 KB.
Example
You can use your preferred Salesforce development environment to test this function. Create the following Apex class:
1public class TestGenerateMAC {
2
3 public void testGenerateMAC() {
4 String salt = String.valueOf(Crypto.getRandomInteger());
5 String key = 'key';
6 Blob data = crypto.generateMac('HmacSHA256',
7 Blob.valueOf(salt),
8 Blob.valueOf(key));
9 System.debug('Generated MAC: ');
10 System.debug(EncodingUtil.base64Encode(data));
11 }
12 }To invoke this method, run the following:
1TestGenerateMAC tgm = new TestGenerateMAC();
2tgm.testGenerateMAC();getRandomInteger()
Signature
public static Integer getRandomInteger()
Return Value
Type: Integer
Returns a random 4-byte integer. Salesforce invokes the java.security.SecureRandom api to generate this number. For information on how the number is generated, see java.security.SecureRandom.
Example
You can use your preferred Salesforce development environment to exercise this function. Create the following Apex class:
1public class TestGetRandomInteger {
2
3 public void testGetRandomInteger() {
4 Integer i1 = Crypto.getRandomInteger();
5 Integer i2 = Crypto.getRandomInteger();
6 System.debug('Integer 1: ' + i1);
7 System.debug('Integer 2: ' + i2);
8 Assert.areNotEqual(i1, i2, 'Sorry, those aren’t random!');
9 //This is just an example. This is not a true test of randomness
10 }
11 }To invoke this method, run the following:
1TestGetRandomInteger tri = new TestGetRandomInteger();
2tri.testGetRandomInteger();getRandomLong()
Signature
public static Long getRandomLong()
Return Value
Type: Long
Returns a random 8-byte long. Salesforce invokes the java.security.SecureRandom api to generate this number. For information on how the number is generated, see java.security.SecureRandom.
Example
You can use your preferred Salesforce development environment to exercise this function. Create the following Apex class:
1public class TestGetRandomLong {
2
3 public void testGetRandomLong() {
4 Long L1 = Crypto.getRandomLong();
5 Long L2 = Crypto.getRandomLong();
6 System.debug('Long 1: ' + L1);
7 System.debug('Long 2: ' + L2);
8 Assert.areNotEqual(L1, L2, 'Sorry, not random!');
9 //This is just an example. This is not a true test of randomness
10 }
11 }To invoke this method, run the following:
1TestGetRandomLong trl = new TestGetRandomLong();
2trl.testGetRandomLong();sign(algorithmName, input, privateKey)
Signature
public static Blob sign(String algorithmName, Blob input, Blob privateKey)
Parameters
- algorithmName
- Type: String
- These are valid values for algorithmName.
- RSA: the same as RSA-SHA1.
- RSA-SHA1: an RSA signature (with an asymmetric key pair) of an SHA1 hash.
- RSA-SHA256: an RSA signature of an SHA256 hash.
- RSA-SHA384: an RSA signature of an SHA384 hash.
- RSA-SHA512: an RSA signature of an SHA512 hash.
- ECDSA-SHA256: an ECDSA signature of an SHA256 hash.
- ECDSA-SHA256-PLAIN: an ECDSA signature of an SHA256 hash (P1363 format) .
- ECDSA-SHA384: an ECDSA signature of an SHA384 hash.
- ECDSA-SHA512: an ECDSA signature of an SHA512 hash.
- input
- Type: Blob
- The data to sign.
- privateKey
- Type: Blob
- The key to use for signing. 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 can’t exceed 4 KB.
Example
You can use your preferred Salesforce development environment to test this function. To run it correctly, you need a PKCS8 private key. At your terminal, use openssl to create one. First, create the key. Then convert it to PKCS8:
1$ openssl genrsa -out myprivatekey.pem 1024
2$ openssl pkey -in myprivatekey.pem -out myprivatekey.pkcs8.pemAfter you create the PKCS8 compatible key, you decode just the key portion of the text (without the BEGIN PRIVATE KEY or END PRIVATE KEY lines) for the privateKey parameter.
1public class TestSign {
2
3 public void testSign() {
4 Blob input = Blob.valueOf('Some text.');
5 String algorithmName = 'RSA';
6 String rawKey = '<text value of your pkcs8 private key>';
7
8 //no BEGIN PRIVATE KEY or END PRIVATE KEY header/footer !
9 Blob privateKey = EncodingUtil.base64Decode(rawKey);
10 System.debug(privateKey);
11 Blob signedKey = Crypto.sign(algorithmName, input, privateKey);
12
13 }
14 }To invoke this method, run the following:
1TestSign ts = new TestSign();
2ts.testSign();signWithCertificate(algorithmName, input, certDevName)
Signature
public static Blob signWithCertificate(String algorithmName, Blob input, String certDevName)
Parameters
- algorithmName
- Type: String
- These are valid values for algorithmName.
- RSA: the same as RSA-SHA1.
- RSA-SHA1: an RSA signature (with an asymmetric key pair) of an SHA1 hash.
- RSA-SHA256: an RSA signature of an SHA256 hash.
- RSA-SHA384: an RSA signature of an SHA384 hash.
- RSA-SHA512: an RSA signature of an SHA512 hash.
- ECDSA-SHA256: an ECDSA signature of an SHA256 hash.
- ECDSA-SHA256-PLAIN: an ECDSA signature of an SHA256 hash (P1363 format) .
- ECDSA-SHA384: an ECDSA signature of an SHA384 hash.
- ECDSA-SHA512: an ECDSA signature of an SHA512 hash.
- input
- Type: Blob
- The data to sign.
- certDevName
- Type: String
- The value listed in the Unique Name field 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.
Example
You can use your preferred Salesforce development environment to test this function. Create the following Apex class. For the TestCertName variable, use the unique name value for a self-signed or CA certificate that you have created in the org in which you run this test.
1public class TestSignWithCert {
2
3 public void testSignWithCert() {
4
5 String algorithmName = 'RSA';
6 Blob input = Blob.valueOf('Test Sign With Certificate.');
7 String TestCertName = 'your-cert-unique-name';
8 Blob signedKey = Crypto.signWithCertificate(algorithmName, input, TestCertName);
9 }
10 }To invoke the method, run the following:
1TestSignWithCert tswc = new TestSignWithCert();
2tswc.testSignWithCert();signXML(algorithmName, node, idAttributeName, certDevName)
Signature
public Void signXML(String algorithmName, Dom.XmlNode node, String idAttributeName, String certDevName)
Parameters
- algorithmName
- Type: String
- These are valid values for algorithmName.
- RSA: the same as RSA-SHA1.
- RSA-SHA1: an RSA signature (with an asymmetric key pair) of an SHA1 hash.
- RSA-SHA256: an RSA signature of an SHA256 hash.
- RSA-SHA384: an RSA signature of an SHA384 hash.
- RSA-SHA512: an RSA signature of an SHA512 hash.
- ECDSA-SHA256: an ECDSA signature of an SHA256 hash.
- ECDSA-SHA256-PLAIN: an ECDSA signature of an SHA256 hash (P1363 format) .
- ECDSA-SHA384: an ECDSA signature of an SHA384 hash.
- ECDSA-SHA512: an ECDSA signature of an SHA512 hash.
- 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’s 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
This method doesn’t return a value. The signature envelope is inserted within node.
Example
You can use your preferred Salesforce development environment to test this function. Create the following Apex class. For the testCertName variable, use the unique name value for a self-signed or CA certificate that you have created in the org in which you run this test.
1 public class TestSignXML {
2 public void testSignXML() {
3 String algorithmName = 'RSA';
4 String testCertName = 'your-cert-unique-name';
5 Dom.Document doc = new Dom.Document();
6 String docToLoad = '<?xml version=\"1.0\"?>\n' +
7 '<customers>\n' +
8 ' <customer id="2">\n' +
9 ' <name>Company One</name>\n' +
10 ' </customer>\n' +
11 '</customers>';
12 doc.load(docToLoad);
13
14 System.Crypto.signXML(algorithmName, doc.getRootElement(), null, testCertName);
15
16 //dump the content of the signed XML document to the debug log
17 System.Debug(doc.toXmlString());
18 }
19 }To invoke this method, run the following:
1TestSignXML tswxml = new TestSignXML();
2tswxml.testSignXML();signXML(algorithmName, node, idAttributeName, certDevName, refChild)
Signature
public static void signXml(String algorithmName, Dom.XmlNode node, String idAttributeName, String certDevName, Dom.XmlNode refChild)
Parameters
- algorithmName
- Type: String
- These are valid values for algorithmName.
- RSA: the same as RSA-SHA1.
- RSA-SHA1: an RSA signature (with an asymmetric key pair) of an SHA1 hash.
- RSA-SHA256: an RSA signature of an SHA256 hash.
- RSA-SHA384: an RSA signature of an SHA384 hash.
- RSA-SHA512: an RSA signature of an SHA512 hash.
- ECDSA-SHA256: an ECDSA signature of an SHA256 hash.
- ECDSA-SHA256-PLAIN: an ECDSA signature of an SHA256 hash (P1363 format) .
- ECDSA-SHA384: an ECDSA signature of an SHA384 hash.
- ECDSA-SHA512: an ECDSA signature of an SHA512 hash.
- 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’s 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
This method doesn’t return a value. The signature envelope is inserted within node.
Example
You can use your preferred Salesforce development environment to test this function. Create the following Apex class. For the testCertName variable, use the unique name value for a self-signed or CA certificate that you have created in the org in which you run this test.
1public class TestSignXML_2 {
2 public void testSignXML_2() {
3 String algorithmName = 'RSA';
4 String testCertName = 'your-cert-unique-name';
5 Dom.Document doc = new Dom.Document();
6 String docToLoad = '<?xml version="1.0"?>\n' +
7 '<customers>\n' +
8 ' <customer id="2">\n' +
9 ' <name>Company One</name>\n' +
10 ' </customer>\n' +
11 '</customers>';
12 doc.load(docToLoad);
13 Dom.XmlNode rootNode = doc.getRootElement();
14 Dom.XmlNode commentNode = rootNode.addCommentNode('SomeComment');
15
16 System.Crypto.signXML(algorithmName, doc.getRootElement(), null, testCertName, commentNode);
17
18 //send the content of the signed XML document to the debug log
19 System.Debug(doc.toXmlString());
20 }
21
22 }To invoke this method, run the following:
1TestSignXML_2 tswxml2 = new TestSignXML_2();
2tswxml2.testSignXML_2();verify(algorithmName, data, signature, publicKey)
Signature
public static Boolean verify(String algorithmName, Blob data, Blob signature, Blob publicKey)
Parameters
- algorithmName
- Type: String
- These are valid values for algorithmName.
- RSA: the same as RSA-SHA1.
- RSA-SHA1: an RSA signature (with an asymmetric key pair) of an SHA1 hash.
- RSA-SHA256: an RSA signature of an SHA256 hash.
- RSA-SHA384: an RSA signature of an SHA384 hash.
- RSA-SHA512: an RSA signature of an SHA512 hash.
- ECDSA-SHA256: an ECDSA signature of an SHA256 hash.
- ECDSA-SHA256-PLAIN: an ECDSA signature of an SHA256 hash (P1363 format) .
- ECDSA-SHA384: an ECDSA signature of an SHA384 hash.
- ECDSA-SHA512: an ECDSA signature of an SHA512 hash.
- data
- Type: Blob
- The data to sign.
- signature
- Type:
- Blob
- The RSA or EDSA-compliant signature.
- publicKey
- Type: Blob
- The value of publicKey must be decoded using the EncodingUtilbase64Decode method, and be in X.509 standard format.
Example
You can use your preferred Salesforce development environment to test this function. To run it correctly, you must:
- generate an X.509 private key and public certificate
- convert the private key to PKCS8
- extract the public key from the public certificate
You provide the private PKCS8 key to the sign method, and the extracted public key to the verify method (along with the signature you generate with sign.
At your terminal, use openssl to create the X.509 key pair:
1$ openssl req -x509 -newkey rsa:2048 -keyout myPriv509.key -out myPub509.cert -days 365
2Convert the private key to PKCS8:
1openssl pkey -in myPriv509.key -out myPriv509pkcs8.pemExtract the public key from myPub509.cert:
1openssl x509 -in myPub509.cert -inform pem -pubkey -out myPub509.pemAfter you create the myPub509.pem key, you decode just the key portions of the text (without the BEGIN PRIVATE KEY or END PRIVATE KEY lines) for both the privateKey and publicKey parameters.
1public class TestVerify {
2 public void testVerify() {
3
4 String algorithmName = 'RSA';
5 Blob input = Blob.valueOf('Here is some text.');
6
7 //contents of myPriv509pkcs8.pem
8 String myPriv509pkcs8 = 'contents of myPriv509pkcs8.pem';
9
10 Blob privateKey = EncodingUtil.base64Decode(myPriv509pkcs8);
11
12 Blob signature = Crypto.sign(algorithmName, input, privateKey);
13
14 //contents of myPub509.pem
15 String publicKeyTxt64 = 'contents of myPub509.pem';
16
17 Blob publicKey = EncodingUtil.base64Decode(publicKeyTxt64);
18
19 Boolean verified = false;
20 verified = Crypto.verify(algorithmName, input, signature, publicKey);
21
22 Assert.areEqual(true, verified);
23
24 }
25 }To invoke, run the following:
1TestVerify tv = new TestVerify();
2tv.testVerify();verify(algorithmName, data, signature, certDevName)
Signature
public static Boolean verify(String algorithmName, Blob data, Blob signature, String certDevName)
Parameters
- algorithmName
- Type: String
- These are valid values for algorithmName.
- RSA: the same as RSA-SHA1.
- RSA-SHA1: an RSA signature (with an asymmetric key pair) of an SHA1 hash.
- RSA-SHA256: an RSA signature of an SHA256 hash.
- RSA-SHA384: an RSA signature of an SHA384 hash.
- RSA-SHA512: an RSA signature of an SHA512 hash.
- ECDSA-SHA256: an ECDSA signature of an SHA256 hash.
- ECDSA-SHA256-PLAIN: an ECDSA signature of an SHA256 hash (P1363 format) .
- ECDSA-SHA384: an ECDSA signature of an SHA384 hash.
- ECDSA-SHA512: an ECDSA signature of an SHA512 hash.
- data
- Type: Blob
- The data to sign.
- signature
- Type:
- Blob
- The RSA or ECDSA signature.
- certDevName
- Type: String
- The value listed in the Unique Name field 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.
Example
You can use your preferred Salesforce development environment to test this function. Create the following Apex class. For the TestCertName variable, use the unique name value for a self-signed or CA certificate that you have created in the org in which you run this test.
1public class TestVerify_2 {
2 public void testVerify_2() {
3
4 String algorithmName = 'RSA';
5 Blob input = Blob.valueOf('Test Sign With Certificate.');
6 String TestCertName = 'your-cert-unique-name';
7 Blob signedKey = Crypto.signWithCertificate(algorithmName, input, TestCertName);
8
9 Boolean verified = false;
10 verified = Crypto.verify(algorithmName, input, signedKey, TestCertName);
11 Assert.areEqual(true, verified);
12 }
13 }To invoke this method, run the following:
1TestVerify_2 tv_2 = new TestVerify_2();
2tv_2.testVerify_2();verifyHMac(algorithmName, data, privateKey, macToVerify)
Signature
public static Boolean verifyHMac(String algorithmName, Blob data, Blob privateKey, Blob macToVerify)
Parameters
- algorithmName
- Type: String
- These are valid values for algorithmName.
- hmacMD5
- hmacSHA1
- hmacSHA256
- hmacSHA512
- data
- Type: Blob
- The data to sign.
- privateKey
- Type: Blob
- If the private key used to generate the MAC was Base64 encoded, then the value of privateKey must also be Base64 encoded. The value cannot exceed 4 KB.
- hmacToVerify
- Type: Blob
- The value of the mac must be verified against the provided privateKey, data, and algorithmName.
Example
You can use your preferred Salesforce development environment to test this function. Create the following Apex class:
1public class TestVerifyMAC {
2
3 public void testVerifyMAC() {
4 String salt = String.valueOf(Crypto.getRandomInteger());
5 String key = 'key';
6 Blob data = crypto.generateMac('HmacSHA256',
7 Blob.valueOf(salt),
8 Blob.valueOf(key));
9 System.debug('Generated MAC: ');
10 System.debug(EncodingUtil.base64Encode(data));
11
12 Boolean verified = false;
13
14 verified = Crypto.verifyHMac('HmacSHA256', Blob.valueOf(salt), Blob.valueOf(key), data);
15 Assert.areEqual(true, verified);
16 }
17 }To invoke this method, run the following:
1TestVerifyMAC tvm = new TestVerifyMAC();
2tvm.testVerifyMAC();