Make Nodejs encrypt and decrypt function up to date - node.js

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

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.

node-forge package error with RSA enc/dec

I'm using node-forge npm on my meteor.js web app. I'm trying to do RSA encryption on some plain text according to this example: https://github.com/digitalbazaar/forge#rsa
The problem arrives when I want to decrypt the ciphertext where I want to get back the plaintext where it says the encryption block is invalid.
Following the example, I have to encrypt the bytes from the string so all that is done, but I don't understand why it fails on decryption? Any guesses?
rsaEncrypt:function(pubPem,privPem,plainText){
console.log(plainText);
var str = plainText;
var bytes = [];
for (var i = 0; i < str.length; ++i) {
bytes.push(str.charCodeAt(i));
}
console.log("BAJTOVI:");
console.log(bytes);
var publicKey = pki.publicKeyFromPem(pubPem);
console.log(publicKey);
var encrypted = publicKey.encrypt(bytes);
console.log("Encryption: ");
console.log(encrypted);
var privateKey = pki.privateKeyFromPem(privPem);
var decrypted = privateKey.decrypt(encrypted);
console.log("Decryption: ");
console.log(decrypted);
function bin2String(decrypted) {
var result = "";
for (var i = 0; i < decrypted.length; i++) {
result += String.fromCharCode(parseInt(decrypted[i], 2));
}
return result;
}
console.log("OPET TEXT:");
console.log(result);
return decryted;
},
The problem i get from the server:
Exception while invoking method 'rsaEncrypt' Error: Encryption block is invalid.
I20151110-21:22:05.279(1)? at Object._decodePkcs1_v1_5 [as decode] (/Users/mrcina/Meteor Projects/cryptonic/.meteor/local/isopacks/npm-container/npm/node_modules/node-forge/js/rsa.js:1446:11)
I20151110-21:22:05.279(1)? at Object.key.decrypt (/Users/mrcina/Meteor Projects/cryptonic/.meteor/local/isopacks/npm-container/npm/node_modules/node-forge/js/rsa.js:1083:19)
I20151110-21:22:05.279(1)? at [object Object].Meteor.methods.rsaEncrypt (server/methods.js:49:32)
I20151110-21:22:05.279(1)? at maybeAuditArgumentChecks (livedata_server.js:1698:12)
I20151110-21:22:05.279(1)? at livedata_server.js:708:19
I20151110-21:22:05.279(1)? at [object Object]._.extend.withValue (packages/meteor/dynamics_nodejs.js:56:1)
I20151110-21:22:05.279(1)? at livedata_server.js:706:40
I20151110-21:22:05.279(1)? at [object Object]._.extend.withValue (packages/meteor/dynamics_nodejs.js:56:1)
I20151110-21:22:05.280(1)? at livedata_server.js:704:46
I20151110-21:22:05.280(1)? at tryCallTwo (/Users/mrcina/.meteor/packages/promise/.0.5.1.1wnrf8h++os+web.browser+web.cordova/npm/node_modules/meteor-promise/node_modules/promise/lib/core.js:45:5)
THis line: var decrypted = privateKey.decrypt(encrypted);
Forge doesn't use arrays of integers to represent bytes; it uses binary-encoded strings. Try simplifying your code to the following:
rsaEncrypt:function(pubPem,privPem,plainText){
console.log(plainText);
var publicKey = pki.publicKeyFromPem(pubPem);
console.log(publicKey);
var encrypted = publicKey.encrypt(forge.util.encodeUtf8(plainText));
console.log("Encryption: ");
console.log(encrypted);
var privateKey = pki.privateKeyFromPem(privPem);
var decrypted = forge.util.decodeUtf8(privateKey.decrypt(encrypted));
console.log("Decryption: ");
console.log(decrypted);
return decrypted;
}

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