Skip to content

Instantly share code, notes, and snippets.

@acdcjunior
Created May 20, 2024 23:12
Show Gist options
  • Save acdcjunior/3c57b2b2e8df413aa127a05f61d136a7 to your computer and use it in GitHub Desktop.
Save acdcjunior/3c57b2b2e8df413aa127a05f61d136a7 to your computer and use it in GitHub Desktop.
Generate sha256 hash for a buffer - browser and node.js
/*
* Sometimes you want to hash stuff on the client and on the server to test if
* data transmission is happening okay. These functions to that.
*/
// node.js
import crypto from 'node:crypto';
async function calculateHashForArrayBuffer(data: ArrayBuffer) {
return calculateHashForBuffer(Buffer.from(data));
}
async function calculateHashForBuffer(data: Buffer) {
const hash = crypto.createHash('sha256');
hash.update(data);
return hash.digest('hex');
}
// browser
async function calculateHash(data: BufferSource) {
const hashBuffer = await window.crypto.subtle.digest('SHA-256', data);
return Array.from(new Uint8Array(hashBuffer))
.map((b) => b.toString(16).padStart(2, '0'))
.join('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment