1

I am trying to encrypt two fields when record is submitted using VF page. As there are multiple functions in my class I am encrypting and decrypting multiple times as needed. Is there a way we can using generic method and call that method when needed?

Here is the code which I am using in multiple functions

Blob cryptoKey = Blob.valueOf('xxxxfff1424389523');
Blob data1 = Blob.valueOf(o.dob__c);
Blob data2 = Blob.valueOf(o.number__c);
Blob encryptedData1 = Crypto.encryptWithManagedIV('AES128', cryptoKey , data1 );
Blob encryptedData2 = Crypto.encryptWithManagedIV('AES128', cryptoKey , data2 );
String b64Data1 = EncodingUtil.base64Encode(encryptedData1);
String b64Data2 = EncodingUtil.base64Encode(encryptedData2);
o.dob__c= b64Data1;
o.number__c= b64Data2 ;
2

Yes, you can always modularize your code.

In your case, the code that can be reused and the simplest it could look is as something below. Note, this is an example based on what you have here, you may need to make adjustments based on what values you want to pass.

private String getEncryptedValue(String key, String valueToEncrypt) {
    Blob cryptoKey = Blob.valueOf(key);
    Blob data = Blob.valueOf(valueToEncrypt);
    Blob encryptedData = Crypto.encryptWithManagedIV('AES128', cryptoKey , valueToEncrypt);
    String b64Data = EncodingUtil.base64Encode(encryptedData);

    return b64Data;
}

And then you can use this function from anywhere in your other code snippets, as:

o.dob__c = getEncryptedValue('xxxxfff1424389523', o.dob__c);
o.number__c = getEncryptedValue('xxxxfff1424389523', o.number__c);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.