Encrypt des-ede3-cbc nodejs - node.js

I am trying to encrypt a string with des-ede3-cbc algorithm
My base64 password is sq7HjrUOBfKmC576ILgskD5srU870gJ7, the message I want to encrypt is 06080232580 the result I should have in hexadecimal is a5334014a4f010c8779cef789886c123
First try
const iv = Buffer.alloc(8);
const cipher = crypto.createCipheriv('des-ede3-cbc', Buffer.from('sq7HjrUOBfKmC576ILgskD5srU870gJ7', 'base64'), iv);
let ciph = cipher.update('06080232580', 'utf8', 'hex');
ciph += cipher.final('hex');
console.log(ciph);
The result is a5334014a4f010c8300101ae242354de
An other test
let shortkey = Buffer.from('06080232580', 'utf8');
let key = Buffer.alloc(24);
key.fill('\0');
for (i = 0; i < shortkey.length; i++) {
key[i] = shortkey[i];
}
let IV = Buffer.alloc(8);
const cipher = crypto.createCipheriv('des-ede3-cbc', key, IV);
password = Buffer.from('sq7HjrUOBfKmC576ILgskD5srU870gJ7', 'base64');
let encryptedArr = [cipher.update(password)];
encryptedArr.push(cipher.final());
encrypted = Buffer.concat(encryptedArr);
console.log(encrypted.toString('hex'));
The result is 6f6b59b6c3ea45592bedbd86db4f31cc5da23d85e2ff773940aaa39e2efdc4ae
Y have my old code working in php
<?php
$message = "06080232580";
$key = base64_decode("sq7HjrUOBfKmC576ILgskD5srU870gJ7");
$l = ceil(strlen($message) / 8) * 8;
$message = $message.str_repeat("\0", $l - strlen($message));
$result = substr(openssl_encrypt($message, 'des-ede3-cbc', $key, OPENSSL_RAW_DATA, "\0\0\0\0\0\0\0\0"), 0, $l);
echo implode(unpack("H*", $result));
The result id a5334014a4f010c8779cef789886c123

Found the solution
let shortkey = Buffer.from('06080232580', 'utf8');
let key = Buffer.alloc(16);
key.fill('\0');
for (i = 0; i < shortkey.length; i++) {
key[i] = shortkey[i];
}
let IV = Buffer.alloc(8);
const password = Buffer.from('sq7HjrUOBfKmC576ILgskD5srU870gJ7', 'base64');
const cipher = crypto.createCipheriv('des-ede3-cbc', password, IV);
cipher.setAutoPadding(false)
let encryptedArr = [cipher.update(key)];
encryptedArr.push(cipher.final());
encrypted = Buffer.concat(encryptedArr);
console.log(encrypted.toString('hex'));

Related

Validate mining share in NodeJS before submit to pool (Stratum)

I am trying to validate share if it meets minimum difficulty.
I have all required data to create block hash and compare with difficulty.
My code is not generating valid block hash, but don't understand why.
My code with example data:
const crypto = require('crypto');
sha256 = function(buffer){
var hash1 = crypto.createHash('sha256');
hash1.update(buffer);
return hash1.digest();
};
sha256d = function(buffer){
return sha256(sha256(buffer));
};
reverseBuffer = function(buff){
var reversed = new Buffer.alloc(buff.length);
for (var i = buff.length - 1; i >= 0; i--)
reversed[buff.length - i - 1] = buff[i];
return reversed;
};
reverseHex = function(hex){
return reverseBuffer(Buffer.from(hex, 'hex')).toString('hex');
};
serializeCoinbase = function(coinbase1, coinbase2, extraNonce1, extraNonce2){
var coinbase = coinbase1+
extraNonce1+
extraNonce2+
coinbase2;
return Buffer.from(coinbase, 'hex');
};
MerkleRootWithCoinbase = function(merkleTree,coinbaseHash){
var hash = coinbaseHash;
merkleTree.forEach(a => {
hash = sha256d(Buffer.from(hash + a,'hex')).toString('hex')
});
return hash
}
convertPreviousblockhash = function(previousblockhash){
return previousblockhash.match(/.{1,8}/g).reverse().join('')
}
blockHeader = function(blockVersion, previousblockhash, merkleRoot, nTime, nBits, nonce){
previousblockhash = convertPreviousblockhash(previousblockhash)
var hash = reverseHex(blockVersion)+
reverseHex(previousblockhash)+
reverseHex(merkleRoot)+
reverseHex(nTime)+
reverseHex(nBits)+
reverseHex(nonce);
return Buffer.from(hash, 'hex');
};
// blockTemplate is received from pool (mining.notify)
let blockTemplate = {
ExtraNonce1: '929e4bb4',
ExtraNonce2_size: 4,
previousblockhash: '83ed60ce078736fe15528d3f5ea5cfdd0ed72b04000a31440000000000000000',
coinbase: [
'01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff5c0332410a192f5669614254432f4d696e6564206279206c6576616d75732f2cfabe6d6def4d71fab9c4856256f87621806274036feb16b79c411157a920716275e722951000000000000000108ad5ef13de0027ea',
'ffffffff04ce4c6229000000001976a914536ffa992491508dca0354e52f32a3a7a679a53a88ac00000000000000002b6a2952534b424c4f434b3acac6189d090598816a3e1092b966aad3c6aef15e3c826a334cea7f21002fd6540000000000000000266a24b9e11b6d65ba1a6db71ac060e04c3cb5bf049af5478970ded266f93b2f5b89f86348c9fc0000000000000000266a24aa21a9edf2716abb1dd5ac06ad1fed7f6bde943fc1657a0fd53a1c11823a4ffb5cc823e400000000'
],
merkleTree: [
'628a4d82f4950e0d55407f231057e8524a27e724143667cfd6c4bb3bc323d75f',
'e1ec3b078e79bd6da16899697e47a1eff05f27304baf7bf4fb3784145b452343',
'dfac6e968c29d40b35f34474b081b3fb9a054497c8ce8cebfca36471e9b5f912',
'35ea339bda0105cd0401e5f4dd89c511a41ea34117d839d6d3e32b575f4e4dc0',
'97bd6bfb590b9cb2a6f388f3a4039a926ed0487f82f6215860443a4bef28fe10',
'3126b182f4115fe6705c36a43737cd38eaf3e600add0de49bd6823c7f0fa6a11',
'793fa91f40722794f2234fd5ab7904a94432f8376b5cef86e7440a457b3482c4',
'd1370e331d8752b53e6b07d560a3d0b9f03569e2686e786739e3a96cc2ae7eb8',
'e99e29d9953dea3642621c08e31bd78ab9a3648b630af7dcff2dd90bdbca08b8',
'5655477db1423bef022382ccfe88d2c597f64bc69df6f4f520adca95a29f94aa',
'3c719be7fbeed1101542c6420fde3f4e5fd773284effacf8f9f21e4a05e5d416'
],
blockVersion: '20000000',
nBits: '170cf4e3',
nTime: '6036f006'
}
// extraNonce2,nTime and nonce is received from miner (mining.submit)
let extraNonce2 = "301a0000"
let nTime = "6036f00a"
let nonce = "e4abf319"
let coinbaseBuffer = serializeCoinbase(blockTemplate.coinbase[0], blockTemplate.coinbase[1], blockTemplate.ExtraNonce1, extraNonce2);
let coinbaseHash = sha256d(coinbaseBuffer);
console.log(coinbaseHash.toString('hex'))
// result: a97941791004f1ad8fe01d9e1a0116b932e65c37b7de2bd29ebd238c0705aa72
let merkleRoot = MerkleRootWithCoinbase(blockTemplate.merkleTree,coinbaseHash.toString('hex'));
console.log(merkleRoot.toString('hex'))
// result: 7c1a57f3f75d94e3f1014afca791101e80eebed18b3bca014f798e7399f3ceef
let headerBuffer = blockHeader(blockTemplate.blockVersion, blockTemplate.previousblockhash, merkleRoot, nTime, blockTemplate.nBits, nonce);
console.log(headerBuffer.toString('hex'))
// result: 00000020ce60ed83fe3687073f8d5215ddcfa55e042bd70e44310a000000000000000000efcef399738e794f01ca3b8bd1beee801e1091a7fc4a01f1e3945df7f3571a7c0af03660e3f40c1719f3abe4
let headerHash = sha256d(headerBuffer);
console.log(headerHash.toString('hex'))
// result: 87d83009bcca8068760bbdf5130a19b88e0f120c17cb97590397aed4b62ef4e4
let headerHashReversed = reverseBuffer(headerHash);
console.log(headerHashReversed.toString('hex'))
// result: e4f42eb6d4ae97035997cb170c120f8eb8190a13f5bd0b766880cabc0930d887
result hash is not valid, don't understand where I have invalid calculation.
I fixed problem and you can find working example below:
const crypto = require('crypto');
sha256 = function(buffer){
var hash1 = crypto.createHash('sha256');
hash1.update(buffer);
return hash1.digest();
};
sha256d = function(buffer){
return sha256(sha256(buffer));
};
reverseBuffer = function(buff){
var reversed = new Buffer.alloc(buff.length);
for (var i = buff.length - 1; i >= 0; i--)
reversed[buff.length - i - 1] = buff[i];
return reversed;
};
reverseHex = function(hex){
return reverseBuffer(Buffer.from(hex, 'hex')).toString('hex');
};
serializeCoinbase = function(coinbase1, coinbase2, extraNonce1, extraNonce2){
var coinbase = coinbase1+
extraNonce1+
extraNonce2+
coinbase2;
return Buffer.from(coinbase, 'hex');
};
MerkleRootWithCoinbase = function(merkleTree,coinbaseHash){
var hash = coinbaseHash;
merkleTree.forEach(a => {
hash = sha256d(Buffer.from(hash + a,'hex')).toString('hex')
});
return hash
}
convertPreviousblockhash = function(previousblockhash){
return previousblockhash.match(/.{1,8}/g).reverse().join('')
}
blockHeader = function(blockVersion, previousblockhash, merkleRoot, nTime, nBits, nonce){
previousblockhash = convertPreviousblockhash(previousblockhash)
var hash = reverseHex(blockVersion)+
reverseHex(previousblockhash)+
merkleRoot+
reverseHex(nTime)+
reverseHex(nBits)+
reverseHex(nonce);
return Buffer.from(hash, 'hex');
};
// blockTemplate is received from pool (mining.notify)
let blockTemplate = {
ExtraNonce1: '929e4bb4',
ExtraNonce2_size: 4,
previousblockhash: '83ed60ce078736fe15528d3f5ea5cfdd0ed72b04000a31440000000000000000',
coinbase: [
'01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff5c0332410a192f5669614254432f4d696e6564206279206c6576616d75732f2cfabe6d6def4d71fab9c4856256f87621806274036feb16b79c411157a920716275e722951000000000000000108ad5ef13de0027ea',
'ffffffff04ce4c6229000000001976a914536ffa992491508dca0354e52f32a3a7a679a53a88ac00000000000000002b6a2952534b424c4f434b3acac6189d090598816a3e1092b966aad3c6aef15e3c826a334cea7f21002fd6540000000000000000266a24b9e11b6d65ba1a6db71ac060e04c3cb5bf049af5478970ded266f93b2f5b89f86348c9fc0000000000000000266a24aa21a9edf2716abb1dd5ac06ad1fed7f6bde943fc1657a0fd53a1c11823a4ffb5cc823e400000000'
],
merkleTree: [
'628a4d82f4950e0d55407f231057e8524a27e724143667cfd6c4bb3bc323d75f',
'e1ec3b078e79bd6da16899697e47a1eff05f27304baf7bf4fb3784145b452343',
'dfac6e968c29d40b35f34474b081b3fb9a054497c8ce8cebfca36471e9b5f912',
'35ea339bda0105cd0401e5f4dd89c511a41ea34117d839d6d3e32b575f4e4dc0',
'97bd6bfb590b9cb2a6f388f3a4039a926ed0487f82f6215860443a4bef28fe10',
'3126b182f4115fe6705c36a43737cd38eaf3e600add0de49bd6823c7f0fa6a11',
'793fa91f40722794f2234fd5ab7904a94432f8376b5cef86e7440a457b3482c4',
'd1370e331d8752b53e6b07d560a3d0b9f03569e2686e786739e3a96cc2ae7eb8',
'e99e29d9953dea3642621c08e31bd78ab9a3648b630af7dcff2dd90bdbca08b8',
'5655477db1423bef022382ccfe88d2c597f64bc69df6f4f520adca95a29f94aa',
'3c719be7fbeed1101542c6420fde3f4e5fd773284effacf8f9f21e4a05e5d416'
],
blockVersion: '20000000',
nBits: '170cf4e3',
nTime: '6036f006'
}
// extraNonce2,nTime and nonce is received from miner (mining.submit)
let extraNonce2 = "301a0000"
let nTime = "6036f00a"
let nonce = "e4abf319"
let coinbaseBuffer = serializeCoinbase(blockTemplate.coinbase[0], blockTemplate.coinbase[1], blockTemplate.ExtraNonce1, extraNonce2);
let coinbaseHash = sha256d(coinbaseBuffer);
console.log(coinbaseHash.toString('hex'))
// result: a97941791004f1ad8fe01d9e1a0116b932e65c37b7de2bd29ebd238c0705aa72
let merkleRoot = MerkleRootWithCoinbase(blockTemplate.merkleTree,coinbaseHash.toString('hex'));
console.log(merkleRoot.toString('hex'))
// result: 7c1a57f3f75d94e3f1014afca791101e80eebed18b3bca014f798e7399f3ceef
let headerBuffer = blockHeader(blockTemplate.blockVersion, blockTemplate.previousblockhash, merkleRoot, nTime, blockTemplate.nBits, nonce);
console.log(headerBuffer.toString('hex'))
// result: 00000020ce60ed83fe3687073f8d5215ddcfa55e042bd70e44310a0000000000000000007c1a57f3f75d94e3f1014afca791101e80eebed18b3bca014f798e7399f3ceef0af03660e3f40c1719f3abe4
let headerHash = sha256d(headerBuffer);
console.log(headerHash.toString('hex'))
// result: 5edd9d1f993bb74a4f1b5fcd3ab48140df048af0c3bfa43c16c1000000000000
let headerHashReversed = reverseBuffer(headerHash);
console.log(headerHashReversed.toString('hex'))
// result: 000000000000c1163ca4bfc3f08a04df4081b43acd5f1b4f4ab73b991f9ddd5e
If the the miner is using version-rolling it means that miner is able to manipulate bits as specified in BIP320 - within mask 0x1fffe000.
Try including the version from the submit into block hash calculation.

Unable to decrypt a pdf file Using 'aes-256-cbc' algorithm in node js

I am trying to decrypt a PDF file using node js,PDF file encrypted by third party using C# .
I am having a hard time because I keep getting this error:
D:\IMP\DevOps Implementation\New folder (2)> node index1.js
internal/crypto/cipher.js:172
const ret = this[kHandle].final();
^
Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
at Decipheriv.final (internal/crypto/cipher.js:172:29)
at Object.AESCrypt.decrypt (D:\IMP\DevOps Implementation\New folder (2)\index1.js:12:18)
at D:\IMP\DevOps Implementation\New folder (2)\index1.js:57:24
at FSReqCallback.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:63:3) {
library: 'digital envelope routines',
function: 'EVP_DecryptFinal_ex',
reason: 'bad decrypt',
code: 'ERR_OSSL_EVP_BAD_DECRYPT'
}
we are using below code for encryption(C#)
private void FileEncrypt(string inputFile, string outputfile, string password)
{
byte[] salt = GenerateSalt();
byte[] passwords = Encoding.UTF8.GetBytes(password);
RijndaelManaged AES = new RijndaelManaged();
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwords, salt, 50000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CBC;
AES.Padding = PaddingMode.Zeros;
using (FileStream fsCrypt = new FileStream(inputFile + ".aes", FileMode.Create))
{
fsCrypt.Write(salt, 0, salt.Length);
using (CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateEncryptor(), CryptoStreamMode.Write))
{
using (FileStream fsIn = new FileStream(inputFile, FileMode.Open))
{
byte[] buffer = new byte[1048576];
int read;
while ((read = fsIn.Read(buffer, 0, buffer.Length)) > 0)
{
cs.Write(buffer, 0, read);
}
}
}
}
}
we are using below code for decryption(Node js)
AESCrypt.encrypt = function(cryptkey, iv, cleardata) {
var encipher = crypto.createCipheriv('aes-256-cbc', cryptkey, iv);
return Buffer.concat([
encipher.update(cleardata),
encipher.final()
]);
}
function decrypted(){
var enc;
fs.readFile('./resource/test.pdf', function (err,data) {
if (err) {
return console.log(err);
}
var bufferenc = new Buffer.from(data);
var dec = AESCrypt.decrypt(cryptkey,iv, bufferenc);
console.log(dec);
// var buffer = new Buffer.from(dec);
fs.writeFileSync('./resource/decrypted.pdf',dec);
});
}
Unable to decrypt a pdf file Using 'aes-256-cbc' algorithm in node js
You can try this code to decrypt the pdf data, it's working for me with the C# code:
const fs = require('fs');
const crypto = require("crypto");
function FileDecrypt(inputFile, outputfile, password)
{
// Read the entire file into the buffer.
let buffer = fs.readFileSync(inputFile);
// Read the first eight bytes as a salt.
let salt = buffer.slice(0,8);
let cipherText = buffer.slice(8);
// use key derivation function to get key and iv.
let derivedBytes = crypto.pbkdf2Sync(password, salt, 50000, 48, "sha1");
let key = derivedBytes.slice(0, 32);
let iv = derivedBytes.slice(32);
let cipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
// Switch off auto padding in this context
cipher.setAutoPadding(false);
let decryptedData = Buffer.concat([cipher.update(cipherText), cipher.final()]);
fs.writeFileSync(outputfile, decryptedData);
}
FileDecrypt("encrypted.pdf", "node-decrypted.pdf", "password");

Invalid IV length with AES-192

I'm updating my old function to encrypt password since createCipher is deprecated.
Here are my old functions:
encrypt(payload) {
let AES192 = crypto.createCipher('aes192', Buffer.from(config.secret))
let crypted = AES192.update(payload, 'utf8', 'hex')
crypted += AES192.final('hex')
return crypted
},
decrypt(payload) {
let AES192 = crypto.createDecipher('aes192', Buffer.from(config.secret))
let decrypted = AES192.update(payload, 'hex', 'utf8')
decrypted += AES192.final('utf8')
return decrypted
}
Here is what I tried to do:
encrypt(payload) {
const iv = crypto.randomBytes(96)
const cipher = crypto.createCipheriv('aes192', Buffer.from(config.secret, 'hex'), iv)
const encrypted = cipher.update(payload)
encrypted = Buffer.concat([encrypted, cipher.final()])
return iv.toString('hex') + ':' + encrypted.toString('hex')
},
decrypt(payload) {
let textParts = payload.split(':')
let iv = Buffer.from(textParts.shift(), 'hex')
let encryptedText = Buffer.from(textParts.join(':'), 'hex')
let decipher = crypto.createDecipheriv('aes192', Buffer.from(config.secret, 'hex'), iv)
let decrypted = decipher.update(encryptedText)
decrypted = Buffer.concat([decrypted, decipher.final()])
return decrypted.toString()
}
But I got this error when I try to do it:
Error: Invalid IV length
at Cipheriv.createCipherBase (internal/crypto/cipher.js:103:19)
at Cipheriv.createCipherWithIV (internal/crypto/cipher.js:121:20)
at new Cipheriv (internal/crypto/cipher.js:225:22)
at Object.createCipheriv (crypto.js:119:10)
For this line I tried multiple values like 12, 16, 32, 124 etc. But none are working
const iv = crypto.randomBytes(96)
AES-192 (and for that matter AES-128 and AES-256) all use a 128 bit block length, so the IV should also be 128 bits, or 16 bytes. It's weird that you tried 16 as the length; at any rate this code is working for me:
function encrypt(payload) {
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv('aes192', Buffer.from(config.secret, 'hex'), iv)
let encrypted = cipher.update(payload)
encrypted = Buffer.concat([encrypted, cipher.final()])
return iv.toString('hex') + ':' + encrypted.toString('hex')
}
I'm assuming config looks like this:
{ secret: 'dc8a453e728fc19398178797e2c39067e1965f2061220257' }

Rfc2898DeriveBytes to crypto.pbkdf2

I am not getting the same results when switching from C# to JS:
Converting from this:
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(
passPhrase,
Encoding.UTF8.GetBytes(saltValue)
);
MemoryStream ms = new MemoryStream();
Aes aes = new AesManaged();
aes.Key = pdb.GetBytes(aes.KeySize / 8);
aes.IV = pdb.GetBytes(aes.BlockSize / 8);
CryptoStream cs = new CryptoStream(ms,
aes.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(input, 0, input.Length);
cs.Close();
ms.Close();
aes.Clear();
return ms.ToArray();
To this:
crypto.pbkdf2(Buffer.from(pass), Buffer.from(salt, 'hex'), 1000, 256 / 8, null, function (err, key) {
console.log("Key:" + key);
crypto.pbkdf2(Buffer.from(pass), Buffer.from(salt, 'hex'), 1000, 128 / 8, null, function (err, key) {
console.log("VID:" + key);
}
}
But it's not working for some reason
I tried Buffer.from(pass, 'utf8') and so one but I am never getting the same result.
I know I have something wrong but I have no idea how pbkdf2 works
For anyone in the same problem as I am this is the equivalent code
var pass = 'password';
var salt = 'salt';
var keyLen = keylen; // aes.KeySize / 8 where KeySize is 256
var IVLen = ivlen; // aes.BlockSize / 8 where BlockSize is 128
var nodeCrypto = crypto.pbkdf2Sync(pass, salt, 1000, keyLen + IVLen, 'sha1');
// Output same values as C# Bytes
var aesKey = [], aesIV = [];
for (var i = 0; i < nodeCrypto.length; i++) {
if (i < keyLen)
aesKey[i] = nodeCrypto[i];
else
aesIV[i - keyLen] = nodeCrypto[i];
}
console.log(aesKey);
console.log(aesIV);
// How to use it to decrypt
var r = fs.createReadStream(path);
var decrypt = crypto.createDecipheriv('aes-256-cbc', nodeCrypto.slice(0, keyLen), nodeCrypto.slice(keyLen, keyLen + IVLen));
var w = fs.createWriteStream(output);
r.pipe(decrypt).pipe(w);

Decrypting AES256 with node.js returns wrong final block length

Using this Gist I was able to successfully decrypt AES256 in Node.js 0.8.7. Then when I upgraded to Node.js 0.10.24, I now see this error:
TypeError: error:0606506D:digital envelope
routines:EVP_DecryptFinal_ex:wrong final block length
at Decipheriv.Cipher.final (crypto.js:292:27)
Here is the decrypt code from the Gist (shown here for convenience):
var crypto = require('crypto');
var AESCrypt = {};
AESCrypt.decrypt = function(cryptkey, iv, encryptdata) {
encryptdata = new Buffer(encryptdata, 'base64').toString('binary');
var decipher = crypto.createDecipheriv('aes-256-cbc', cryptkey, iv),
decoded = decipher.update(encryptdata);
decoded += decipher.final();
return decoded;
}
AESCrypt.encrypt = function(cryptkey, iv, cleardata) {
var encipher = crypto.createCipheriv('aes-256-cbc', cryptkey, iv),
encryptdata = encipher.update(cleardata);
encryptdata += encipher.final();
encode_encryptdata = new Buffer(encryptdata, 'binary').toString('base64');
return encode_encryptdata;
}
var cryptkey = crypto.createHash('sha256').update('Nixnogen').digest(),
iv = 'a2xhcgAAAAAAAAAA',
buf = "Here is some data for the encrypt", // 32 chars
enc = AESCrypt.encrypt(cryptkey, iv, buf);
var dec = AESCrypt.decrypt(cryptkey, iv, enc);
console.warn("encrypt length: ", enc.length);
console.warn("encrypt in Base64:", enc);
console.warn("decrypt all: " + dec);
Ok, so there was a change to Crypto in the switch from 0.8 to 0.10 Crypto methods return Buffer objects by default, rather than binary-encoded strings
This means the above code needs to specify encodings.
These four lines:
decoded = decipher.update(encryptdata);
decoded += decipher.final();
encryptdata = encipher.update(cleardata);
encryptdata += encipher.final();
Are changed to:
decoded = decipher.update(encryptdata, 'binary', 'utf8');
decoded += decipher.final('utf8');
encryptdata = encipher.update(cleardata, 'utf8', 'binary');
encryptdata += encipher.final('binary');
This worked for me, but I am open to other suggestions.
As your answer states, those functions work with Buffers now unless you specify an encoding. That said, you'd be better off avoiding binary encoded strings entirely and treat everything as Buffers until you strictly need a string for something. This way you can also use your encryption helpers to process non-text content.
var crypto = require('crypto');
var AESCrypt = {};
AESCrypt.decrypt = function(cryptkey, iv, encryptdata) {
var decipher = crypto.createDecipheriv('aes-256-cbc', cryptkey, iv);
return Buffer.concat([
decipher.update(encryptdata),
decipher.final()
]);
}
AESCrypt.encrypt = function(cryptkey, iv, cleardata) {
var encipher = crypto.createCipheriv('aes-256-cbc', cryptkey, iv);
return Buffer.concat([
encipher.update(cleardata),
encipher.final()
]);
}
var cryptkey = crypto.createHash('sha256').update('Nixnogen').digest(),
iv = new Buffer('a2xhcgAAAAAAAAAA'),
buf = new Buffer("Here is some data for the encrypt"), // 32 chars
enc = AESCrypt.encrypt(cryptkey, iv, buf);
var dec = AESCrypt.decrypt(cryptkey, iv, enc);
console.warn("encrypt length: ", enc.length);
console.warn("encrypt in Base64:", enc.toString('base64'));
console.warn("decrypt all: " + dec.toString('utf8'));
My issue was that the string I was passing to my decrypt function was empty. I built in a check for empty strings and I did not receive the message again.
decrypt: function(text){
if(text.length == 0){
return text;
}
return this.decipher.update(text, 'hex', 'utf8') + this.decipher.final('utf8');
}

Resources