Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I have to Hash a text with HMAC sha256 in Javascript

Tags:

javascript

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.

like image 305
Rav Avatar asked Dec 11 '22 07:12

Rav


2 Answers

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=
like image 188
NVRM Avatar answered Jan 04 '23 17:01

NVRM


I think CryptoJS would be able to do it using

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

like image 37
Morten Olsen Avatar answered Jan 04 '23 17:01

Morten Olsen