How to calculate a hash of a string
Short answer
In Node.js, createHash() from node:crypto calculates a hash. digest('hex') returns it as a hex string:
import { createHash } from 'node:crypto';
const hash = createHash('sha256').update('hello').digest('hex');
console.log(hash);Output:
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824In the browser
In the browser and in modern Node.js, crypto.subtle.digest() works. It returns bytes that you turn into hex yourself:
const sha256 = async (text) => {
const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
return [...new Uint8Array(bytes)].map((b) => b.toString(16).padStart(2, '0')).join('');
};
console.log(await sha256('hello'));Output:
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824A file checksum
A hash of the file content shows whether the file has changed:
import { createHash } from 'node:crypto';
import { readFile, writeFile } from 'node:fs/promises';
await writeFile('data.txt', 'version 1');
const checksum = createHash('md5').update(await readFile('data.txt')).digest('hex');
console.log(checksum.length);Output:
32Common mistake
Do not store passwords as a plain SHA-256 or MD5 hash: they are fast to brute force. For passwords use special slow functions such as scrypt from node:crypto or bcrypt.
import { randomBytes, scryptSync } from 'node:crypto';
const salt = randomBytes(16).toString('hex');
const hash = scryptSync('my password', salt, 64).toString('hex');
console.log(hash.length);Output:
128Functions used in this recipe
- String.prototype.padStart — Pads a string on the left to a given length.
- Number.prototype.toString — Converts a number to a string, including in another numeral system.