How to compute an SHA256 hash and Base64 String encoding in JavaScript/Node
Asked Answered
M

2

9

I am trying to recreate the following C# code in JavaScript.

SHA256 myHash = new SHA256Managed();
Byte[] inputBytes = Encoding.ASCII.GetBytes("test");
myHash.ComputeHash(inputBytes);
return Convert.ToBase64String(myHash.Hash);

this code returns "n4bQgYhMfWWaL+qgxVrQFaO/TxsrC4Is0V1sFbDwCgg="

This is what I have so far for my JavaScript code

var sha256 = require('js-sha256').sha256;
var Base64 = require('js-base64').Base64;

var sha256sig = sha256("test");

return Base64.encode(sha256sig);

the JS code returns "OWY4NmQwODE4ODRjN2Q2NTlhMmZlYWEwYzU1YWQwMTVhM2JmNGYxYjJiMGI4MjJjZDE1ZDZjMTViMGYwMGEwOA=="

These are the 2 JS libraries that I have used

js-sha256

js-base64

Does anybody know how to make it work ? Am I using the wrong libs ?

Millepore answered 10/5, 2016 at 2:22 Comment(0)
N
17

You don't need any libraries to use cryptographic functions in NodeJS.

const crypto = require('crypto');

const hash = crypto.createHash('sha256')
                   .update('test')
                   .digest('base64');
console.log(hash); // n4bQgYhMfWWaL+qgxVrQFaO/TxsrC4Is0V1sFbDwCgg=
Nonsuit answered 10/5, 2016 at 3:0 Comment(0)
J
1

If your target user using modern browser such as chrome and edge, just use browser Crypto API:

const text = 'stackoverflow';

async function digestMessage(message) {
  const msgUint8 = new TextEncoder().encode(message);                           // encode as (utf-8) Uint8Array
  const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8);           // hash the message
  const hashArray = Array.from(new Uint8Array(hashBuffer));                     // convert buffer to byte array
  const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join(''); // convert bytes to hex string
  return hashHex;
}

const result = await digestMessage(text);
console.log(result)

Then you could verify the result via online sha256 tool.

Jacintojack answered 23/12, 2022 at 7:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.