I have created a public site where a VF page is exposed with a few URL parameter ( Id of a few objects ). Now I want to encrypt those Ids so that there is no security risk.

I was trying to achieve it using Crypto class but the moment I am adding below lines of code in my class, it's asking me to log in.

Blob exampleIv = Blob.valueOf('Example of IV123');
Blob key = Crypto.generateAesKey(128);
Blob data = Blob.valueOf(param);
Blob encrypted = Crypto.encrypt('AES128', key, exampleIv, data); 

or this

Blob key = Crypto.generateAesKey(128);
Blob data = Blob.valueOf(param);
Blob encrypted = Crypto.encryptwithManagedIV('AES128', key, data); 

Depends a little whether you just need a token you can query for in a separate field, or something you can actually decrypt and read the id Assuming the latter, you need to create a key, store it somewhere and then use it to encrypt and decrypt e.g. create a key that is the right length and store the string somewhere safe:

Datetime dt = system.now();
String s = string.valueof(dt);
String s2 = s.replaceAll('\\D','');
String sKey = userinfo.getOrganizationId() +s2;

Encrypt the Id replace [MyId] with your Id to encrypt:

 Blob sKeyBLob = blob.valueOf(sKey);
 Blob cipherText = Crypto.encryptWithManagedIV('AES256', sKeyBLob, Blob.valueOf([MyId]));
 String encodedCipherText = EncodingUtil.convertToHex(cipherText); 
 String encodedId = EncodingUtil.urlEncode(encodedCipherText,'UTF-8') ;
 system.debug('encoded version' + encodedId);

Pass Id to the VF page - and then you take the parameter e.g. sEncryptedId and decrypt using the same key

 Blob sKeyBLob2 = blob.valueOf(sKey);
String sCleanLink = EncodingUtil.urlDecode(sEncryptedId,'UTF-8');
 Blob encodedEncryptedBlob = EncodingUtil.convertFromHex(sCleanLink);
 Blob decryptedBlob = Crypto.decryptWithManagedIV('AES256', sKeyBLob2, encodedEncryptedBlob);
 String decryptedId = decryptedBlob.toString();
 system.debug('decryptedId' + decryptedId);

decryptedId should be the original version of the Id

| improve this answer | |
  • I am getting the same message. Authorization Required. – Salesforce Development May 16 at 17:22
  • Authorization Required means the site is throwing an error, so you need to setup a debug log for that Guest Site user so you can then what the error is – BritishBoyinDC May 16 at 19:08
  • 1
    I was assigning the encrypted String to an Id variable that's why it was throwing an error. It's working now. Thanks a lot. – Salesforce Development May 16 at 19:46

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.