0% found this document useful (0 votes)
274 views5 pages

Example Encrypting and Decrypting: Apex Classes Reference

This document provides examples and documentation on encrypting and decrypting data in Apex using the Crypto class. It describes generating encryption keys, encrypting and decrypting data, and writing unit tests to test encryption and decryption. It also lists exceptions that can be thrown by the encryption and decryption methods and describes the EncodingUtil class for encoding, decoding, and converting strings.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
274 views5 pages

Example Encrypting and Decrypting: Apex Classes Reference

This document provides examples and documentation on encrypting and decrypting data in Apex using the Crypto class. It describes generating encryption keys, encrypting and decrypting data, and writing unit tests to test encryption and decryption. It also lists exceptions that can be thrown by the encryption and decryption methods and describes the EncodingUtil class for encoding, decoding, and converting strings.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Reference Apex Classes

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 {
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);
}
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());
}

632
Reference Apex Classes

}
}

Encrypt and Decrypt Exceptions


The following exceptions can be thrown for these methods:
• decrypt
• encrypt
• decryptWithManagedIV
• encryptWithManagedIV

Exception Message Description


InvalidParameterValue Unable to parse initialization vector from Thrown if you're using managed
encrypted data. initialization vectors, and the cipher text
is less than 16 bytes.
InvalidParameterValue Invalid algorithm algoName. Must be Thrown if the algorithm name isn't one
AES128, AES192, or AES256. of the valid values.
InvalidParameterValue Invalid private key. Must be size bytes. Thrown if size of the private key doesn't
match the specified algorithm.
InvalidParameterValue Invalid initialization vector. Must be 16 Thrown if the initialization vector isn't
bytes. 16 bytes.
InvalidParameterValue Invalid data. Input data is size bytes, Thrown if the data is greater than 1 MB.
which exceeds the limit of 1048576 bytes. For decryption, 1048608 bytes are
allowed for the initialization vector
header, plus any additional padding the
encryption added to align to block size.
NullPointerException Argument cannot be null. Thrown if one of the required method
arguments is null.
SecurityException Given final block not 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.

EncodingUtil Class
Use the methods in the EncodingUtil class to encode and decode URL strings, and convert strings to hexadecimal format.

Name Arguments Return Type Description


base64Decode String inputString Blob Converts a Base64-encoded String to a Blob representing its
normal form.
base64Encode Blob inputBlob String Converts a Blob to an unencoded String representing its normal
form.

633
Reference Knowledge Management Publishing Service Class

Name Arguments Return Type Description


convertToHex Blob inputString String Returns a hexadecimal (base 16) representation of the
inputString. This method can be used to compute the client
response (for example, HA1 or HA2) for HTTP Digest
Authentication (RFC2617).
urlDecode String inputString String Decodes a string in application/x-www-form-urlencoded
String format using a specific encoding scheme, for example “UTF-8.”
encodingScheme This method uses the supplied encoding scheme to determine
which characters are represented by any consecutive sequence of
the from \"%xy\". For more information about the format, see
The form-urlencoded Media Type in Hypertext Markup Language
- 2.0.
urlEncode String inputString String Encodes a string into the
String application/x-www-form-urlencoded format using a
encodingScheme specific encoding scheme, for example “UTF-8.” This method
uses the supplied encoding scheme to obtain the bytes for unsafe
characters. For more information about the format, see The
form-urlencoded Media Type in Hypertext Markup Language -
2.0.
Example:

String encoded = EncodingUtil.urlEncode(url,


'UTF-8');

Note: You cannot use the EncodingUtil methods to move documents with non-ASCII characters to Salesforce. You
can, however, download a document from Salesforce. To do so, query the ID of the document using the API query
call, then request it by ID.

The following example illustrates how to use convertToHex to compute a client response for HTTP Digest Authentication
(RFC2617):

@isTest
private class SampleTest {
static testmethod void testConvertToHex() {
String myData = 'A Test String';
Blob hash = Crypto.generateDigest('SHA1',Blob.valueOf(myData));
String hexDigest = EncodingUtil.convertToHex(hash);
System.debug(hexDigest);
}
}

Knowledge Management Publishing Service Class

Usage
Use the methods in the KbManagement.PublishingService class to manage the following parts of the lifecycle of an
article and its translations:

634
Reference Apex Classes

• Publishing
• Updating
• Retrieving
• Deleting
• Submitting for translation
• Setting a translation to complete or incomplete status
• Archiving
• Assigning review tasks for draft articles or translations

Note: Date values are based on GMT.

To use the methods in this class, you must enable Salesforce Knowledge. See Salesforce Knowledge Implementation Guide
for more information on setting up Salesforce Knowledge.

Methods
The following are static methods of the KbManagement.PublishingService class.

Method Arguments Return Description


Type
archiveOnlineArticle String articleId Void Archives an online version of an article. If
scheduledDate is null, the article is archived
Datetime
immediately. Otherwise, it archives the article on
scheduledDate
the scheduled date.

String articleId = 'Insert article


ID';
Datetime scheduledDate =
Datetime.newInstanceGmt(2012,
12,1,13,30,0);
KbManagement.PublishingService.
archiveOnlineArticle (articleId,
scheduledDate);

assignDraftArticleTask String articleId Void Assigns a review task related to a draft article.
String articleId = 'Insert article
String assigneeID ID';
String String assigneeId = 'Insert assignee
ID';
instructions String instructions = 'Please review
this draft.';
Datetime dueDate Datetime dueDate =
Boolean Datetime.newInstanceGmt(2012, 12,1);
KbManagement.PublishingService.
sendEmailNotification assignDraftArticleTask (articleId,
assigneeId, instructions, dueDate,
true);

assignDraftTranslationTask String Void Assigns a review task related to a draft translation.


articleVersionId String articleId = 'Insert article
ID';
String assigneeID String assigneeId = 'Insert assignee
ID';

635
Reference Apex Classes

Method Arguments Return Description


Type
String String instructions = 'Please review
instructions this draft.';
Datetime dueDate =
DatetimedueDate Datetime.newInstanceGmt(2012, 12,1);
KbManagement.PublishingService.
Boolean assignDraftTranslationTask
(articleId, assigneeId,
sendEmailNotification
instructions, dueDate, true);

cancelScheduledArchiving String articleId Void Cancels the scheduled archiving of an online article.
OfArticle String articleId = 'Insert article
ID';
KbManagement.PublishingService.
cancelScheduledArchivingOfArticle
(articleId);

cancelScheduledPublication String articleId Void Cancels the scheduled publication of a draft article.
OfArticle String articleId = 'Insert article
ID';
KbManagement.PublishingService.
cancelScheduledPublicationOfArticle
(articleId);

completeTranslation String Void Puts a translation in a completed state that is ready


articleVersionId to publish.
String articleVersionId = 'Insert
article version ID';
KbManagement.PublishingService.
completeTranslation(articleVersionId);

deleteArchivedArticle String articleId Void Deletes an archived article.


String articleId = 'Insert article
ID';
KbManagement.PublishingService.
deleteArchivedArticle(articleId);

deleteArchivedArticleVersion String articleId Void Deletes a specific version of an archived article.


String articleId = 'Insert article
Integer ID';
versionNumber Integer versionNumber = 1;
KbManagement.PublishingService.
deleteArchivedArticleVersion
(articleId, versionNumber);

deleteDraftArticle String articleId Void Deletes a draft article.


String articleId = 'Insert article
ID';
KbManagement.PublishingService.
deleteDraftArticle(articleId);

636

You might also like