0

I am trying to compute the Apex equivalent of the following -

var shaBodyContent = CryptoJS.HmacSHA256(stringToSign, postman.getEnvironmentVariable("HMAC_SS"));

var b64BodyContent = shaBodyContent.toString(CryptoJS.enc.Base64);

Apex:

    Blob mac = Crypto.generateMac('hmacSHA256',blob.valueOf(stringToSign),blob.valueOf(secretAccessKey));
    system.debug('This is the shaBodyContent: ' +mac); // debug log displays Blob[32]

    String signature = EncodingUtil.base64Encode(mac);
    system.debug(This is b64BodyContent :' +signature); 

This, system.debug('This is the shaBodyContent: ' +mac); displays Blob[32] and this, system.debug(This is b64BodyContent :' +signature); displays a string

However when I create a raw signature as follows -

    String authorization_header = 'RouteOne' + ' ' + accessKeyID + ':' + signature;

I get an error.

Status Code: 401

Status Message: Unauthorized

Error Message: "The authenticity of the request could not be verified","developerMessage":"The HMAC-SHA256 headers encoded with the secret key associated with the Access Key Id provided did not match the encoded value provided in the request Authorization header"

1
  • Is the value of b64bodyContent in JS same as the value of signature in Apex?
    – identigral
    Jul 31, 2019 at 22:15

1 Answer 1

0
system.debug('This is the shaBodyContent: ' +mac); // debug log displays Blob[32]

Yes, this is what Blob does when you "debug" it. The output says that it is a binary data object that is 32 bytes in size. To see the actual contents, use EncodingUtil.convertToHex or EncodingUtil.base64Encode:

System.debug('This is the shaBodyContent in hex: '+EncodingUtil.convertToHex(mac));
System.debug('This is the shaBodyContent in base64: '+EncodingUtil.base64encode(mac));

The latter value should match what you see in JS. If not, you've used the wrong key or you formatted the string incorrectly. Working with binary data in Apex is rather non-trivial because of its limited support for binary.

1
  • Thanks @SFDCFOX. Most likely I have formatted the string incorrectly. Aug 2, 2019 at 15:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .