You need to sign in to do that
Don't have an account?
3 Creeks
Bug using Crypto ans system.runAs() in a test?
I posted this a week or two ago and got no response so posting again in case anyone has any insight or maybe someone from Salesforce can take a look:
I am encrypting and decrypting a string and using a portion of the current user's Id as the seed:
And gives me this output:
But also errors out with "System.SecurityException: Given final block not properly padded" on line 9 in the middle box: String s2Decrypt = decrypt( s2Encrypt ) 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
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" on line 9 in the middle box: String s2Decrypt = decrypt( s2Encrypt ) 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