SubtleCrypto: phương thức digest()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.

Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

Note: This feature is available in Web Workers.

Phương thức digest() của giao diện SubtleCrypto tạo một digest từ dữ liệu đã cho, sử dụng hash function được chỉ định. Digest là một giá trị có độ dài cố định ngắn được dẫn xuất từ một đầu vào có độ dài thay đổi. Digest mật mã nên thể hiện khả năng chống va chạm, có nghĩa là khó có thể tìm ra hai đầu vào khác nhau có cùng giá trị digest.

Nó nhận làm đối số một định danh cho thuật toán digest sẽ sử dụng và dữ liệu cần digest. Nó trả về một Promise sẽ được fulfill với digest.

Lưu ý rằng API này không hỗ trợ đầu vào dạng streaming: bạn phải đọc toàn bộ đầu vào vào bộ nhớ trước khi truyền nó vào hàm digest.

Cú pháp

js
digest(algorithm, data)

Tham số

algorithm

Đây có thể là một chuỗi hoặc một đối tượng với một thuộc tính duy nhất name là một chuỗi. Chuỗi đặt tên hàm hash sẽ sử dụng. Các giá trị được hỗ trợ là:

  • "SHA-1" (nhưng đừng sử dụng trong các ứng dụng mật mã)
  • "SHA-256"
  • "SHA-384"
  • "SHA-512".
data

Một đối tượng ArrayBuffer, TypedArray hoặc DataView chứa dữ liệu cần digest.

Giá trị trả về

Một Promise được fulfill với một ArrayBuffer chứa digest.

Các thuật toán được hỗ trợ

Các thuật toán digest, còn được gọi là hàm hash, biến đổi một khối dữ liệu có kích thước tùy ý thành đầu ra có kích thước cố định, thường ngắn hơn nhiều so với đầu vào. Chúng có nhiều ứng dụng trong mật mã.

Thuật toán Độ dài đầu ra (bit) Kích thước khối (bit) Đặc tả kỹ thuật
SHA-1 160 512 FIPS 180-4, mục 6.1
SHA-256 256 512 FIPS 180-4, mục 6.2
SHA-384 384 1024 FIPS 180-4, mục 6.5
SHA-512 512 1024 FIPS 180-4, mục 6.4

Warning: SHA-1 hiện được coi là dễ bị tấn công và không nên sử dụng cho các ứng dụng mật mã.

Note: Nếu bạn đang tìm cách tạo mã xác thực thông báo dựa trên hash (HMAC), bạn cần sử dụng SubtleCrypto.sign() thay thế.

Ví dụ

Để biết thêm ví dụ về cách sử dụng API digest(), xem Các công dụng phi mật mã của SubtleCrypto.

Ví dụ cơ bản

Ví dụ này mã hóa một thông báo, sau đó tính digest SHA-256 của nó và ghi log độ dài digest:

js
const text =
  "An obscure body in the S-K System, your majesty. The inhabitants refer to it as the planet Earth.";

async function digestMessage(message) {
  const encoder = new TextEncoder();
  const data = encoder.encode(message);
  const hash = await window.crypto.subtle.digest("SHA-256", data);
  return hash;
}

digestMessage(text).then((digestBuffer) =>
  console.log(digestBuffer.byteLength),
);

Chuyển đổi digest thành chuỗi hex

Digest được trả về dưới dạng ArrayBuffer, nhưng để so sánh và hiển thị, digest thường được biểu diễn dưới dạng chuỗi hex. Ví dụ này tính một digest, sau đó chuyển ArrayBuffer thành chuỗi hex:

js
const text =
  "An obscure body in the S-K System, your majesty. The inhabitants refer to it as the planet Earth.";

async function digestMessage(message) {
  const msgUint8 = new TextEncoder().encode(message); // encode as (utf-8) Uint8Array
  const hashBuffer = await window.crypto.subtle.digest("SHA-256", msgUint8); // hash the message
  const hashHex = new Uint8Array(hashBuffer).toHex(); // Convert ArrayBuffer to hex string.
  return hashHex;
}

digestMessage(text).then((digestHex) => console.log(digestHex));

Ví dụ trên sử dụng Uint8Array.toHex(), đã có sẵn từ năm 2025. Để hỗ trợ các trình duyệt cũ hơn, có thể sử dụng phương án thay thế sau:

js
const text =
  "An obscure body in the S-K System, your majesty. The inhabitants refer to it as the planet Earth.";

async function digestMessage(message) {
  const msgUint8 = new TextEncoder().encode(message); // encode as (utf-8) Uint8Array
  const hashBuffer = await window.crypto.subtle.digest("SHA-256", msgUint8); // hash the message
  if (Uint8Array.prototype.toHex) {
    // Use toHex if supported.
    return new Uint8Array(hashBuffer).toHex(); // Convert ArrayBuffer to hex string.
  }
  // If toHex() is not supported, fall back to an alternative implementation.
  const hashArray = Array.from(new Uint8Array(hashBuffer)); // convert buffer to byte array
  const hashHex = hashArray
    .map((b) => b.toString(16).padStart(2, "0"))
    .join(""); // convert bytes to hex string
  return hashHex;
}

digestMessage(text).then((digestHex) => console.log(digestHex));

Đặc tả kỹ thuật

Specification
Web Cryptography Level 2
# SubtleCrypto-method-digest

Tương thích trình duyệt

Xem thêm