Code Example
// Browser: Web Crypto API (SHA-256)
async function sha256(message) {
const msgBuffer = new TextEncoder().encode(message);
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}
// Usage
const hash = await sha256('Hello World');
console.log(hash);
// Node.js: crypto module
const crypto = require('crypto');
// SHA-256
const sha256 = crypto.createHash('sha256').update('Hello World').digest('hex');
console.log(sha256);
// MD5
const md5 = crypto.createHash('md5').update('Hello World').digest('hex');
console.log(md5);
// SHA-1
const sha1 = crypto.createHash('sha1').update('Hello World').digest('hex');
console.log(sha1);
// HMAC
const hmac = crypto.createHmac('sha256', 'secret-key')
.update('Hello World')
.digest('hex');
console.log(hmac);
// Hash file
const fs = require('fs');
const fileHash = crypto.createHash('sha256');
const stream = fs.createReadStream('file.txt');
stream.on('data', chunk => fileHash.update(chunk));
stream.on('end', () => console.log(fileHash.digest('hex')));
Key Points: Browser uses Web Crypto API (async, limited algorithms). Node.js crypto module supports MD5, SHA-1, SHA-256, SHA-512, HMAC.