I am trying to Hash a text using HMAC SHA-256 in Javascript I have [secret Ket]
I have Ruby code to hash, but I need Javascript code to Hash the text
Ruby Code
OpenSSL::HMAC.hexdigest(
'sha256', # hash function
'HFgGgIOaLiyFgUhIjirOoqxloHuiLNr20jkhXrNw', # secret key (keep safe!)
current_user.email # user's email address
)
Please suggest me for any solution.
With the Web crypto native api, taken from this source:
async function HMAC(key, message){
const g = str => new Uint8Array([...unescape(encodeURIComponent(str))].map(c => c.charCodeAt(0))),
k = g(key),
m = g(message),
c = await crypto.subtle.importKey('raw', k, { name: 'HMAC', hash: 'SHA-256' },true, ['sign']),
s = await crypto.subtle.sign('HMAC', c, m);
return btoa(String.fromCharCode(...new Uint8Array(s)))
}
/* TEST */
HMAC("mypassword", "Hello world!")
.then(e => console.log(e))
// jhg4cIbXnNicUx6BeG9EKEQHLp6NuBVzBp1d5D1Ghw4=
I think CryptoJS would be able to do it using
CryptoJS.HmacSHA256(current_user.email, 'HFgGgIOaLiyFgUhIjirOoqxloHuiLNr20jkhXrNw')
.toString(CryptoJS.enc.Hex)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With