1

Trying to generate a hash of a HMAC Sring in Salesforce. The hash generated using APEX in Salesforce is not identical when compared to a hash generated by JS code on the same message. Am I doing anything wrong, please help

let hmac = crypto.createHmac("sha256", 'KEY_HASH');
    hmac.update('some string');
    let hash = hmac.digest('hex');

Generated Digest/Hash: d3db519bb2c64dd3777be06f970d6d8533a1e3b1d5d6b9fa4b945ec27cea8e4d

Blob blobHMAC = Crypto.generateMac('hmacSHA256', Blob.valueOf('some string'), Blob.valueOf(keyHash));
Blob hash = Crypto.generateDigest('SHA-256', blobHMAC);a
EncodingUtil.convertToHex(hash);

Generated Digest/Hash: d02debb0549e98cc71eb8ec55b1abb62d524de3742c908703d5654324fedd732

0

1 Answer 1

4

Removing line 2 from your apex code will generate a hash that is equal to the javascript code example.

const crypto = require('crypto')

let hmac = crypto.createHmac("sha256", 'KEY_HASH');
hmac.update('some string');
let hash = hmac.digest('hex');

// cae5ae339f9833f66350c3ca84d4ab4202d924a176b53078a83d240ffb7fb4b6
Blob blobHMAC = Crypto.generateMac('hmacSHA256', Blob.valueOf('some string'), Blob.valueOf('KEY_HASH'));

EncodingUtil.convertToHex(blobHMAC);

// cae5ae339f9833f66350c3ca84d4ab4202d924a176b53078a83d240ffb7fb4b6
1
  • 1
    It worked, thank you Tyler.
    – Vamsi
    Commented Mar 7, 2022 at 12:30

You must log in to answer this question.

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