FileDummy Logo
FileDummy
Bảo Mật & Toàn Vẹn Tệp Tin

Cách Băm (Hash) File Trong JavaScript: SHA-256, MD5 và SHA-1

Tính toán checksum toàn vẹn file trong JavaScript sử dụng Web Crypto API (SHA-256) và Node.js crypto stream. Tặng kèm file mẫu để đối soát.

14 tháng 9, 20269 phút đọc1,420 lượt xem
javascriptcryptographysha256checksumweb-crypto

Calculating cryptographic hashes of files is fundamental for data deduplication, tamper verification, and integrity checks. Modern browsers provide the high-performance Web Crypto API for SHA-256 and SHA-512, while Node.js offers the native crypto module with streaming support.

Tính Mã Băm Với Web Crypto API Trên Trình Duyệt

The Web Crypto API runs inside the browser engine using hardware-accelerated cryptographic primitives:

TypeScript
export async function calculateFileSha256(file: File): Promise<string> {
  const arrayBuffer = await file.arrayBuffer();
  const hashBuffer = await crypto.subtle.digest('SHA-256', arrayBuffer);

  // Convert ArrayBuffer to Hex string
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  const hexHash = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');

  return hexHash;
}
Verified Test Asset.txt

Download our 1MB text file with deterministic content to test your SHA-256 hash algorithm.

Tải File Mẫu 1MB TXT →

Truyền Luồng Tính Hash Trong Node.js (Tệp Lớn)

When hashing multi-gigabyte files in Node.js, loading the entire file into memory with fs.readFileSync causes out-of-memory crashes. Use streaming transforms instead:

TypeScript
import fs from 'fs';
import crypto from 'crypto';

export function getFileChecksum(filePath: string, algorithm = 'sha256'): Promise<string> {
  return new Promise((resolve, reject) => {
    const hash = crypto.createHash(algorithm);
    const stream = fs.createReadStream(filePath);

    stream.on('data', (chunk) => hash.update(chunk));
    stream.on('end', () => resolve(hash.digest('hex')));
    stream.on('error', (err) => reject(err));
  });
}

Khi Nào Nên Dùng MD5 vs SHA-256

  • MD5: Cryptographically broken. Do not use for password hashing, digital signatures, or security checks. Still widely used for non-security checksums, such as AWS S3 ETag verification and local file caching keys.
  • SHA-256: Strong cryptographic collision resistance. The industry benchmark for software releases, package integrity, and blockchain transactions.
NDL

Nguyễn Đại Long

Tác Giả

Backend Lead • Chuyên gia Kiến trúc Hệ thống Phân tán & Lưu trữ Đám mây

Hơn 4 năm kinh nghiệm thiết kế các hệ thống xử lý tệp tải lên thông lượng lớn, tối ưu hóa cơ sở dữ liệu và hạ tầng phân tán Cloudflare R2 / AWS S3. Người sáng lập FileDummy và Mạng lưới Hệ sinh thái NDL.

Bài viết này có hữu ích không?

Bấm Thích để ủng hộ tác giả và giúp bài viết lan tỏa tới cộng đồng lập trình viên.

Thảo Luận Kỹ Thuật & Đóng Góp Ý Kiến (0)

Chia sẻ kết quả benchmark, phản hồi các trường hợp biên hoặc đặt câu hỏi chuyên môn.

0/3000

Chưa có bình luận nào. Hãy là lập trình viên đầu tiên bắt đầu cuộc thảo luận!

Câu Hỏi Thường Gặp (FAQ)

Should I use MD5 or SHA-256 for file integrity checks?

For security-critical applications, always use SHA-256 or SHA-512. MD5 is cryptographically broken and should only be used for non-security checksums like deduplication or cache keys.

How do I hash a large file without loading it into memory?

In Node.js use crypto.createHash('sha256') as a Transform stream with pipe(). In the browser, use the Web Crypto API with SubtleCrypto.digest() processing chunks via ReadableStream.

Can I compute a file hash entirely in the browser?

Yes. The Web Crypto API (crypto.subtle.digest) is available in all modern browsers. Read the file using FileReader as an ArrayBuffer, then pass it to subtle.digest('SHA-256'). MD5 requires a third-party library since it is not in the Web Crypto API.

Bài Viết Liên Quan