4

Any ideas what I am doing wrong?

Data = '1605470404trashed';
Private Key = '5034eafbf7068b76e4762db248effd77';
Algoithm: SHA256

Actual HMAC generated from service = e4911d1d188c24d313a159d38f1beb06e56c53f87ae0833820aef7c3a3812b96

When I use this service I get the correct HMAC:

https://www.freeformatter.com/hmac-generator.html

When I use this code in salesforce to verify it returns false:

Crypto.verifyHmac(
        'hmacSHA256',
        blob.valueOf('1605470404trashed'),
        blob.valueOf('5034eafbf7068b76e4762db248effd77'),
        blob.valueOf('e4911d1d188c24d313a159d38f1beb06e56c53f87ae0833820aef7c3a3812b96')
);

And when I try to generate the same HMAC I get a value that is nowhere near the result expected:

Blob bdata = Blob.valueOf('1605470404trashed');
Blob encrypted = Crypto.generateMac('HmacSHA256',bdata, blob.valueOf('5034eafbf7068b76e4762db248effd77'));
System.debug( EncodingUtil.base64Encode(encrypted)); 

returns: X4u/2/COJQR1yxUmDcxIp5BxcgYxLz+0X08FB4Bg5Oc=

Any ideas how to verify the HMAC e4911d1d188c24d313a159d38f1beb06e56c53f87ae0833820aef7c3a3812b96 in salesforce using the above information?

Part about generating HMAC is answered by Generating HMAC message digest via Crypto class

Still curious why verifyHMAC returns false. Maybe it cannot be used for this use case?

2
  • Does this answer your question? Generating HMAC message digest via Crypto class It appears instead of base64Encode it should be convertToHex.
    – tugce
    Commented Nov 15, 2020 at 21:11
  • @tugce - It does answer the part about generating. thank you. But it still does not work with the verifyHMAC. I know I could generate it then just do a straight compare but would be interested in if the provided verifyHMAC method could be used
    – Eric
    Commented Nov 15, 2020 at 21:13

1 Answer 1

7

Instead of Blob.valueOf(hmacString) you need to use EncodingUtil.convertFromHex(hmacString) to generate the blob for the HMAC part.

Boolean verified = Crypto.verifyHmac(
        'hmacSHA256',
        blob.valueOf('1605470404trashed'),
        blob.valueOf('5034eafbf7068b76e4762db248effd77'),
        encodingutil.convertFromHex('e4911d1d188c24d313a159d38f1beb06e56c53f87ae0833820aef7c3a3812b96')
);
system.debug(verified); //22:22:16:010 USER_DEBUG [10]|DEBUG|true
1
  • ConvertFromHex it was. Thanks
    – Eric
    Commented Nov 15, 2020 at 22:04

You must log in to answer this question.

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