Createhash crypto

Comment

Author: Admin | 2025-04-27

I'm trying to hash a variable in NodeJS like so:var crypto = require('crypto');var hash = crypto.createHash('sha256');var code = 'bacon';code = hash.update(code);code = hash.digest(code);console.log(code);But looks like I have misunderstood the docs as the console.log doesn't log a hashed version of bacon but just some information about SlowBuffer.What's the correct way to do this? gevorg5,0555 gold badges38 silver badges54 bronze badges asked Jan 15, 2015 at 18:26 3 digest returns the hash by default in a Buffer. It takes a single parameter which allows you to tell it which encoding to use. In your code example, you incorrectly passed the encoding bacon to digest. To fix this, you need only to pass a valid encoding to the digest(encoding) function.base64:const { createHash } = require('crypto');createHash('sha256').update('bacon').digest('base64');// nMoHAzQuJIBqn2TgjAU9yn8s2Q8QUpr46ocq+woMd9Q=hex:const { createHash } = require('crypto');createHash('sha256').update('bacon').digest('hex');// 9cca0703342e24806a9f64e08c053dca7f2cd90f10529af8ea872afb0a0c77d4 Warren Parad4,0912 gold badges21 silver badges30 bronze badges answered Jan 15, 2015 at 18:31 MaximeFMaximeF5,4034 gold badges39 silver badges54 bronze badges 6 Other way:const {createHash} = require('node:crypto');const result = createHash('sha256').update("bacon").digest('hex');console.log(result); answered Mar 29, 2023 at 2:08 you can use, like this, in here create a reset token (resetToken), this token is used to create a hex version.in database, you can store hex version.// Generate token const resetToken = crypto.randomBytes(20).toString('hex');// Hash token and set to resetPasswordToken fieldthis.resetPasswordToken = crypto .createHash('sha256') .update(resetToken) .digest('hex');console.log(resetToken ) answered Sep 3, 2021 at 12:47 1 nodejs (8) refconst crypto = require('crypto');const hash = crypto.createHash('sha256');hash.on('readable', () => { const data = hash.read(); if (data) { console.log(data.toString('hex')); // Prints: // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 }});hash.write('some data to hash');hash.end(); answered Oct 29, 2017 at 8:16 Mohamed.AbdoMohamed.Abdo2,2001 gold badge20 silver badges12 bronze badges Similar to the answers above, but this shows how to do multiple writes; for example if you read line-by-line from a file and then add each line to the hash computation as a separate operation.In my example, I also trim newlines / skip empty lines (optional):const {createHash} = require('crypto');// lines: array of stringsfunction computeSHA256(lines) { const hash = createHash('sha256'); for (let i = 0; i I use this code ensure generated lines of a file aren't edited by someone manually. To do this, I write the lines out, append a line

Add Comment