5

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.

Andreas
  • 20,797
  • 7
  • 44
  • 55
Rav
  • 63
  • 1
  • 1
  • 6
  • 4
    Possible duplicate of [Are there any SHA-256 javascript implementations that are generally considered trustworthy?](https://stackoverflow.com/questions/18338890/are-there-any-sha-256-javascript-implementations-that-are-generally-considered-t) – Gabriel Santos Mar 03 '18 at 07:46
  • 1
    browser or server side? – Jaromanda X Mar 03 '18 at 08:15

2 Answers2

12

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);
  [...new Uint8Array(s)].map(b => b.toString(16).padStart(2, '0')).join('');
  return btoa(String.fromCharCode(...new Uint8Array(s)))
}

/* TEST */
HMAC("mypassword", "Hello world!")
 .then(e => console.log(e))
NVRM
  • 8,789
  • 1
  • 69
  • 80
  • 1
    This is really helpful! No external dependencies, just a tiny function to take care of it - thanks a lot man! – Jay Dadhania Jan 19 '21 at 09:57
  • 3
    Thanks, very helpful. I changed your function g() to use the TextEncoder. const encoder = new TextEncoder() const messageBytes = encoder.encode(message) – RodP Apr 18 '21 at 14:40
  • why is the js output different from the nodejs output? – Israel Obanijesu May 11 '21 at 08:06
  • Doesn't work, For instance try with message='a' and key='b'. This outputs 'y0SLRAxCrIrQhPyKh5XJj1t4AjWcMF6r1X7Nsg4kiJY=' instead of cb448b440c42ac8ad084fc8a8795c98f5b7802359c305eabd57ecdb20e248896 – KVM May 01 '22 at 10:33
3

I think CryptoJS would be able to do it using

CryptoJS.HmacSHA256(current_user.email, 'HFgGgIOaLiyFgUhIjirOoqxloHuiLNr20jkhXrNw') .toString(CryptoJS.enc.Hex)

Morten Olsen
  • 1,699
  • 13
  • 18