Using SHA-256 with NodeJS Crypto - node.js

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.

Related

Make Nodejs encrypt and decrypt function up to date

I'm trying to make my small function up to date, it generate 2 warnings:
(node:8944) [DEP0106] DeprecationWarning: crypto.createDecipher is deprecated.
(node:8944) Warning: Use Cipheriv for counter mode of aes-256-ctr:
Code:
var crypto = require('crypto'),
algorithm = 'aes-256-ctr',
password = 'd6F3Efeq';
function encrypt(text){
var cipher = crypto.createCipher(algorithm,password)
var crypted = cipher.update(text,'utf8','hex')
crypted += cipher.final('hex');
return crypted;
}
function decrypt(text){
var decipher = crypto.createDecipher(algorithm,password)
var dec = decipher.update(text,'hex','utf8')
dec += decipher.final('utf8');
return dec;
}
This encrypt and decrypt wonderfully, but it generate some errors. I tried the new syntax, and I have a hard time figuring it out. If someone could provide an up to date demo, you're the best. Thank you
PS: I don't want to use createDecipherIv, I only want to use a key if this make sense
Install crypto-js:
npm i --save crypto-js
and use it:
const crypto = require('crypto-js'),
password = 'd6F3Efeq';
function encrypt(text){
const result = crypto.AES.encrypt(text, password);
return result.toString();
}
function decrypt(text){
const result = crypto.AES.decrypt(text, password);
return result.toString(crypto.enc.Utf8);
}
or You can use cryptr

Crypto module is not working with latest node 7.10

The following code snippet is working in Node 0.12.18 (replace Buffer.from to new Buffer) but it's not working with the latest Node version (7.10.0)
Can anybody explain me why this is happening?? Anything is missing in below code.
/* Node.js */
var crypto = require('crypto');
var algorithm = 'aes-256-ctr';
var data = "Dhanet-Kalan-Chittorgarh"
var encryption_key = "VHUz1dxrhsowwEYGqUnPcE4wvAyz7Vmb";
var encryption_data = _encrypt()
console.log('data for encryption :: ' + data);
console.log('encrypted data :: ' + encryption_data);
console.log('decrypted data :: ' + _decrypt(encryption_data));
function _decrypt(_encryption_data){
var decipher, dec, chunks, itr_str;
// remove itr string
itr_str = _encryption_data.substring(_encryption_data.length-24);
_encryption_data = _encryption_data.substring(0, _encryption_data.length-24);
decipher = crypto.createDecipheriv(algorithm, encryption_key, Buffer.from(itr_str, "base64"));
chunks = []
chunks.push( decipher.update( Buffer.from(_encryption_data, "base64").toString("binary")) );
chunks.push( decipher.final('binary') );
dec = chunks.join("");
dec = Buffer.from(dec, "binary").toString("utf-8");
return dec;
}
function _encrypt(){
//random alpha-numeric string
var itr_str = Buffer.from(randomString(16)).toString('base64') ; // "3V5eo6XrkTtDFMz2QrF3og==";
var cipher = crypto.createCipheriv(algorithm, encryption_key, Buffer.from(itr_str, "base64"));
var chunks = [];
chunks.push(cipher.update( Buffer.from(data), 'utf8', 'base64'));
chunks.push(cipher.final('base64'));
var crypted = chunks.join('');
crypted = crypted.concat(itr_str);
return crypted;
}
function randomString(len, an)
{
an = an&&an.toLowerCase();
var str="", i=0, min=an=="a"?10:0, max=an=="n"?10:62;
for(;i++<len;){
var r = Math.random()*(max-min)+min <<0;
str += String.fromCharCode(r+=r>9?r<36?55:61:48);
}
return str;
}
Node.js v6 introduced some backward-incompatible changes to crypto which are causing this.
I've documented the exact reason in this answer, but because that question is related to hashing I'm reluctant to close your question as a duplicate.
The fix is similar, though (you need to pass binary as encoding for decipher.update(), otherwise it will default to utf-8):
chunks.push( decipher.update( Buffer.from(_encryption_data, "base64"), 'binary') );

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.

Generating ECDSA signature with Node.js/crypto

I have code that generates a concatenated (r-s) signature for the ECDSA signature using jsrsasign and a key in JWK format:
const sig = new Signature({ alg: 'SHA256withECDSA' });
sig.init(KEYUTIL.getKey(key));
sig.updateHex(dataBuffer.toString('hex'));
const asn1hexSig = sig.sign();
const concatSig = ECDSA.asn1SigToConcatSig(asn1hexSig);
return new Buffer(concatSig, 'hex');
Seems to work. I also have code that uses SubtleCrypto to achieve the same thing:
importEcdsaKey(key, 'sign') // importKey JWK -> raw
.then((privateKey) => subtle.sign(
{ name: 'ECDSA', hash: {name: 'SHA-256'} },
privateKey,
dataBuffer
))
These both return 128-byte buffers; and they cross-verify (i.e. I can verify jsrsasign signatures with SubtleCrypto and vice versa). However, when I use the Sign class in the Node.js crypto module, I seem to get something quite different.
key = require('jwk-to-pem')(key, {'private': true});
const sign = require('crypto').createSign('sha256');
sign.update(dataBuffer);
return sign.sign(key);
Here I get a buffer of variable length, roughly 70 bytes; it does not cross-verify with jsrsa (which bails complaining about an invalid length for an r-s signature).
How can I get an r-s signature, as generated by jsrsasign and SubtleCrypto, using Node crypto?
The answer turns out to be that the Node crypto module generates ASN.1/DER signatures, while other APIs like jsrsasign and SubtleCrypto produce a “concatenated” signature. In both cases, the signature is a concatenation of (r, s). The difference is that ASN.1 does so with the minimum number of bytes, plus some payload length data; while the P1363 format uses two 32-bit hex encoded integers, zero-padding them if necessary.
The below solution assumes that the “canonical” format is the concatenated style used by SubtleCrypto.
const asn1 = require('asn1.js');
const BN = require('bn.js');
const crypto = require('crypto');
const EcdsaDerSig = asn1.define('ECPrivateKey', function() {
return this.seq().obj(
this.key('r').int(),
this.key('s').int()
);
});
function asn1SigSigToConcatSig(asn1SigBuffer) {
const rsSig = EcdsaDerSig.decode(asn1SigBuffer, 'der');
return Buffer.concat([
rsSig.r.toArrayLike(Buffer, 'be', 32),
rsSig.s.toArrayLike(Buffer, 'be', 32)
]);
}
function concatSigToAsn1SigSig(concatSigBuffer) {
const r = new BN(concatSigBuffer.slice(0, 32).toString('hex'), 16, 'be');
const s = new BN(concatSigBuffer.slice(32).toString('hex'), 16, 'be');
return EcdsaDerSig.encode({r, s}, 'der');
}
function ecdsaSign(hashBuffer, key) {
const sign = crypto.createSign('sha256');
sign.update(asBuffer(hashBuffer));
const asn1SigBuffer = sign.sign(key, 'buffer');
return asn1SigSigToConcatSig(asn1SigBuffer);
}
function ecdsaVerify(data, signature, key) {
const verify = crypto.createVerify('SHA256');
verify.update(data);
const asn1sig = concatSigToAsn1Sig(signature);
return verify.verify(key, new Buffer(asn1sig, 'hex'));
}
Figured it out thanks to
https://crypto.stackexchange.com/questions/1795/how-can-i-convert-a-der-ecdsa-signature-to-asn-1
ECDSA signatures between Node.js and WebCrypto appear to be incompatible?

In Node.js, how to read a file, append a string at a specified line or delete a string from a certain line?

I need to open an existing JavaScript file, check if this string exists:
var LocalStrategy = require('passport-local').Strategy;
If it doesn't, then append it at the top with the rest of require() lines.
In another case, I need to check if that string exists, and if it does, I would like to remove just that line.
I have looked at fs.readFile, fs.writeFile, fs.open but I don't think it is capable of doing what I need. Any suggestions?
This is a simplified script:
var fs = require('fs');
var search = "var LocalStrategy = require('passport-local').Strategy;";
function append (line) {
line = line || 0;
var body = fs.readFileSync('example.js').toString();
if (body.indexOf(search) < 0 ) {
body = body.split('\n');
body.splice(line + 1,0,search);
body = body.filter(function(str){ return str; }); // remove empty lines
var output = body.join('\n');
fs.writeFileSync('example.js', output);
}
}
function remove () {
var body = fs.readFileSync('example.js').toString();
var idx = body.indexOf(search);
if (idx >= 0 ) {
var output = body.substr(0, idx) + body.substr(idx + search.length);
fs.writeFileSync('example.js', output);
}
}

Resources