get hash from strings, like hashids - node.js

Using the package hashids, I can obtain hashes (with encode and decode) from numbers.
var Hashids = require("hashids"),
hashids = new Hashids("this is my salt", 8);
var id = hashids.encode(1);
Is there a similar package to obtain hashes from strings?
(with encode and decode)

var Hashids = require("hashids");
var hashids = new Hashids("this is my salt");
var hex = Buffer.from('Hello World', 'utf8').toString('hex');
console.log (hex); // '48656c6c6f20576f726c64'
var encoded = hashids.encodeHex(hex);
console.log (encoded); // 'rZ4pPgYxegCarB3eXbg'
var decodedHex = hashids.decodeHex('rZ4pPgYxegCarB3eXbg');
console.log (decodedHex); // '48656c6c6f20576f726c64'
var string = Buffer.from('48656c6c6f20576f726c64', 'hex').toString('utf8');
console.log (string); // 'Hello World'

Getting hex without Node's Buffer.from ( to use with hashids.decodeHex)
const toHex = (str: string): string => str.split("")
.reduce((hex, c) => hex += c.charCodeAt(0).toString(16).padStart(2, "0"), "")
const toUTF8 = (num: string): string =>
num.match(/.{1,2}/g)
.reduce((acc, char) => acc + String.fromCharCode(parseInt(char, 16)),"");

Related

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.

base64 encode, nodejs c++ python's result is diffrent

nodejs:
var test = 'VdEU+Q2J5qfwsn9xshAcEImDSnxTR8RkRLlLmyNaeos=';
var result = new Buffer(test, 'base64').toString()
//var buf = Buffer.from(test, 'base64');
//var result = new Buffer(test, 'base64').toString("utf8");
var fs = require('fs');
fs.writeFile("test.txt",result,function(e){//会先清空原先的内容
if(e) throw e;
})
python:
import base64
result = base64.b64decode('VdEU+Q2J5qfwsn9xshAcEImDSnxTR8RkRLlLmyNaeos=')
file_object = open('thefile.txt', 'w')
file_object.write(result)
file_object.close( )
c++: (I use libcef's base library's base64):
const std::string kText = "VdEU+Q2J5qfwsn9xshAcEImDSnxTR8RkRLlLmyNaeos=";
std::string encoded;
base::Base64Decode(kText, &encoded);
FILE *pFile = fopen("1.txt", "wb+");
fwrite(encoded.c_str(), encoded.length(), 1, pFile);
fclose(pFile);
the result is python c++ is the same, but nodejs is different
You simply need to not call toString():
var result = new Buffer(test, 'base64');
Then the Node code does the same as the others.

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.

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