The digest()
method of the SubtleCrypto
interface generates a digest of the given data. A digest is a short fixed-length value derived from some variable-length input. Cryptographic digests should exhibit collision-resistance, meaning that it's hard to come up with two different inputs that have the same digest value.
It takes as its arguments an identifier for the digest algorithm to use and the data to digest. It returns a Promise
which will be fulfilled with the digest.
A Promise
that fulfills with an ArrayBuffer
containing the digest.
Digest algorithms, also known as cryptographic hash functions, transform an arbitrarily large block of data into a fixed-size output, usually much shorter than the input. They have a variety of applications in cryptography.
Warning: SHA-1 is now considered vulnerable and should not be used for cryptographic applications.
Note: If you are looking here for how to create an keyed-hash message authentication code (HMAC), you need to use the SubtleCrypto.sign() instead.
This example encodes a message, then calculates its SHA-256 digest and logs the digest length:
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 crypto.subtle.digest('SHA-256', data);
return hash;
}
digestMessage(text)
.then(digestBuffer => console.log(digestBuffer.byteLength));
The digest is returned as an ArrayBuffer
, but for comparison and display digests are often represented as hex strings. This example calculates a digest, then converts the ArrayBuffer
to a hex string:
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);
const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
return hashHex;
}
digestMessage(text)
.then(digestHex => console.log(digestHex));
Note: Chrome 60 added a feature that disables crypto.subtle for non-TLS connections.