← Back to Blog
2026-03-102 min readby DevUtilz

SHA-256 Hashing Explained

SHA256HashingSecurityTutorial

SHA-256 Hashing Explained

SHA-256 is a cryptographic hash function that produces a 256-bit (32-byte) hash value. It's widely used for data integrity and security.

What is SHA-256?

SHA-256 is part of the SHA-2 family. Given any input, it produces a fixed 64-character hex string:

Input: "hello"
Output: 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

Properties

  1. Deterministic - Same input always produces same output
  2. One-way - Can't reverse to get original input
  3. Collision-resistant - Hard to find two inputs with same hash
  4. Fast to compute - But slow to reverse

Using SHA-256 in JavaScript

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');
console.log(hash); // 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

Common Use Cases

1. Password Storage (with salt)

async function hashPassword(password, salt) {
  const combined = password + salt;
  return await sha256(combined);
}

2. File Integrity

async function getFileHash(file) {
  const buffer = await file.arrayBuffer();
  const hashBuffer = await crypto.subtle.digest('SHA-256', buffer);
  // Convert to hex...
}

3. Digital Signatures

const message = "Transfer $100 to John";
const signature = await sha256(message + privateKey);

Important Security Notes

Never use SHA-256 alone for passwords! Use:

  • bcrypt - Designed for passwords
  • Argon2 - Modern, memory-hard
  • PBKDF2 - Key derivation
// Wrong - simple hash is vulnerable to rainbow tables
const bad = await sha256('mypassword');

// Correct - use bcrypt for passwords
const bcrypt = require('bcrypt');
const hash = await bcrypt.hash('mypassword', 12);

Comparing Hashes

// Constant-time comparison (prevents timing attacks)
function secureCompare(a, b) {
  if (a.length !== b.length) return false;
  let result = 0;
  for (let i = 0; i < a.length; i++) {
    result |= a.charCodeAt(i) ^ b.charCodeAt(i);
  }
  return result === 0;
}

SHA-256 vs Other Algorithms

| Algorithm | Output Size | Speed | Security | |-----------|-------------|-------|----------| | MD5 | 128-bit | Fast | Broken | | SHA-1 | 160-bit | Fast | Weak | | SHA-256 | 256-bit | Fast | Strong | | bcrypt | Variable | Slow | Best for passwords |

Conclusion

SHA-256 is excellent for data integrity and checksums. For password storage, use bcrypt or Argon2. Always use cryptographic libraries rather than implementing your own.