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
Ker DeveloperKer Developer 

Encrypting and then Decrypting Using decryptWithManagedIV Problem

Hello EveryBody , 

 

I'm trying to encrypt a Clear Text  (Test Data )using encryptWithManagedIV , I store this in a field . In the same class , I decrypt using  decryptWithManagedIV , the text decrypted is not the same as original text : Test Data , Why ? How can i get the original Data? 

 

Here is the class i used : 

 

for (Account a : accs)
		{
			
			
			
		 Blob key = Crypto.generateAesKey(128);
        // Generate the data to be encrypted. 
    
        Blob data = Blob.valueOf(a.Name);
        // Generate an encrypted form of the data using base64 encoding 
    
       
        // Encrypt and decrypt the data 
    	
        Blob encryptedData = Crypto.encryptWithManagedIV('AES128', key, data);
       
      // a.textcryptee__c=b64Data;
       
        String b64Data = EncodingUtil.base64Encode(data);
      a.textcryptee__c=b64Data;
      
        Blob decryptedData = Crypto.decryptWithManagedIV('AES128', key, encryptedData);
        String b64Decrypted = EncodingUtil.base64Encode(decryptedData);
        
        
        //String b64Decrypted = EncodingUtil.urlEncode(EncodingUtil.base64Encode(decryptedData), 'UTF-8');
		a.TextAcrypter__c=b64Decrypted;
		}

 It is very urgent and i'd like to have your Help ASAP 

 

 

benvkbenvk

I've done this before, so thought i'd just try it out. i wrote a quick test case which all passed:

 

static testmethod void testA(){
Blob key = Crypto.generateAesKey(128);
Blob data = Blob.valueOf('asdf');
String b64Data = EncodingUtil.base64Encode(data);

Blob encryptedData = Crypto.encryptWithManagedIV('AES128', key, data);
Blob decryptedData = Crypto.decryptWithManagedIV('AES128', key, encryptedData);
String b64Decrypted = EncodingUtil.base64Encode(decryptedData);
System.assertEquals('asdf', decryptedData.toString());
System.assertEquals(b64Decrypted, b64Data);
}

 

i think it's exactly the same as you have written but it all passes, so i'm baffled :) sorry i can't help more