Last active
June 5, 2020 21:43
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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= |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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