Node.js hash.digest() Method
The hash.digest( ) method is an inbuilt function of the crypto module’s Hash class. This is used to create the digest of the data which is passed when creating the hash. For example, when we create a hash we first create an instance of Hash using crypto.createHash() and then we update the hash content using the update( ) function but till now we did not get the resulting hash value, So to get the hash value we use the digest function which is offered by the Hash class.
This function takes a string as an input which defines the type of the returning value for example hex or base64. If you leave this field you will get Buffer as a result.
Syntax:
hash.digest([encoding])
Parameter: This function takes the following one parameter:
- encoding: This method takes an optional parameter that defines the type of returning output. You can use ‘hex’ or ‘base64’ as a parameter.
Module Installation: Install the required module using the following command:
npm install crypto
Return Value: This function returns a String when the parameter is passed and returns a Buffer object when no parameter is passed. Suppose we passed parameter base64 then the return value will be a string of base64 encoding.
Example 1: Generating hash values of the string GeeksForGeeks in the form of a hex and base64.
// Importing the crypto library
const crypto = require("crypto")
// Defining the algorithm
let algorithm = "sha256"
// Defining the key
let key = "GeeksForGeeks"
// Creating the digest in hex encoding
let digest1 = crypto.createHash(algorithm).update(key).digest("hex")
// Creating the digest in base64 encoding
let digest2 = crypto.createHash(algorithm).update(key).digest("base64")
// Printing the digests
console.log("In hex Encoding : \n " + digest1 + "\n")
console.log("In base64 encoding: \n " + digest2)