Apex Crypto Example

Salesforce Crypto Provides methods for creating digests, message authentication codes, and signatures, as well as encrypting and decrypting information.
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).The cryptographic capabilities of the Crypto class are normally used in the following scenarios:
  • Confidentiality – the protection of data either at rest or in transit from unauthorized parties
  • Integrity – the data is complete and correct
  • Authenticity – proof of the authenticity of the sender or receiver of the message

Encryption and Decryption

Salesforce supports encrypt and decrypt information using AES128, AES192, and AES256 algorithms. Currently, only symmetric private key encryption using the AES algorithm is supported. 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.Here is the example that will show encryption and decryption.

AES128 algorithms

AES192 algorithms

AES256 algorithms

Encrypt Decrypt With ManagedIV

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. 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.
AES128 algorithms

AES192 algorithms

AES256 algorithms

 

Digital signature 

Computes a unique digital signature for the input string, using the specified algorithm and the supplied private key.The algorithm name. The valid values for algorithmName are RSA-SHA1RSA-SHA256, or RSA.RSA-SHA1 is an RSA signature (with an asymmetric key pair) of a SHA1 hash.

You can use Salesforce Certificate to use for signing as shown below.The Unique Name for a certificate stored in the Salesforce organization’s Certificate and Key Management page to use for signing.