This post goes over how to generate a SHA-256 hexadecimal hash using Node.js and JavaScript in the browser:
Node.js
To generate a SHA-256 hash in Node.js using crypto:
const { createHash } = require('crypto');
function hash(string) {
return createHash('sha256').update(string).digest('hex');
}
Usage:
console.log(hash('foo')); // '2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae'
Demo:
Browser
To generate a SHA-256 hash in the browser using SubtleCrypto:
function hash(string) {
const utf8 = new TextEncoder().encode(string);
return crypto.subtle.digest('SHA-256', utf8).then((hashBuffer) => {
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray
.map((bytes) => bytes.toString(16).padStart(2, '0'))
.join('');
return hashHex;
});
}
Or written in async/await:
async function hash(string) {
const utf8 = new TextEncoder().encode(string);
const hashBuffer = await crypto.subtle.digest('SHA-256', utf8);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray
.map((bytes) => bytes.toString(16).padStart(2, '0'))
.join('');
return hashHex;
}
Usage:
hash('foo').then((hex) => console.log(hex)); // '2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae'
Demo: