Using the Apex Crypto Class with Examples

The Apex Crypto class provides a number of cryptographic functions for creating digests, message authentication codes, and signatures, as well as functions for encrypting and decrypting information. These functions allow you to protect the confidentiality of data as well as allow external systems to verify the integrity of messages and authenticity of the sender.

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 AWS.
The cryptographic capabilities of the Crypto class are normally used in the following scenarios:

  • Authenticity – proof of the authenticity of the sender or receiver of the message
  • Confidentiality – Protecting the data in a rest resource or in transit from unauthorized parties
  • Integrity – the data is complete and correct

Encryption and Decryption

Consists of functions to encrypt and decrypt information using AES128, AES192 and AES256 algorithms. Currently, only symmetric private key encryption using the AES algorithm is supported. Whilst encryption provides for data protection, it does not authenticate the sender (non-repudiation) and nor does it guarantee message integrity.

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

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.

Add Comment