Crypto Class

The methods in the Crypto class provide standard algorithms for creating digests, message authentication codes, and signatures, as well as encrypting and decrypting information. These can be used for securing content in Force.com, or for integrating with external services such as Google or Amazon WebServices (AWS).

Name Arguments Return Type Description
decrypt String algorithmName

Blob privateKey

Blob initializationVector

Blob cipherText

Blob 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.
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.)

For an example, see Example Encrypting and Decrypting.

For more information about possible exceptions thrown during execution, see Encrypt and Decrypt Exceptions.

decryptWithManagedIV String algorithmName

Blob privateKey

Blob IVAndCipherText

Blob 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.
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 first 128 bits (16 bytes) of IVAndCipherText must contain the initialization vector.

For an example, see Example Encrypting and Decrypting.

For more information about possible exceptions thrown during execution, see Encrypt and Decrypt Exceptions.

encrypt String algorithmName

Blob privateKey

Blob initializationVector

Blob clearText

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

For an example, see Example Encrypting and Decrypting.

For more information about possible exceptions thrown during execution, see Encrypt and Decrypt Exceptions.

encryptWithManagedIV String algorithmName

Blob privateKey

Blob clearText

Blob 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. It 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.

For an example, see Example Encrypting and Decrypting.

For more information about possible exceptions thrown during execution, see Encrypt and Decrypt Exceptions.

generateAesKey Integer size Blob Generates an Advanced Encryption Standard (AES) key. Use size to specify the key's size in bits. Valid values are:
  • 128
  • 192
  • 256
generateDigest String algorithmName

Blob input

Blob Computes a secure, one-way hash digest based on the supplied input string and algorithm name. Valid values for algorithmName are:
  • MD5
  • SHA1
  • SHA-256
  • SHA-512
generateMac

String algorithmName

Blob input

Blob privateKey
Blob Computes a message authentication code (MAC) for the input string, using the private key and the specified algorithm. The valid values for algorithmName are:
  • hmacMD5
  • hmacSHA1
  • hmacSHA256
  • hmacSHA512

The value of privateKey does not need to be in decoded form. The value cannot exceed 4 KB.

getRandomInteger Integer Returns a random Integer.
getRandomLong Long Returns a random Long.
sign

String algorithmName

Blob input

Blob privateKey
Blob Computes a unique digital signature for the input string, using the supplied private key and the specified algorithm. The valid values for algorithmName are RSA-SHA1 or RSA. Both values represent the same algorithm.

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.

The following snippet is an example declaration and initialization:

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

Example Integrating Amazon WebServices

The following example demonstrates an integration of Amazon WebServices with Salesforce:

public class HMacAuthCallout {

   public void testAlexaWSForAmazon() {
 
   // The date format is yyyy-MM-dd'T'HH:mm:ss.SSS'Z' 
    
      DateTime d = System.now();
      String timestamp = ''+ d.year() + '-' +
      d.month() + '-' +
      d.day() + '\'T\'' +
      d.hour() + ':' +
      d.minute() + ':' +
      d.second() + '.' +
      d.millisecond() + '\'Z\'';
      String timeFormat = d.formatGmt(timestamp);

      String urlEncodedTimestamp = EncodingUtil.urlEncode(timestamp, 'UTF-8');
      String action = 'UrlInfo';
      String inputStr = action + timeFormat;
      String algorithmName = 'HMacSHA1';
      Blob mac = Crypto.generateMac(algorithmName,  Blob.valueOf(inputStr), 
                                                    Blob.valueOf('your_signing_key'));
      String macUrl = EncodingUtil.urlEncode(EncodingUtil.base64Encode(mac), 'UTF-8');
 
      String urlToTest = 'amazon.com';
      String version = '2005-07-11'; 
      String endpoint = 'http://awis.amazonaws.com/';
      String accessKey = 'your_key';
 
      HttpRequest req = new HttpRequest();
      req.setEndpoint(endpoint +
                      '?AWSAccessKeyId=' + accessKey +
                      '&Action=' + action +
                      '&ResponseGroup=Rank&Version=' + version +
                      '&Timestamp=' + urlEncodedTimestamp +
                      '&Url=' + urlToTest +
                      '&Signature=' + macUrl);
 
      req.setMethod('GET');
      Http http = new Http();
      try {
         HttpResponse res = http.send(req);
         System.debug('STATUS:'+res.getStatus());
         System.debug('STATUS_CODE:'+res.getStatusCode());
         System.debug('BODY: '+res.getBody());
      } catch(System.CalloutException e) {
         System.debug('ERROR: '+ e);
      }
   }
}

Example Encrypting and Decrypting

The following example uses the encryptWithManagedIV and decryptWithManagedIV methods, as well as the generateAesKey method.

// Use generateAesKey to generate the private key 
    
Blob cryptoKey = Crypto.generateAesKey(256);

// Generate the data to be encrypted. 
    
Blob data = Blob.valueOf('Test data to encrypted');

// Encrypt the data and have Salesforce.com generate the initialization vector  
    
Blob encryptedData = Crypto.encryptWithManagedIV('AES256', cryptoKey, data);

// Decrypt the data 
    
Blob decryptedData = Crypto.decryptWithManagedIV('AES256', cryptoKey, encryptedData);
The following is an example of writing a unit test for the encryptWithManagedIV and decryptWithManagedIV methods.
@isTest
private class CryptoTest {
    public static testMethod void testValidDecryption() {

        // Use generateAesKey to generate the private key 
    
        Blob key = Crypto.generateAesKey(128);
        // Generate the data to be encrypted. 
    
        Blob data = Blob.valueOf('Test data');
        // Generate an encrypted form of the data using base64 encoding 
    
        String b64Data = EncodingUtil.base64Encode(data);
        // Encrypt and decrypt the data 
    
        Blob encryptedData = Crypto.encryptWithManagedIV('AES128', key, data);
        Blob decryptedData = Crypto.decryptWithManagedIV('AES128', key, encryptedData);
        String b64Decrypted = EncodingUtil.base64Encode(decryptedData);
        // Verify that the strings still match 
    
        System.assertEquals(b64Data, b64Decrypted);
    }
    public static testMethod void testInvalidDecryption() {
        // Verify that you must use the same key size for encrypting data 
    
        // Generate two private keys, using different key sizes 
    
        Blob keyOne = Crypto.generateAesKey(128);
        Blob keyTwo = Crypto.generateAesKey(256);
        // Generate the data to be encrypted. 
    
        Blob data = Blob.valueOf('Test data');
        // Encrypt the data using the first key  
    
        Blob encryptedData = Crypto.encryptWithManagedIV('AES128', keyOne, data);
        try {
         // Try decrypting the data using the second key    
    
            Crypto.decryptWithManagedIV('AES256', keyTwo, encryptedData);
            System.assert(false);
        } catch(SecurityException e) {
            System.assertEquals('Given final block not properly padded', e.getMessage());
        }
    }
}

Encrypt and Decrypt Exceptions

The following exceptions can be thrown for these methods:
ExceptionMessageDescription
InvalidParameterValueUnable to parse initialization vector from encrypted data.Thrown if you're using managed initialization vectors, and the cipher text is less than 16 bytes.
InvalidParameterValueInvalid algorithm algoName. Must be AES128, AES192, or AES256.Thrown if the algorithm name isn't one of the valid values.
InvalidParameterValueInvalid private key. Must be size bytes.Thrown if size of the private key doesn't match the specified algorithm.
InvalidParameterValueInvalid initialization vector. Must be 16 bytes.Thrown if the initialization vector isn't 16 bytes.
InvalidParameterValueInvalid 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.
NullPointerExceptionArgument cannot be null.Thrown if one of the required method arguments is null.
SecurityExceptionGiven final block not properly padded.Thrown if the data isn't properly block-aligned or similar issues occur during encryption or decryption.
SecurityExceptionMessage VariesThrown if something goes wrong during either encryption or decryption.
© Copyright 2000–2012 salesforce.com, inc. All rights reserved.
Various trademarks held by their respective owners.