Encrypt a password with Salesforce Apex using SHA1

Viewed 296

I need to write a Salesforce Apex code that encrypts a password. This is used to poll an external API for which credentials must follow this encryption model.

The API password encryption requires 3 parameters: a user password, a random 16-char string and a timestamp in format 2022-01-06T17:01:22Z.

The formula is : outputKey = Base64(SHA1($randomString + $timestamp+ SHA1($userPassword)))

A clean encryption would give the following result Inputs:
Password: peanutButter randomString: uniqueCode123456 timestamp: 2022-01-06T17:01:22Z

Expected output: FApp+ayrBcB5XUhygr9lFJLK1p0=

My code currently runs as follows but doesn't deliver the expected outputs. (Note: the variables uniqueCode and timestamp have been hard-coded here for simplicity, but they are generated on each API call).

String uniqueCode = 'uniqueCode123456';
String timestamp = '2015-09-30T14:12:15Z'; 
Blob password = Blob.valueOf(‘peanutButter’);
Blob hashPassword = Crypto.generateDigest('SHA1', password); 
String combinedPassword = uniqueCode + timeStamp + EncodingUtil.convertToHex(hashPassword);

Blob blobCombinedPassword = Blob.valueOf(combinedPassword);
Blob hashedFull = Crypto.generateDigest('SHA1', blobCombinedPassword);
String outputKey = EncodingUtil.base64encode (hashedFull);

What do I need to run differently to generate the correct output?

Thank you

1 Answers

This produces the same result for your input data:

Blob pwd = Crypto.generateDigest('SHA1', Blob.valueOf('peanutButter'));
Blob full = Blob.valueOf('uniqueCode1234562022-01-06T17:01:22Z');
String combo = EncodingUtil.convertToHex(full) + EncodingUtil.convertToHex(pwd);
Blob comboBlob = EncodingUtil.convertFromHex(combo);
Blob finalBlob = Crypto.generateDigest('SHA1', comboBlob);
String finalStr = EncodingUtil.base64Encode(finalBlob);
System.debug(finalStr); // Prints FApp+ayrBcB5XUhygr9lFJLK1p0=

So your error was interpreting combinedPassword as if it was textual which it wasn't when converting to Blob the second time.

Related