Skip to main content
hash - crypto - Node documentation
function hash

Usage in Deno

import { hash } from "node:crypto";
hash(
algorithm: string,
data: BinaryLike,
outputEncoding?: BinaryToTextEncoding,
): string

A utility for creating one-shot hash digests of data. It can be faster than the object-based crypto.createHash() when hashing a smaller amount of data (<= 5MB) that's readily available. If the data can be big or if it is streamed, it's still recommended to use crypto.createHash() instead. The algorithm is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are 'sha256', 'sha512', etc. On recent releases of OpenSSL, openssl list -digest-algorithms will display the available digest algorithms.

Example:

import crypto from 'node:crypto';
import { Buffer } from 'node:buffer';

// Hashing a string and return the result as a hex-encoded string.
const string = 'Node.js';
// 10b3493287f831e81a438811a1ffba01f8cec4b7
console.log(crypto.hash('sha1', string));

// Encode a base64-encoded string into a Buffer, hash it and return
// the result as a buffer.
const base64 = 'Tm9kZS5qcw==';
// <Buffer 10 b3 49 32 87 f8 31 e8 1a 43 88 11 a1 ff ba 01 f8 ce c4 b7>
console.log(crypto.hash('sha1', Buffer.from(base64, 'base64'), 'buffer'));

Parameters

algorithm: string

When data is a string, it will be encoded as UTF-8 before being hashed. If a different input encoding is desired for a string input, user could encode the string into a TypedArray using either TextEncoder or Buffer.from() and passing the encoded TypedArray into this API instead.

optional
outputEncoding: BinaryToTextEncoding = 'hex'

Encoding used to encode the returned digest.

Return Type

string
hash(
algorithm: string,
data: BinaryLike,
outputEncoding: "buffer",
): Buffer

Parameters

algorithm: string
outputEncoding: "buffer"

Return Type

Buffer
hash(
algorithm: string,
data: BinaryLike,
outputEncoding?: BinaryToTextEncoding | "buffer",
): string | Buffer

Parameters

algorithm: string
optional
outputEncoding: BinaryToTextEncoding | "buffer"

Return Type

string | Buffer
Back to top