Crypto Class

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

System

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 that you want to do, check each method.

The Crypto class supports Galois Counter Mode (GCM) and Cipher Block Chaining mode (CBC). The GCM AES256-GCM algorithm is valid in all encrypt and decrypt variants Currently, only the 256-bit size is supported for GCM. CBC algorithms in 128-bit, 192-bit, and 256-bit sizes are valid in all variants except those that expect additional authentication data (an aaD parameter).

  • When you use CBC with encrypt and decrypt, you provide a 16-bit initialization vector (IV).
  • When you use GCM with encrypt and decrypt, you provide no initialization vector (IV).
  • When you use CBC with encryptWithManagedIV and decryptWithManagedIV, Salesforce provides the IV. You provide no additional authentication data (aaData). You can only use CBC with encryptWithManagedIV and decryptWithManagedIV if you use the version which does not expect aaData.
  • When you use GCM with encryptWithManagedIV and decryptWithManagedIV, Salesforce provides an IV. and you can optionally provide the aaData

When use the Crypto class to encrypt using GCM, the final encrypted content includes the length of the IV (always 12), the Salesforce-generated 12-byte IV, and the cipher text.

The Crypto class supports these encryption algorithms.

MODEVARIANTDESCRIPTION
CBC (Cipher Block Chaining)AES128, AES128-CBCAES 128-bit with CBC mode with PKCS7 padding. Use either of these two values.
 AES192,AES192-CBCAES 192-bit with CBC mode with PKCS7 padding. Use either of these two values.
 AES256,AES256-CBCAES 256-bit with CBC mode with PKCS7 padding. Use either of these two values.
GCM (Galois Counter Mode)AES256-GCMAES 256-bit with GCM mode with no padding. Currently, only the 256-bit size is supported for GCM.

The Crypto class supports these signing algorithms.

modeVARIANTDESCRIPTION
RSARSA, RSA-SHA1An RSA signature (with an asymmetric key pair) of an SHA1 hash. Use either of these two values.
 RSA-SHA256RSA signature of an SHA256 hash
 RSA-SHA384RSA signature of an SHA384 hash
 RSA-SHA512RSA signature of an SHA512 hash
ECDSA (DER)ECDSA-SHA256ECDSA signature of an SHA256 hash
 ECDSA-SHA384ECDSA signature of an SHA384 hash
 ECDSA-SHA512ECDSA signature of an SHA512 hash
ECDSA (P1363)ECDSA-SHA256-P1363ECDSA signature of an SHA256 hash (P1363 format)
 ECDSA-SHA256-PLAINECDSA signature of an SHA256 hash (P1363 format). Use if the JWT returns invalid_client. See Other Errors on this page.
 ECDSA-SHA384-P1363ECDSA signature of an SHA256 hash (P1363 format)
 ECDSA-SHA512-P1363ECDSA signature of an SHA512 hash (P1363 format)
ECDSAES256Signs data using ECDSA over the P-256 curve with a SHA-256 hash.
 ES384Signs data using ECDSA over the P-384 curve with a SHA-384 hash.
 ES512Signs data using ECDSA over the P-521 curve with a SHA-512 hash.

The Crypto class supports these key management algorithms.

modeVARIANTDESCRIPTION
Key WrappingECDH-ES+A128KWDerives a 128-bit key using Elliptic Curve Diffie-Hellman Ephemeral-Static (ECDH-ES) key agreement, then uses that derived key to encrypt the content encryption key with the AES Key Wrap algorithm.
 ECDH-ES+A192KWDerives a 192-bit key using Elliptic Curve Diffie-Hellman Ephemeral-Static (ECDH-ES) key agreement, then uses that derived key to encrypt the content encryption key with the AES Key Wrap algorithm.
 ECDH-ES+A256KWDerives a 256-bit key using Elliptic Curve Diffie-Hellman Ephemeral-Static (ECDH-ES) key agreement, then uses that derived key to encrypt the content encryption key with the AES Key Wrap algorithm.

The Crypto class supports these curve and key type algorithms.

modeVARIANTDESCRIPTION
Elliptic CurveEC-P256Identifies an elliptic curve key pair generated on the P-256 (secp256r1) curve.
 EC-P384Identifies an elliptic curve key pair generated on the P-384 (secp384r1) curve.
 EC-P521Identifies an elliptic curve key pair generated on the P-521 (secp521r1) curve.
 P-256NIST-standardized elliptic curve providing a 256-bit key size, used as the basis for EC-P256 keys and ES256 signatures.
 P-384NIST-standardized elliptic curve providing a 384-bit key size, used as the basis for EC-P384 keys and ES384 signatures.
 P-521NIST-standardized elliptic curve providing a 521-bit key size, used as the basis for EC-P521 keys and ES512 signatures.
 RSA-3072Identifies an RSA key pair using a 3072-bit modulus.
 RSA-4096Identifies an RSA key pair using a 4096-bit modulus.
 ECDSA-SHA512ECDSA signature of an SHA512 hash
ECDSA (P1363)ECDSA-SHA256-P1363ECDSA signature of an SHA256 hash (P1363 format)
 ECDSA-SHA256-PLAINECDSA signature of an SHA256 hash (P1363 format). Use if the JWT returns invalid_client. See Other Errors on this page.
 ECDSA-SHA384-P1363ECDSA signature of an SHA384 hash (P1363 format)
 ECDSA-SHA512-P1363ECDSA signature of an SHA512 hash (P1363 format)

These 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 the suported AES algorithms listed on this page.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. For CBC, this must be 16 bytes. For GCM, the IV is 12 bytes.Thrown if the initialization vector provided for a CBC encryption isn’t 16 bytes.
 AAD can only be used with AESGCM algorithms.Thrown if a value is supplied for aaData, but the encryption algorithm isn’t a GCM type.
 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.
 Message VariesThrown if something goes wrong during either encryption or decryption.
 This crypto method is unavailable. Contact your Salesforce administrator.Thrown if any of the gated crypto methods are called when the gate platform.encryption.apexcrypto is closed.
 This crypto method is temporarily unavailable. Contact your Salesforce administrator.Thrown if any of the gated crypto methods are called when the gater service is unavailable or there is a temporary glitch in the system.
SystemExceptionTypeInvalid data. Input data is %d bytes, which exceeds the limit of %d bytes.Thrown if the input blob to encrypt and decrypt has exceeded a certain limit in size.
INVALID_PARAMETER_VALUEUnsupported RSA algorithm.Thrown if RSA algorithm string doesn’t match supported formats.
 Unsupported algorithm.Thrown if algorithm not in the supported list.
 Invalid EC key pair blob: too small to contain length prefix.Thrown if key pair blob is less than 4 bytes.
 Invalid EC key pair blob: private key length out of range.Thrown if private key length is invalid or exceeds blob size.
 Invalid EC key pair blob: no public key data after private key.Thrown if public key data is missing from the key pair blob.
 JWE token exceeds maximum size of 1048576 bytes.Thrown if JWE token exceeds 1 MB limit.
 Unsupported content encryption algorithm.Thrown if content encryption algorithm isn’t supported.
 Unsupported algorithm for ECDH-ES encryption.Thrown if algorithm is not a supported ECDH-ES key wrap algorithm.
 Additional AAD isn’t supported in JWE compact serialization. Use empty AAD.Thrown if caller provides non-empty AAD (JWE compact serialization only uses protected header as AAD).
 CEK length mismatch: expected {expected} bytes for {enc}, got {actual}.Thrown if provided CEK length doesn’t match the content encryption algorithm requirements.
SECURITYException message from underlying Java security framework.Thrown if GeneralSecurityException during key pair generation.
 Invalid JWE compact serialization. Expected 5 dot-separated parts, got {actual_count}.Thrown if JWE doesn’t have exactly 5 dot-separated parts.
 JWE header missing required alg field.Thrown if JWE protected header lacks alg field.
 JWE header missing required enc field.Thrown if JWE protected header lacks enc field.
 JWE header missing required epk (ephemeral public key) field.Thrown if JWE protected header lacks epk field.
 JWE parsing failed: {exception_message}.Thrown if any GeneralSecurityException, IOException, or IllegalArgumentException during JWE parsing.
 Decryption failed: {exception_class}: {exception_message}.Thrown if any GeneralSecurityException or IllegalArgumentException during decryption.
 Encryption failed: {exception_class}: {exception_message}.Thrown if any GeneralSecurityException or IllegalArgumentException during encryption.
SECURITY (InvalidKeySpecException)EPK JWK kty must be EC, got: {kty_value}.Thrown when the EPK JWK key type is not EC.
 EPK JWK missing required fields (crv, x, y).Thrown if EPK JWK lacks required EC coordinate fields.
 Unsupported EPK curve: {crv_value}.Thrown if EPK curve is not P-256, P-384, or P-521.
 Ephemeral key curve does not match recipient public key curve.Thrown if ephemeral key pair curve doesn’t match recipient’s public key curve.
SECURITY (GeneralSecurityException)Encrypted key must not be empty for key-wrap algorithms.Thrown if encrypted key blob is empty for key-wrap algorithms.
 AES-GCM IV must be 96 bits (12 bytes), got {actual_length}Thrown if IV for AES-GCM is not 12 bytes.
SECURITY (AEADBadTagException)Authentication tag verification failed.Thrown if HMAC tag verification fails during AES-CBC-HS decryption.
SECURITY (NoSuchAlgorithmException)Unsupported content encryption: {enc_value}.Thrown if internal routing doesn’t recognize content encryption algorithm.

These exceptions are a subset of the exceptions that can be thrown from the System namespace. Refer to Exception Class and Built-In Exceptions

For CBC, the Crypto class uses AES / CBC / PKCS7 padding, which is vulnerable to a Padding Oracle attack. You can protect against a Padding Oracle attack by 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 by 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.

You can also protect against a Padding Oracle attack by using a GCM encryption algorithm.

Under rare conditions you may encounter the invalid_client error from the JSON Web Tokens (JWT) service.

ErrorMessageDescription
invalid_clientThe 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 P1363 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.

Each of the methods in this section contains a code sample to demonstrate the method’s use. The samples use curl to make calls into your Salesforce org. Use your preferred developer environment to run the samples. Use the Salesforce developer Introduction to REST API for basic information on making REST calls into Salesforce. Also, Introducing the Salesforce Shield Platform Encryption REST API gives you starter information on using REST to work with Shield Platform Encryption.

See Also

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

Decrypts a JWE (JSON Web Encryption) token using ECDH-ES key agreement with AES Key Wrap algorithms. Use this method to decrypt ID tokens from identity providers (e.g., Singpass, Corppass) that use JWE for additional security.

public static Blob decrypt( String algorithm, String enc, Blob privateKey, Blob ephemeralPublicKey, Blob encryptedKey, Blob iv, Blob ciphertext, Blob tag, Blob aad )

  • algorithm:

    Type: String

    The JWE key agreement algorithm supports these values for algorithm. See Crypto Class for details on each algorithm.

    • ECDH-ES+A128KW
    • ECDH-ES+A192KW
    • ECDH-ES+A256KW
  • enc:

    Type: String

    The content encryption algorithm used to encrypt the JWE payload supports these values for enc. See Crypto Class for details on each algorithm.

    • A128GCM
    • A192GCM
    • A256GCM
    • A128CBC-HS256
    • A192CBC-HS384
    • A256CBC-HS512
  • privateKey:

    Type: Blob

    Your static private key (PKCS#8 DER format) for ECDH key agreement.

  • ephemeralPublicKey:

    Type: Blob

    The sender’s ephemeral public key (X.509 DER format) from the JWE header.

  • encryptedKey:

    Type: Blob

    The wrapped Content Encryption Key (CEK) from the JWE.

  • iv:

    Type: Blob

    The initialization vector from the JWE.

  • ciphertext:

    Type: Blob

    The encrypted payload from the JWE.

  • tag:

    Type: Blob

    The GCM authentication tag from the JWE.

  • aad:

    Type: Blob

    The Additional Authenticated Data (typically the base64url-encoded JWE header).

Type: Blob

The decrypted plaintext. For OAuth/OIDC flows, this is typically a JWS (signed JWT) that requires additional verification.

You can use your preferred Salesforce development environment to test this function. Create this Apex class.

To invoke this method, run:

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

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

  • algorithmName:

    Type: String

    This version of decrypt supports these values for algorithmName. See Crypto Class for details on each algorithm.

    • AES128, AES128-CBC
    • AES192, AES192-CBC
    • AES256, AES256-CBC
    • AES256-GCM
  • secretKey:

    Type: Blob

    Private key text. The length of secretKey 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

    • For CBC, the 128 bit (16 byte) IV. The IV must be 128 bits (16 bytes.)
    • For GCM, don’t provide an IV. Any non-null IV will result in an error.
  • encryptedData:

    Type: Blob

    The content to decrypt.

Type: Blob

Contains the decrypted contents of cipherText.

You can use your preferred Salesforce development environment to test this function. Create this Apex class.

To invoke this method, run:

Decrypts the IVAndCipherText blob by using the specified algorithm and private key. Use this method to decrypt blobs encrypted by using a third-party application or the encryptWithManagedIV method. This version of decryptWithManagedIV doesn’t use additional authentication data.

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

  • algorithmName:

    Type: String

    decryptWithManagedIV supports all these values for algorithmName. See Crypto Class for details on each algorithm.

    • AES128, AES128-CBC
    • AES192, AES192-CBC
    • AES256, AES256-CBC
    • AES256-GCM
  • secretKey:

    Type: Blob

    Private key text. The length of secretKey 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 that you want to decrypt.

    • For CBC, IVAndCipherText must contain IV + ciphertext, where the IV must be the first 128 bits (16 bytes) with the ciphertext following.
    • FOR GCM, IVAndCipherText must contain the length of the IV (always 12) followed by a 96 bit (12 byte) IV, with the ciphertext following.

Type: Blob

Contains the decrypted contents of IVAndCipherText.

You can use your preferred Salesforce development environment to test this function. Create this Apex class.

To invoke this method, run:

Decrypts the IVAndCipherText blob by using the specified algorithm and private key. Use this method to decrypt blobs encrypted by using a third-party application or the encryptWithManagedIV method. This version of decryptWithManagedIV uses additional authentication data. CBC isn’t supported for this method.

public static Blob decryptWithManagedIV(String algorithmName, Blob secretKey, Blob IVAndCipherText, Blob aaData)

  • algorithmName:

    Type: String

    decryptWithManagedIV supports all these values for algorithmName. See Crypto Class for details on each algorithm.

    • AES256-GCM
  • secretKey:

    Type: Blob

    Private key text. The length of secretKey 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

    IVAndCipherText must contain the length of the IV (always 12) followed by a 96 bit (12 byte) IV, with the ciphertext following.

  • aaData:

    Type: Blob

    Additional authentication data. This value is required.

Type: Blob

Contains the decrypted contents of IVAndCipherText.

You can use your preferred Salesforce development environment to test this function. Create this Apex class.

To invoke this method, run:

Encrypts plaintext using ECDH-ES key agreement with AES Key Wrap algorithms, producing a JWE token. Use this method for encrypting sensitive data that only the recipient can decrypt.

public static Blob encrypt( String algorithm, String enc, Blob recipientPublicKey, Blob ephemeralPublicKey, Blob ephemeralPrivateKey, Blob cek, Blob iv, Blob plaintext, Blob aad )

  • algorithm:

    Type: String

    This version of decrypt supports these values for algorithm. See Crypto Class for details on each algorithm.

    • ECDH-ES+A128KW
    • ECDH-ES+A192KW
    • ECDH-ES+A256KW
  • enc:

    Type: String

    The JWE key agreement algorithm supports these values for enc. See Crypto Class for details on each algorithm.

    • A128GCM, A128CBC-HS256
    • A192GCM, A192CBC-HS384
    • A256GCM, A256CBC-HS512
  • recipientPublicKey:

    Type: Blob

    The recipient’s public key (X.509 DER format) for ECDH key agreement.

  • ephemeralPrivateKey:

    Type: Blob

    Your ephemeral private key (from generateKeyPair().).

  • ephemeralPublicKey:

  • Type: Blob

    The sender’s ephemeral public key (X.509 DER format) from the JWE header.

  • cek:

    Type: Blob

    A random CEK (from generateAesKey()). Must match the AES key size for the chosen algorithm.

  • iv:

    Type: Blob

    The initialization vector from the JWE.

  • plaintext:

    Type: Blob

    The data to encrypt.

  • aad:

    Type: Blob

    The Additional Authenticated Data for authenticated encryption (typically empty for compact serialization).

Type: Blob

The encrypted JWE token in compact serialization format: header.encryptedKey.iv.ciphertext.tag

You can use your preferred Salesforce development environment to test this function. Create this Apex class.

To invoke this method, run:

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

public static Blob encrypt(String algorithmName, Blob secretKey, Blob initializationVector, Blob clearData)

  • algorithmName:

    Type: String

    Algorithm for encrypting clearText. encrypt supports all these values for algorithmName. See Crypto Class for details on each algorithm.

    • AES128, AES128-CBC
    • AES192, AES192-CBC
    • AES256, AES256-CBC
    • AES256-GCM
  • secretKey:

    Type: Blob

    Private key text. The length of secretKey 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

    • For CBC, any 128 bit (16 byte) string to provide the initial state to this method. The initialization vector must be 128 bits (16 bytes.)
    • For GCM, don’t provide an IV. Any non-null IV results in an error.
  • clearData:

    Type: Blob

    The content that you want to encrypt.

Type: Blob

Contains the encrypted contents of clearText.

You can use your preferred Salesforce development environment to test this function. Create this Apex class.

To invoke this method, run:

Encrypts the clearText blob by using the specified algorithm and private key. Use this method when you want Salesforce to generate the initialization vector. This version of encryptWithManagedIV doesn’t use additional authentication data.

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

  • algorithmName:

    Type: String

    encryptWithManagedIV supports all these values for algorithmName. See Crypto Class for details on each algorithm.

    • AES128, AES128-CBC
    • AES192, AES192-CBC
    • AES256, AES256-CBC
    • AES256-GCM
  • secretKey:

    Type: Blob

    Private key text. The length of secretKey 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.

Type: Blob

Contains the encrypted contents of clearText.

  • For CBC, the initialization vector is stored as the first 128 bits (16 bytes) of the encrypted blob.
  • For GCM, the return value contains the length of the IV (always 12) followed by a 96 bit (12 byte) Salesforce generated IV, with the ciphertext following.

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.

You can use your preferred Salesforce development environment to test this function. Create this Apex class.

To invoke this method, run:

Encrypts the clearText blob by using the specified algorithm and private key. Use this method when you want Salesforce to generate the initialization vector. This version of encryptWithManagedIV uses additional authentication data. CBC isn’t supported for this method.

public static Blob encryptWithManagedIV(String algorithmName, Blob secretKey, Blob clearText, Blob aaData)

  • algorithmName:

    Type: String

    encryptWithManagedIV supports all these values for algorithmName. See Crypto Class for details on each algorithm.

    • AES256-GCM
  • secretKey:

    Type: Blob

    Private key text. The length of secretKey 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.

  • aaData:

    Type: Blob

    Additional authentication data. This is required .

Type: Blob

Contains the encrypted contents of clearText. For GCM, the return value contains the length of the IV (always 12) followed by a 96 bit (12 byte) Salesforce generated IV, with the ciphertext following.

You can use your preferred Salesforce development environment to test this function. Create this Apex class.

To invoke this method, run:

Generates an Advanced Encryption Standard (AES) key.

public static Blob generateAesKey(Integer size)

  • size: Type: Integer The key’s size in bits. Valid values are:

    • 128
    • 192
    • 256

Type: Blob

Contains the generated AES key.

You can use your preferred Salesforce development environment to test this function. Create the following Apex class:

To invoke this method, run the following:

Computes a secure, one-way hash digest using the specified algorithm on the supplied input blob.

public static Blob generateDigest(String algorithmName, Blob input)

  • algorithmName: Type: String The algorithm you want to use to generate the digest. Valid values for algorithmName are:

    • MD5
    • SHA1
    • SHA3-256
    • SHA3-384
    • SHA3-512
    • SHA-256
    • SHA-512
  • input: Type: Blob The content for which you want to generate the digest.

Type: Blob

Contains the generated digest.

You can use your preferred Salesforce development environment to test this function. Create the following Apex class:

To invoke this method, run the following:

Generates an asymmetric cryptographic key pair for digital signatures, key agreement protocols (ECDH), or DPoP token generation. The returned blob contains both keys; extract them using getPrivateKey() and getPublicKey() methods.

public static Blob generateKeyPair(String algorithm)

  • algorithm:

    Type: String

    generateKeyPair supports these values for algorithm. See Crypto Class for details on each algorithm.

    • ES256, ES384, ES512
    • EC-P256, EC-P384, EC-P521
    • P-256, P-384, P-521

Type: Blob

A combined blob containing both the private and public keys in a custom binary format: [4-byte length][PKCS#8 private key][X.509 public key]. Use getPrivateKey() and getPublicKey() to extract individual keys.

You can use your preferred Salesforce development environment to test this function. Create this Apex class.

To invoke this method, run:

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

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

  • 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.

Type: Blob

The message authentication code.

You can use your preferred Salesforce development environment to test this function. Create the following Apex class:

To invoke this method, run the following:

Extracts the private key from a combined key pair blob returned by generateKeyPair().

public static Blob getPrivateKey(Blob keyPairBlob)

  • keyPairBlob

    Type: Blob

    The combined key pair blob returned by generateKeyPair().

Type: Blob

The private key in PKCS#8 DER-encoded format. The extracted EC private key can be used with:

  • sign() — algorithmName must be ES256, ES384, or ES512 (matching the curve used in generateKeyPair()). RSA algorithm names throw SecurityException.
  • decrypt(algorithm, enc, privateKey, ephemeralPublicKey, encryptedKey, iv, ciphertext, tag, aad) — nine-argument JWE ECDH-ES overload only.

You can use your preferred Salesforce development environment to test this function. Create this Apex class.

To invoke this method, run:

Extracts the public key from a combined key pair blob returned by generateKeyPair().

public static Blob getPublicKey(Blob keyPairBlob)

  • keyPairBlob

    Type: Blob

    The combined key pair blob returned by generateKeyPair()

Type: Blob

The public key in X.509 SubjectPublicKeyInfo DER-encoded format. Can be used with verify() or encrypt() methods.

Extracts the public key component from a key pair blob. The public key is encoded in X.509 format and can be safely shared or embedded in tokens (e.g., DPoP JWT header).

You can use your preferred Salesforce development environment to test this function. Create this Apex class.

To invoke this method, run:

Returns a random integer value.

public static Integer getRandomInteger()

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.

You can use your preferred Salesforce development environment to exercise this function. Create the following Apex class:

To invoke this method, run the following:

See Also

Returns a random long value.

public static Long getRandomLong()

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.

You can use your preferred Salesforce development environment to exercise this function. Create the following Apex class:

To invoke this method, run the following:

See Also

Parses a JWE (JSON Web Encryption) compact serialization token and returns a structured JweToken object containing all components needed for decryption. Use this method as an alternative to manually parsing the JWE compact serialization string.

public static System.JweToken parseJwe(Blob jweToken)

  • jweToken:

    Type: Blob

    The JWE token in compact serialization format (five dot-separated base64url-encoded parts).

Type: System.JweToken

A structured object containing parsed JWE components. Use getter methods to access individual fields for use with decrypt().

You can use your preferred Salesforce development environment to test this function. Create this Apex class.

To invoke this method, run:

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

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

  • algorithmName: Type: String

  • input: sign supports all these values for algorithmName. See Crypto Class for details on each algorithm.

    RSA, RSA-SHA1, RSA-SHA256, RSA-SHA384, RSA-SHA512, ECDSA-SHA256, ECDSA-SHA256-PLAIN, ECDSA-SHA384, ECDSA-SHA512, ES256, ES384, and ES512

    Type: Blob The data to sign.

  • privateKey: Type: Blob The key to use for signing. The value of privateKey must be decoded using the EncodingUtil base64Decode method, and should be in RSA’s PKCS #8 (1.2) Private-Key Information Syntax Standard form. The value can’t exceed 4 KB.

Type: Blob

The new digital signature.

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:

After 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.

To invoke this method, run the following:

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

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

  • algorithmName: Type: String signWithCertificate supports all these values for algorithmName. See Crypto Class for details on each algorithm.

    RSA, RSA-SHA1, RSA-SHA256, RSA-SHA384, RSA-SHA512, ECDSA-SHA256, ECDSA-SHA256-PLAIN, ECDSA-SHA384, and ECDSA-SHA512

  • 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.

Type: Blob

The signed content.

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.

To invoke the method, run the following:

Envelops the signature into an XML document.

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

  • algorithmName: Type: String signWithCertificate supports all these values for algorithmName. See Crypto Class for details on each algorithm.

    RSA, RSA-SHA1, RSA-SHA256, RSA-SHA384, RSA-SHA512, ECDSA-SHA256, ECDSA-SHA256-PLAIN, ECDSA-SHA384, and ECDSA-SHA512

  • 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.

Type: void

This method doesn’t return a value. The signature envelope is inserted within node.

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.

To invoke this method, run the following:

Inserts the signature envelope before the specified child node.

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

  • algorithmName: Type: String signWithCertificate supports all these values for algorithmName. See Crypto Class for details on each algorithm.

    RSA, RSA-SHA1, RSA-SHA256, RSA-SHA384, RSA-SHA512, ECDSA-SHA256, ECDSA-SHA256-PLAIN, ECDSA-SHA384, and ECDSA-SHA512

  • 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.

Type: Void

This method doesn’t return a value. The signature envelope is inserted within node.

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.

To invoke this method, run the following:

Verifies the digital signature for the data blob using the specified algorithm and the supplied public key. Use this method to verify a blob signed by a digital signature created using a third-party application or the sign method.

public static Boolean verify(String algorithmName, Blob data, Blob signature, Blob publicKey)

  • algorithmName: Type: String verify supports all these values for algorithmName. See Crypto Class for details on each algorithm.

    RSA, RSA-SHA1, RSA-SHA256, RSA-SHA384, RSA-SHA512, ECDSA-SHA256, ECDSA-SHA256-PLAIN, ECDSA-SHA384, ECDSA-SHA512, ES256, ES384, and ES512

  • data: Type: Blob The data whose signature is being verified.

  • signature: Type: Blob The ECDSA-compliant signature.

  • publicKey: Type: Blob The value of publicKey must be decoded using the EncodingUtil.base64Decode method, and be in X.509 SubjectPublicKeyInfo DER encoded format, matching the algorithm family (RSA public key for RSA-*, EC public key for ECDSA-*, and ES*).

Type: Boolean

true if and only if the signature is successfully verified.

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:

Convert the private key to PKCS8:

Extract the public key from myPub509.cert:

After 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.

To invoke, run the following:

See Also

Verifies the digital signature for the data blob using the specified algorithm and the public key associated with certDevName. Use this method to verify a blob signed by a digital signature created using a third-party application or the signWithCertificate method.

public static Boolean verify(String algorithmName, Blob data, Blob signature, String certDevName)

  • algorithmName: Type: String verify supports all these values for algorithmName. See Crypto Class for details on each algorithm.

    RSA, RSA-SHA1, RSA-SHA256, RSA-SHA384, RSA-SHA512, ECDSA-SHA256, ECDSA-SHA256-PLAIN, ECDSA-SHA384, and ECDSA-SHA512

  • 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.

Type: Boolean

Returns true if the signature is successfully verified.

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.

To invoke this method, run the following:

Verifies the HMAC signature for the data blob using the specified algorithm, input data, private key, and the mac. Use this method to verify a blob signed by a digital signature created using a third-party application or the sign method.

public static Boolean verifyHMac(String algorithmName, Blob data, Blob privateKey, Blob macToVerify)

  • 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.

Type: Boolean

The verification status of the data to verify.

You can use your preferred Salesforce development environment to test this function. Create the following Apex class:

To invoke this method, run the following: