NodeJS SHA1 get raw output (PHP SHA1 raw output equivalent) - node.js

In PHP, the code below returns the raw output of the SHA1 of the "string"
sha1("string", true);
What is the nodeJS equivalent of getting the SHA1 raw output?
Edit: I made some test and this line:
crypto.createHash('sha1').update('string').digest('base64');
generates same output as php's
base64_encode(sha1('string', true));
My issue occurs when I try to concatenate a string and the result of sha1, the get the sha1 again:
base64_encode(sha1(sha1("string", true) . "another string", true))
Different with nodejs:
var stringhash = crypto.createHash('sha1').update('string').digest();
crypto.createHash('sha1').update("another string" + stringhash).digest('base64')

Something like this:
const crypto = require('crypto');
let digest = crypto.createHash('sha1').update('string').digest();
process.stdout.write( digest );
EDIT: the equivalent of your second example:
let hash1 = crypto.createHash('sha1').update('string').digest();
let hash2 = crypto.createHash('sha1').update(hash1).update('another string');
let digest = hash2.digest('base64');

Related

Node js equivalent to Python utf8, Sha1, base64

I have this piece of code in python3
payload = 'my URI'
payload_utf8 = payload.encode("utf-8")
print(payload_utf8)
payload_sha1 = hashlib.sha1(payload_utf8).digest()
print(payload_sha1)
payload_base64 = base64.b64encode(payload_sha1)
print(payload_base64)
I want the same result but in node.js. I have tried this
const payload = "my URI";
console.log(payload);
const payload_UTF8 = utf8.encode(payload);
console.log(payload_UTF8);
const payload_Sha = crypto.createHash('sha1').update(payload_UTF8).digest()
console.log(payload_Sha);
const payload_Base64 = Buffer.from(payload_Sha).toString('base64');
But the results isn't the same.
The results are the same, the only difference is that in the python example you're returning a byte array and in the Js example, you're returning a string. If you want to get the exact same result in string format you can use print(payload_base64.decode("utf-8")).

Different result in NodeJS calculating MD5 hash using crypo

I am trying to get the MD5 has from a number in NodeJS using crypto but I am getting a different hash returned then I get from site where I can calculate the has.
According to http://onlinemd5.com/ the MD5 has for 1092000 is AF118C8D2A0D27A1D49582FDF6339B7C.
When I try to calculate the hash for that number in NodeJS it gives me a different result (ac4d61a5b76c96b00235a124dfd1bfd1). My code:
const crypto = require('crypto');
const num = 1092000;
const hash = crypto.createHash('md5').update(toString(num)).digest('hex');
console.log(hash);
If you convert it to a string normally it works:
const hash = crypto.createHash('md5').update(String(num)).digest('hex'); // or num.toString()
See the difference:
toString(num) = [object Undefined]
(1092000).toString() = "1092000"
If you console.log(this) in a Node env by default you will see that it is:
this = {} typeof = 'object'
this in a Node env is pointing at module.exports so you're calling this toString on the Object.prototype which is not the right thing to do a string conversion on anything other than module.exports.

Converting a Password Hashing Script from GO to Nodejs

I have a hard time converting an existing GO script to NodeJS. It basically a hashing script which takes in 2 arguments agreedUponKey and salt and returns a password hash.
package main
import (
"fmt"
"hash"
"crypto/sha256"
)
func main() {
var agreedUponKey string
var salt string
var h hash.Hash
agreedUponKey = "giri"
salt = "XYZabc987"
h = sha256.New()
h.Write([]byte(agreedUponKey))
h.Write([]byte(salt))
sha256Sum := h.Sum(nil)
print("calculated passwordHash:", sha256Sum)
var hexHash = make([]byte, 0, 64)
for _, v := range sha256Sum {
hexHash = append(hexHash,[]byte(fmt.Sprintf("%02x", v))...)
}
print("calculated passwordHash:", string(hexHash))
}
I have managed to code up to the below point
var crypto = require('crypto');
var convert = require('convert-string');
function test(pwd,key) {
console.log("Password :",pwd);
var byteKey=convert.stringToBytes(key);
var bytePwd=convert.stringToBytes(pwd);
var hash = crypto.createHash('sha256').update(byteKey+bytePwd).digest('base64');
console.log("hashcode of password :",hash);
};
test("XYZabc987","giri");
The 2 hashes are different. Any help would be greatly appreciated. I am a Noob in GO Lang
Please Note : You can use https://play.golang.org/ to compile and run the Go Script
var crypto = require('crypto');
function test(pwd, key) {
var input = key.concat(pwd)
var hash = crypto.createHash('sha256').update(input).digest('hex');
console.log("hashcode of password :", hash);
};
test("XYZabc987", "giri");
You could verify the correct hash using this online tool.

Using SHA-256 with NodeJS Crypto

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?
base64:
var crypto = require('crypto');
const hash = crypto.createHash('sha256').update(input).digest('base64');
hex:
var crypto = require('crypto')
const hash = crypto.createHash('sha256').update(input).digest('hex');
nodejs (8) ref
const 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();
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 field
this.resetPasswordToken = crypto
.createHash('sha256')
.update(resetToken)
.digest('hex');
console.log(resetToken )
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 strings
function computeSHA256(lines) {
const hash = createHash('sha256');
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim(); // remove leading/trailing whitespace
if (line === '') continue; // skip empty lines
hash.write(line); // write a single line to the buffer
}
return hash.digest('base64'); // returns hash as string
}
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 like sha256:<hash> with the sha265-sum, and then, upon next run, verify the hash of those lines matches said sha265-sum.

Node.js and crypto library

I'm having weird issues with Node's crypto library. I wrote this simple AES testing script:
var cipher = crypto.createCipher('aes-256-cbc','InmbuvP6Z8')
var text = "123|123123123123123";
cipher.update(text,'utf8','hex')
var crypted = cipher.final('hex')
var decipher = crypto.createDecipher('aes-256-cbc','InmbuvP6Z8')
decipher.update(crypted,'hex','utf8')
var dec = decipher.final('utf8')
When I do console.log(dec), it's null. For some reason if I set test to "123|123123", it works. So why does "123|123123" work but "123|123123123123123" doesn't?
You need to store the return from cipher.update as well as cipher.final to be sure you have everything.
cipher.update "returns the enciphered contents, and can be called many times with new data as it is streamed":
http://nodejs.org/docs/v0.2.5/api.html#cipher-update-247
cipher.final "returns any remaining enciphered contents".
I think you just append the results with each call like this:
var crypto = require('crypto');
var cipher = crypto.createCipher('aes-256-cbc','InmbuvP6Z8');
var text = "123|123123123123123";
var crypted = cipher.update(text,'utf8','hex');
crypted += cipher.final('hex');
var decipher = crypto.createDecipher('aes-256-cbc','InmbuvP6Z8');
var dec = decipher.update(crypted,'hex','utf8');
dec += decipher.final('utf8');
I get '12443a347e8e5b46caba9f7afc93d71287fbf11169e8556c6bb9c51760d5c585' for crypted and '123|123123123123123' for dec in the above with node v0.2.5
RandomEtc is correct, but just in case anyone stumbling on this question is using 'base64' as their encoding: Don't. Stick to 'hex'. At least as of 0.4.2, there's a bug that can result in corrupted data when 'base64' is used. See: https://github.com/joyent/node/issues/738/
Please note that the += operator will not work in later versions of node.js. Please follow the advice given in Node.js Crypto class returning different results with updated version and use Buffer.concat()

Resources