CodeBlanks Logo Icon CodeBlanks

createHash

Learn to create hashes with crypto.createHash.

createHash

crypto.createHash(algorithm) creates a hash generator. You feed data with update(data) and take the hash with digest(format). Chaining is common.

Example: crypto.createHash("sha256").update("hello").digest("hex"). "sha256" is the algorithm; "hex" is the output format (hexadecimal). Other formats: "base64" gives a shorter string; "latin1" is rarer. update() can be called multiple times; data is concatenated. After digest() the generator cannot be reused. SHA-256 output is always 64 hex characters (256 bits = 32 bytes). For password storage sha256 alone is not enough; salt and slow algorithms are needed.

update and digest

update() can feed data piece by piece. For large files you stream data in; you use less memory. digest() finalizes and returns the hash.

Example: const h = crypto.createHash("sha256"); h.update("part1"); h.update("part2"); h.digest("hex");. This gives the same hash as update("part1part2") because data is concatenated. digest("hex") returns a hex string; digest("base64") a shorter string. After calling digest() calling update() throws; the generator is single-use. To hash the same data again you need a new createHash call. This is why chaining is practical: it finishes all steps in one line.

Practice Hash a string with SHA-256

Import with const crypto = require("node:crypto");. Get a hash with const hash = crypto.createHash("sha256").update("merhaba").digest("hex");. Print the first 16 characters with console.log(hash.slice(0, 16)).

Starter code

index.js
// Import the crypto module
// write here

// Hash "merhaba" with SHA-256
// write here

// Print the first 16 characters
// write here

Sample solution

index.js
const crypto = require("node:crypto");
const hash = crypto.createHash("sha256").update("merhaba").digest("hex");
console.log(hash.slice(0, 16));

Expected output

4c6bcdd55f3153e1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the createHash call

Question
const hash = crypto.____("sha256").update("merhaba").digest("hex");
Answer
const hash = crypto.createHash("sha256").update("merhaba").digest("hex");

Explanation: createHash with sha256 creates a hash generator.

2 Match each step to its function

Term Meaning
createHash Creates generator
update Feeds data
digest Finalizes hash
"hex" Hexadecimal format

3 What kind of value does digest("hex") return?

index.js
crypto.createHash("sha256").update("x").digest("hex")
  • A hexadecimal string Correct answer
  • A binary buffer
  • A number
  • Date nesnesi

Explanation: The hex format gives a hex string.

All lessons in Intermediate