Skip to content

Instantly share code, notes, and snippets.

@mrk21
Last active June 5, 2020 21:43
Show Gist options
  • Save mrk21/2a83583083043290c76a5070e5d60b99 to your computer and use it in GitHub Desktop.
Save mrk21/2a83583083043290c76a5070e5d60b99 to your computer and use it in GitHub Desktop.
HMAC SHA256 digest of CryptoJS does not match it of OpenSSL, so should use jsSHA instead of CryptoJS.
const cryptoJsHmacSHA256Digest = (key, data) => {
const hmac = CryptoJS.HmacSHA256(data, key);
const buffer = new ArrayBuffer(hmac.sigBytes);
const dv = new DataView(buffer);
hmac.words.forEach((v, i) => dv.setInt32(4*i, v, false));
let digest = '';
for (let i = 0; i < hmac.sigBytes; i++) {
digest += String.fromCharCode(dv.getUint8(i));
}
return digest;
};
const jsShaHmacSHA256Digest = (key, data) => {
const shaObj = new jsSHA("SHA-256", "TEXT", {
hmacKey: { value: key, format: "BYTES" },
});
shaObj.update(data);
return shaObj.getHash("BYTES");
};
const key = atob('Qs+L5/Pgxm95mtDXm78tOAAuNqjvo66e5SWwqmNoIOI=');
const data = 'data';
console.log(btoa(cryptoJsHmacSHA256Digest(key, data))); //=> mOMPodWFe0tgu3HkfnZPM6hB36NHkB7Z1fYnY/b8T3w=
console.log(btoa( jsShaHmacSHA256Digest(key, data))); //=> 6lViS0n/FZarze0nVewa+Sjel9aeD9sbpWx/c8gvyoQ=
key = Base64.dencode64('Qs+L5/Pgxm95mtDXm78tOAAuNqjvo66e5SWwqmNoIOI=')
data = 'data'
digest = OpenSSL::HMAC.digest(OpenSSL::Digest::SHA256.new, key, data)
puts Base64.encode64(digest) #=> 6lViS0n/FZarze0nVewa+Sjel9aeD9sbpWx/c8gvyoQ=
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment