function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
shrey.tyagi88@tcs.comshrey.tyagi88@tcs.com 

Apex code for Encrytion / Decrytion of a field.---Plz Help!!!!

Hi All,

     I am making a POC to get the feel of encrytion/decrytion of fields in salesforce using apex. Her are my requirements.

 I have a custom object say XYZ__c with field say ABC__c. I want to enter this field in a visual force page , hit encrypt button(command button) that runs the apex code and display encryted text in the output field of the page. Can anyone please help me with the code.

 

Thanks

Shrey Tyagi

Best Answer chosen by Admin (Salesforce Developers) 
sfdcfoxsfdcfox
public with sharing class demoencrypt {

    Blob key;

    public demoencrypt() {
        key = Crypto.generateAesKey(128);
    }

    public PageReference translate() {
        if(mode=='encrypt') {
            result = EncodingUtil.base64Encode(Crypto.encryptwithmanagediv('AES128',key,blob.valueof(source)));
        }
        if(mode=='decrypt') {
            result = Crypto.decryptwithmanagediv('AES128',key,EncodingUtil.base64decode(source)).tostring();
        }
        return null;
    }


    public String result { get; set; }

    public String source { get; set; }

    public String mode { get; set; }
}

 

<apex:page controller="demoencrypt">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockSection columns="1">
                <apex:selectList size="1" value="{!mode}">
                    <apex:selectOption itemValue="encrypt"/>
                    <apex:selectOption itemValue="decrypt"/>
                </apex:selectList>
                <apex:inputText value="{!source}"/>
                <apex:outputText value="{!result}"/>
            </apex:pageBlockSection>
            <apex:pageBlockButtons >
                <apex:commandButton action="{!translate}" value="Translate"/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>

This page demonstrates the basic power of encryption/decryption in salesforce. Obviously, the key generated is lost when the page is reloaded, so normally the key would be stored in a custom setting or database object. The "withmanagediv" is simply used so that we don't need an initialization vector, but you could use the normal encrypt/decrypt methods as well with an IV (this will reduce the output by a decent margin). Finally, do not store the key or IV in the view state at all (this is only a demo page).

 

See: http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_restful_crypto.htm

All Answers

sfdcfoxsfdcfox
public with sharing class demoencrypt {

    Blob key;

    public demoencrypt() {
        key = Crypto.generateAesKey(128);
    }

    public PageReference translate() {
        if(mode=='encrypt') {
            result = EncodingUtil.base64Encode(Crypto.encryptwithmanagediv('AES128',key,blob.valueof(source)));
        }
        if(mode=='decrypt') {
            result = Crypto.decryptwithmanagediv('AES128',key,EncodingUtil.base64decode(source)).tostring();
        }
        return null;
    }


    public String result { get; set; }

    public String source { get; set; }

    public String mode { get; set; }
}

 

<apex:page controller="demoencrypt">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockSection columns="1">
                <apex:selectList size="1" value="{!mode}">
                    <apex:selectOption itemValue="encrypt"/>
                    <apex:selectOption itemValue="decrypt"/>
                </apex:selectList>
                <apex:inputText value="{!source}"/>
                <apex:outputText value="{!result}"/>
            </apex:pageBlockSection>
            <apex:pageBlockButtons >
                <apex:commandButton action="{!translate}" value="Translate"/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>

This page demonstrates the basic power of encryption/decryption in salesforce. Obviously, the key generated is lost when the page is reloaded, so normally the key would be stored in a custom setting or database object. The "withmanagediv" is simply used so that we don't need an initialization vector, but you could use the normal encrypt/decrypt methods as well with an IV (this will reduce the output by a decent margin). Finally, do not store the key or IV in the view state at all (this is only a demo page).

 

See: http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_restful_crypto.htm

This was selected as the best answer
Alex.AcostaAlex.Acosta

Here's a simple encrypt / decrypt class I wrote that would help you out. Pretty much once you have this class decryption and encryption should be cake to eventually display on your vf page.

 

 

public with sharing class Cryptography {
    
    private static Blob cryptoKey;
    
    static {
        String encryptionKey = ''; // <-- 16 character encryption key goes here
        cryptoKey = Blob.valueOf(encryptionKey);
    }
    
    public static String encrypt(String toBeEncryptedString){
        Blob stringToEncrypt = Blob.valueOf(toBeEncryptedString);
        Blob encryption = Crypto.encrypt('AES128', cryptoKey, cryptoKey, stringToEncrypt);
                
        return EncodingUtil.base64Encode(encryption);
    }
    
        public static String decrypt(String encryptedString){
                Blob stringToBlob = EncodingUtil.base64Decode(encryptedString);
                Blob decryption = Crypto.decrypt('AES128', cryptoKey, cryptoKey, stringToBlob);
                
                return decryption.toString();
        }
        
        @isTest
        public static void testCryptography() {
                String testString = 'this is test String';
                String encrypted = Cryptography.encrypt(testString);
                system.assertEquals(Cryptography.decrypt(encrypted), testString); 
        }
}

 

shrey.tyagi88@tcs.comshrey.tyagi88@tcs.com

Thanks a lot for your quick reply alex, It helped a lot!!!

shrey.tyagi88@tcs.comshrey.tyagi88@tcs.com

Hi sfdcfox,

          Your code works perfectly fine. Just wanna know few things here. You are using encryptwithmanagediv , where iv stands for initialization vector. Could you please tell me how and where have you defined it ? I mean , how do we encode/decode using initialization vector, and where do we define /mention this vector?

 

Thanks

shrey.tyagi88@tcs.comshrey.tyagi88@tcs.com
I have
key() As Byte = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}
iv() As Byte = {65, 110, 68, 26, 69, 178, 200, 219}
How can I encrypt using these 2 parametres? Thanks a lot for your help.
sfdcfoxsfdcfox

The IV is "managed" in my example (it is prepended to the actual data so that it can be pulled back out later).

 

Here's a code sample using the bytes you provided:

 

Blob key = EncodingUtil.base64Decode('AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcY'), // 1 through 24
     iv = EncodingUtil.base64Decode('QW5EGkWyyNs='), // 65 110 68 26 69 178 200 219
	 text = Blob.valueOf('data to encrypt goes here'),
	 encryptedData = Crypto.encrypt('AES128', key, iv, text);
String encryptedDataString = EncodingUtil.base64encode(encryptedData);

Other than that, the code is basically the same as I provided previously.