SubtleCrypto

crypto.subtle.digest

Generates a digest (hash) of the given data using the specified algorithm

Syntax

JavaScript
crypto.subtle.digest(algorithm, data)

Parameters

ParameterTypeDescription
algorithmstringThe hash algorithm to use (SHA-1, SHA-256, SHA-384, SHA-512)
dataArrayBuffer | TypedArray | DataViewThe data to hash

Return Value

A Promise that resolves to an ArrayBuffer containing the hash

Examples

Basic Usage
const encoder = new TextEncoder()
const data = encoder.encode('Hello World')
const hash = await crypto.subtle.digest('SHA-256', data)
const hex = Array.from(new Uint8Array(hash))
  .map(b => b.toString(16).padStart(2, '0')).join('')
console.log(hex)
Practical Example
async function sha256(text: string): Promise<string> {
  const data = new TextEncoder().encode(text)
  const buffer = await crypto.subtle.digest('SHA-256', data)
  return Array.from(new Uint8Array(buffer))
    .map(b => b.toString(16).padStart(2, '0')).join('')
}
Advanced Usage
async function checksumFile(file: File): Promise<string> {
  const buffer = await file.arrayBuffer()
  const hash = await crypto.subtle.digest('SHA-256', buffer)
  return Array.from(new Uint8Array(hash))
    .map(b => b.toString(16).padStart(2, '0')).join('')
}

Understanding crypto.subtle.digest

The crypto.subtle.digest method in JavaScript generates a digest (hash) of the given data using the specified algorithm. It belongs to the SubtleCrypto object and is one of the most widely used methods for working with subtlecrypto values in modern JavaScript and TypeScript applications.

The method signature is crypto.subtle.digest(algorithm, data). It accepts 2 parameters: algorithm, data. When called, it returns a promise that resolves to an arraybuffer containing the hash. Understanding when and how to use digest() helps you write more expressive, readable code.

Common use cases for crypto.subtle.digest include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like crypto-getrandomvalues, crypto-subtle-encrypt, enabling you to chain operations together for complex data manipulation pipelines.

Supported in all modern browsers. Requires a secure context (HTTPS).

Browser Compatibility

Supported in all modern browsers. Requires a secure context (HTTPS).

Related Methods

More SubtleCrypto Methods

Other methods in the SubtleCrypto object

Related Tools

More SubtleCrypto Methods

Explore JavaScript Methods

Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.