Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

The SubtleCrypto.digest() method returns a Promise of a digest generated from the hash function and text given as parameters.

Note: Older insecure hash functions, like MD5, are not supported by this method. Even a supported method, SHA-1, is considered weak and should be avoided, at least in any new project.

Syntax

var hash = crypto.subtle.digest(algo, buffer);

Parameters

  • algo is a DOMString defining the hash function to use. Supported values are: SHA-1, SHA-256, SHA-384, and SHA-512.
  • buffer is a ArrayBuffer or an ArrayBufferView containing the data to be hashed using the hashing algorithm.

Return value

  • hash is a Promise that returns the hash on success.

Example

Here's an example that computes the sha256 of a string and display its hex digest.

function sha256(str) {
  // We transform the string into an arraybuffer.
  var buffer = new TextEncoder("utf-8").encode(str);
  return crypto.subtle.digest("SHA-256", buffer).then(function (hash) {
    return hex(hash);
  });
}

function hex(buffer) {
  var hexCodes = [];
  var view = new DataView(buffer);
  for (var i = 0; i < view.byteLength; i += 4) {
    // Using getUint32 reduces the number of iterations needed (we process 4 bytes each time)
    var value = view.getUint32(i)
    // toString(16) will give the hex representation of the number without padding
    var stringValue = value.toString(16)
    // We use concatenation and slice for padding
    var padding = '00000000'
    var paddedValue = (padding + stringValue).slice(-padding.length)
    hexCodes.push(paddedValue);
  }

  // Join all the hex strings into one
  return hexCodes.join("");
}

sha256("foobar").then(function(digest) {
  console.log(digest);
}); // outputs "c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2"

Specifications

Specification Status Comment
Web Cryptography API
The definition of 'SubtleCrypto.digest()' in that specification.
Candidate Recommendation Initial definition.

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (SHA-1 and SHA-2 algorithms) 37 34 (34) No support ? No support
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (SHA-1 and SHA-2 algorithms) (Yes) 37 34.0 (34) No support ? No support

See also

Document Tags and Contributors

 Contributors to this page: teemuremes, pstricker, Sebastianz, GaspardP, ttaubert, tOkeshu, teoli, mesh.a
 Last updated by: teemuremes,