Back to cheatsheets
Cryptography
Hashing with Web Crypto API
Generate SHA-256/384/512 cryptographic hashes in the browser — text and file hashing.
What you'll learn
- SHA-256 hash of text
- File hashing
- All algorithms at once
How to use these snippets
- Click the Copy button next to any snippet to copy it to your clipboard.
- Paste the code into your project, IDE, or terminal.
- Replace placeholder values (like
example.comoryour-secret) with your actual data. - Review the code comments for important security notes and caveats.
- Try the interactive related tool to see the concept in action.
Code Snippets
Copy-paste code snippets
3 ready-to-use snippets for hashing with web crypto api. Click copy and paste into your project.
SHA-256 hash of text
async function sha256(text) {
const data = new TextEncoder().encode(text);
const buf = await crypto.subtle.digest('SHA-256', data);
return Array.from(new Uint8Array(buf))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
}
File hashing
async function hashFile(file) {
const buffer = await file.arrayBuffer();
const buf = await crypto.subtle.digest(
'SHA-256', buffer
);
return Array.from(new Uint8Array(buf))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
}
// Usage: drag-drop file, then
// const hash = await hashFile(droppedFile);
All algorithms at once
async function hashAll(text) {
const data = new TextEncoder().encode(text);
const algos = ['SHA-1', 'SHA-256', 'SHA-384', 'SHA-512'];
const results = {};
for (const algo of algos) {
const buf = await crypto.subtle.digest(algo, data);
results[algo] = Array.from(new Uint8Array(buf))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
}
return results;
}
Tool
Related ShieldX tool
Try this concept hands-on with the interactive tool.
100% Free · No signup · No cost
Generate something unguessable right now
148 bits of entropy, a crack-time estimate you can trust, and a clipboard that clears itself after 30 seconds.
Part of the Toolly ecosystem · secure.toolly.site