+ Start a Discussion
3 Creeks3 Creeks 

Crypto.decrypt() and Crypto.encrypt() not respecting system.runAs( User )?

I am encrypting and decrypting a string and using a portion of the current user's Id as the seed:
public static String encrypt(String s) {
   system.debug( 'In encrypt, user id = ' + UserInfo.getUserId() );
	blob eKey = Blob.valueOf(  String.valueOf(UserInfo.getUserId()).left(16) );
	return EncodingUtil.base64Encode( Crypto.encrypt('AES128', eKey, eKey, blob.valueof(s)) );
}

....

public static String decrypt(String s) {
   system.debug( 'In decrypt, user id = ' + UserInfo.getUserId() );
	blob eKey = Blob.valueOf(  String.valueOf(UserInfo.getUserId()).left(16) );
	return Crypto.decrypt('AES128', eKey, eKey, EncodingUtil.base64decode(s)).toString();
}
Then I have a test that will call these methods as two different users:
static testMethod void myTest() {
   String s1 = 'important Information';
   String s1Encrypt = encrypt( s1 );
   String s1Decrypt = decrypt( s1Encrypt );

   system.runAs( TestDataFactory.aDifferentUser()  ) {
      String s2 = 'more important Information';
      String s2Encrypt = encrypt( s2 );
      String s2Decrypt = decrypt( s2Encrypt );
   }
}
And gives me this output:
DEBUG|In encrypt, user id = 00536000000g6InAAI
DEBUG|In decrypt, user id = 00536000000g6InAAI

....

DEBUG|In encrypt, user id = 00536000001sJvCAAU
DEBUG|In decrypt, user id = 00536000001sJvCAAU

But also errors out with "System.SecurityException: Given final block not properly padded"   which usually means that the seed used to encrypt and decrypt where not the same key.   From the debug statement, it looks like they are so I am wondering if something is not respecting the user id given by system.runAs().

For the now I got around the issue by adding an if statement that looks at Test.isRunningTest() and if so just uses a static string as the key, but I would like to see if anyone has seen this before.

Thanks
3 Creeks3 Creeks
Sorry, realized I did not indicate what line the error is appearing on.   The "System.SecurityException: Given final block not properly padded" is being raised on line 9 in the middle box: String s2Decrypt = decrypt( s2Encrypt );
Thanks