Node.js – hash.digest() Method


The Hash class is one of the many utility classes that is used for creating the hash digests of data. The hash.digest() method calculates all the data that needs to be hashed passed inside the hash function and returns them. If an encoding is defined, a string will be returned, else a buffer is returned.

Syntax

hash.digest([encoding])

Parameters

It takes a single parameter −

  • encoding − This input parameter takes input for the encoding to be applied while calculating the hash.

Example 1

Create a file with the name "hashDigest.js" and copy the following code snippet. After creating the file, use the command "node hashDigest.js" to run this code.

// hash.digest() Demo Example

// Importing the crypto module
const crypto = require("crypto")

// Creating the hash object in hex encoding
let hexDigest = crypto.createHash('sha256').update('Welcome To
TutorialsPoint').digest('hex')

// Printing the hash value using digests
console.log("Hash is: " + hexDigest)

Output

C:\home
ode>> node hashDigest.js Hash is: 6c37595a919c467f0b3a1876ad0a3933cf3f7a9c3e7fc6bacf59337e0aa35afe

Example 2

Let’s have a look at one more example

 Live Demo

// hash.digest() Demo Example

// Importing the crypto module
const crypto = require("crypto")

// Defining the hash encoding algorithm
let algorithm = "sha256"

// Defining the data to be hashed
let key = "TutorialsPoint"

// Creating the hash in hex encoding
let hexDigest = crypto.createHash(algorithm).update(key).digest("hex")

// Creating the hash in base64 encoding
let base64Digest =
crypto.createHash(algorithm).update(key).digest("base64")

// Printing the hash value using digests
console.log("Hex Encoding: " + hexDigest)
console.log("Base64 encoding: " + base64Digest)

Output

C:\home
ode>> node hashDigest.js Hex Encoding: 62e2de2644fa0987f79f54118c175d6a924e50aa60df1ff38e197eac0da8a963 Base64 encoding: YuLeJkT6CYf3n1QRjBddapJOUKpg3x/zjhl+rA2oqWM=

Updated on: 18-Aug-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements