Encrypt and Decrypt Strings with Apex Code

Posted by Andrea on 2011-06-30 11:04

The following code encrypts and decrypts a string with the AES algorithm.
The key is stored in a Custom Setting so that it can be mantained and reset across multiple organizations.

public with sharing class CryptoUtils {
	public static string decrypt(string encryptedString) {
		Blob decryptedData = Crypto.decryptWithManagedIV('AES256', getKey(), EncodingUtil.base64Decode(encryptedString));
		return decryptedData.toString();
	}
	
	public static string encrypt(string plainString) {
		Blob cryptoKey = Crypto.generateAesKey(256);
		Blob encryptedData = Crypto.encryptWithManagedIV('AES256', getKey(), Blob.valueOf(plainString));
		return EncodingUtil.base64Encode(encryptedData);
	}
	
	private static Blob getKey() {
		return EncodingUtil.base64Decode(MySettings__c.getOrgDefaults().MyAESKey__c);
	}
}

This could be of help when you want to pass safely parameters via querystring.

Comments

Julio commented
Gravatar
Ok!! i undestand to use math mod method,

Thanks