NodeJS aes decrypt not working - javascript

I using online tools for encrpyt using AES. I'm using my module to decrypt. But I get not the same results. Why?
I used one of those tool for encrypt:
https://www.browserling.com/tools/aes-encrypt
https://www.tools4noobs.com/online_tools/encrypt/
This is the data I provided:
This is the text to encrpyt: Hello World
This is the password:12345
This is the result of the tool: U2FsdGVkX19HLG+YDMe3kYl+MYwEMlnC5mK78s3rZZg=
Now I try to decrypt it using node, and it is not giving me same results. But everything works welll
var crypto = require('crypto'),
algorithm = 'aes-128-ctr',
password = '12345';
module.exports.decrypt=function(text){
var decipher = crypto.createDecipher(algorithm,password)
var dec = decipher.update(text,'base64','utf8')
dec += decipher.final('utf8');
return dec;
}
text=module.exports.decrypt('U2FsdGVkX1+OOp0KE3lv6qcKQeS/JDFPF8YhgdU131o=')
text
I tried to change to AES-192, and got the same issue.
Update: (Based on zaph response)
This is the new data I entered here: https://www.tools4noobs.com/online_tools/encrypt/
key: 0123456789abcdef (16 bytes) Rijndael-128. mode: CBC. encode:hex.
This is the result: 8b25e846b6a2d52ad87f38f8134906c3
I cannot decrypt it. Here is my code:
var crypto = require('crypto'),
algorithm = 'aes-128-cbc',
password = '0123456789abcdef';
module.exports.decrypt=function(text){
var decipher = crypto.createDecipher(algorithm,password)
var dec = decipher.update(text,'hex','utf8')
dec += decipher.final('utf8');
return dec;
}
if(!module.parent){
var text=module.exports.decrypt('8b25e846b6a2d52ad87f38f8134906c3')
console.log(text)
}

Use an encryption key that is an exact length in order to avoid non-standard padding (there is not standard on handling keys of incorrect lengths). AES supports 128 192 and 256 bit length passwords (16, 24 and 32 bytes). Obviously 12345 does not meet the supported password lengths.
It is generally best not to use CTR mode, is is very easy to get it wrong. The issue is that the same key and counter must never be reused. Generally CBC mode is used with a random IV and PKCS#7 padding is used to accommodate input that is not a multiple of the block size.
The output U2FsdGVkX19HLG+YDMe3kYl+MYwEMlnC5mK78s3rZZg= is Base encoded 32 bytes, twice the block size, so there is something else than the encrypted data in the output.
Entering the password and text into https://www.tools4noobs.com/online_tools/encrypt/ in Rijndael-128 (which is AES) in CTR mode produces 53TI1is8kfYkztQ=, not the resulty in the question. Note that this tool used mcrypt that only supports non-standard padding.

This is my final code for encrypt and decrypt in AES-256 in NodeJS. Using IV, and key (password).
var crypto = require('crypto')
var algorithm = 'aes-128-cbc'
var key = 'AABBBBBBBBBBBBBBBBBBBBBBBBBBBBBB'
var iv = 'AABBBBBBBBBBBBBBBBBBBBBBBBBBBBBB'
key=new Buffer(key,'hex')
iv=new Buffer(iv,'hex')
module.exports.encrypt=function(text){
var cipher = crypto.createCipheriv(algorithm,key,iv)
text=new Buffer(text)
var crypted = cipher.update(text,'utf-8','base64')
crypted += cipher.final('base64');
return crypted;
}
module.exports.decrypt=function(text){
var decipher = crypto.createDecipheriv(algorithm,key,iv)
dec = decipher.update(text,'base64','utf-8');
dec += decipher.final();
return dec;
}
if(!module.parent){
var enc=module.exports.encrypt('Exaxmple of encoding')
console.log(enc)
var dec=module.exports.decrypt(enc)
console.log(dec)
}

Related

Encryption on crypto-js and decryption on node crypto using CTR mode issue

I am trying to encrypt data using crypto-js javascript library and trying to decrypt the same encrypted text on nodejs side using node crypto library. I am using AES 256 encryption algo with CTR mode with no padding. I am able to encrypt properly but the description on nodejs crypto module is not producing same plain text.
If I try to encrypt or decrypt using the same crypto-js and node crypto library, it works fine but encryption on crypto-js and description on crypto is not working as expected. I have tried to confirm if I encrypt and decrypt in the same library than it works or not and it works perfectly fine. Can someone please check what mistake I am making here?
Please find below code samples.
Encryption:
var key = CryptoJS.enc.Hex.parse('F29BA22B55F9B229CC9C250E11FD4384');
var iv = CryptoJS.enc.Hex.parse('C160C947CD9FC273');
function encrypt(plainText) {
return CryptoJS.AES.encrypt(
plainText,
key,
{
iv: iv,
padding: CryptoJS.pad.NoPadding,
mode: CryptoJS.mode.CTR
}
);
}
Descryption using NodeJS crypo module:
var algorithm = 'aes-256-ctr';
var key = 'F29BA22B55F9B229CC9C250E11FD4384';
var iv = 'C160C947CD9FC273';
var outputEncoding = 'hex';
var inputEncoding = 'hex';
const decipher = crypto.createDecipheriv(algorithm, key, iv);
let decrypted = decipher.update('8df5e11f521cf492437a95', inputEncoding, 'utf8');
decrypted += decipher.final('utf8');
console.log(decrypted);
As I have mentioned above, I have JavaScript crypo-js and NodeJS crypo module sessions working fine if I encrypt and decrypt using the same lib but doesn't work otherwise. Please check the working code as below.
JavaScript: http://jsfiddle.net/usr_r/2qwt8jsh/2/
NodeJS: https://repl.it/repls/AchingRegalPhp
I think your CryptoJS code isn't using AES-256, as the key and IV are too short and hence it's implicitly using AES-128. if you get the blockSize from the CryptoJS.AES object it says 4 for me. that said I don't know CryptoJS very well and that might not mean "4 words".
To bypass this implementation uncertainty, it's good to have a "gold standard" to replicate. NIST provides lots of test vectors, some of which apply to your CTR mode AES-256. First I pull out a set of (hex encoded) test vectors from that document:
const key = (
'603deb1015ca71be2b73aef0857d7781' +
'1f352c073b6108d72d9810a30914dff4'
)
const ctr = 'f0f1f2f3f4f5f6f7f8f9fafbfcfdff00'
const output = '5a6e699d536119065433863c8f657b94'
const cipher = 'f443e3ca4d62b59aca84e990cacaf5c5'
const plain = 'ae2d8a571e03ac9c9eb76fac45af8e51'
next I try and recover these from Node's crypto module:
const crypto = require('crypto')
function node_crypto(text) {
const dec = crypto.createDecipheriv(
'aes-256-ctr',
Buffer.from(key, 'hex'),
Buffer.from(ctr, 'hex')
);
const out = dec.update(Buffer.from(text, 'hex'))
return out.toString('hex')
}
now I can write a simple test harness for testing the above and use it with that function:
const zero = '00'.repeat(16);
function test_crypto(fn) {
return {
'zero => output': fn(zero) == output,
'cipher => plain': fn(cipher) == plain,
'plain => cipher': fn(plain) == cipher,
}
}
console.log(test_crypto(node_crypto))
which gives me true for all tests.
finally, the equivalent code for CryptoJS is:
const CryptoJS = require("crypto-js");
function cryptojs(text) {
const out = CryptoJS.AES.encrypt(
CryptoJS.enc.Latin1.parse(Buffer.from(text, 'hex').toString('binary')),
CryptoJS.enc.Hex.parse(key),
{
iv: CryptoJS.enc.Hex.parse(ctr),
mode: CryptoJS.mode.CTR,
padding: CryptoJS.pad.NoPadding,
}
);
return out.ciphertext.toString();
}
console.log(test_crypto(cryptojs))
which also works for me.
It's important to note that CryptoJS just silently accepts arbitrarily sized keys, with the docs saying:
CryptoJS supports AES-128, AES-192, and AES-256. It will pick the variant by the size of the key you pass in. If you use a passphrase, then it will generate a 256-bit key.
In contrast to the NodeJS-code (Crypto), the JavaScript-code (CryptoJS) interprets keys and IV as hexadecimal strings. Therefore, in the JavaScript-Code AES-128 is used and in the NodeJS-Code AES-256. To solve the problem, both codes must use the same encryption.
Option 1: Change the JavaScript-code to AES-256: Replace in the JavaScript-code
var key = CryptoJS.enc.Hex.parse('F18AB33A57F9B229CC9C250D00FC3273');
var iv = CryptoJS.enc.Hex.parse('D959B836CD9FB162');
by
var key = CryptoJS.enc.Utf8.parse('F18AB33A57F9B229CC9C250D00FC3273');
var iv = CryptoJS.enc.Utf8.parse('D959B836CD9FB162');
Option 2: Change the NodeJS-code to AES-128: Replace in the NodeJS-code
var algorithm = 'aes-256-ctr';
var key = 'F18AB33A57F9B229CC9C250D00FC3273';
var iv = 'D959B836CD9FB162';
by
var algorithm = 'aes-128-ctr';
var key = Buffer.from('F18AB33A57F9B229CC9C250D00FC3273', 'hex');
var iv = Buffer.from('D959B836CD9FB1620000000000000000', 'hex');
With one of each of the two changes, the codes of both links produce the same result.
If AES-256 should be used and key and IV should be specified as hexadecimal strings, a correspondingly large key and IV must be used, e.g. on the JavaScript-side:
var key = CryptoJS.enc.Hex.parse('F18AB33A57F9B229CC9C250D00FC3273F18AB33A57F9B229CC9C250D00FC3273');
var iv = CryptoJS.enc.Hex.parse('D959B836CD9FB16200000000000000');
and on the NodeJS-side:
var algorithm = 'aes-256-ctr';
var key = Buffer.from('F18AB33A57F9B229CC9C250D00FC3273F18AB33A57F9B229CC9C250D00FC3273', 'hex');
var iv = Buffer.from('D959B836CD9FB1620000000000000000', 'hex');

Node.js/javascript encrypt AES-128 like mcrypt_ecb in PHP

I have a PHP code that encrypt in AES-128 an ip address:
$ip = "MY_IP";
$secret = "MY_KEY";
$ip = #mcrypt_ecb(MCRYPT_RIJNDAEL_128, $secret, $ip, MCRYPT_ENCRYPT);
$encrypted = bin2hex($ip); // encrypted: 2854edb405cb7230ba1f4b87acddba8a
What I need to do is to have the same piece of code but using javascript/node.js. I've searched in the crypto node.js native module but I wasn't able to reproduce the same result:
var crypto = require('crypto');
var ip = "MY_IP";
var secret = "MY_KEY";
var cipher = crypto.createCipher("AES-128-ECB", secret);
var encrypted = cipher.update(ip, 'utf8', 'hex');
encrypted += cipher.final('hex'); // encrypted: e84c06888696edda0139e98fc2c0a8cc
Does someone have an idea ?
I've posted too quickly, found the solution:
$> npm install mcrypt
And then the code:
var MCrypt = require('mcrypt').MCrypt;
var ip = "MY_IP";
var secret = "MY_KEY"
var desEcb = new MCrypt('rijndael-128', 'ecb');
desEcb.open(secret);
var cipherText = desEcb.encrypt(ip); // cipherText: 2854edb405cb7230ba1f4b87acddba8a
MCrypt github for more encryption tool: https://github.com/tugrul/node-mcrypt
The problem here is that there are some things that PHP's mcrypt extension (and node's createCipher()) does behind the scenes that you're probably not aware of.
First off, createCipher() accepts a 'password' that is hashed with MD5 to derive the actual key. So instead what you should be using is createCipheriv(), which allows you to pass the key (and IV) directly, like PHP's mcrypt accepts. In ECB mode, IVs are ignored, so you can just pass in an empty string for the IV parameter.
Secondly, PHP's mcrypt will magically pad both your input and your key with null bytes if they are less than the cipher's block size and key size, respectively.
So for AES-128-ECB, we need to make sure the input and key lengths are a multiple of 16 bytes. With all of this knowledge we then find that appropriate code for the built-in crypto module might look something like:
var crypto = require('crypto');
function makePadded(str) {
var buf;
var len = str.length;
if (str.length % 16)
len = str.length + (16 - str.length % 16);
buf = new Buffer(len);
buf.fill(0);
buf.write(str, 0, str.length);
return buf;
}
var ip = makePadded('MY_IP');
var secret = makePadded('MY_KEY');
var cipher = crypto.createCipheriv("AES-128-ECB", secret, '');
var encrypted = cipher.update(ip, 'binary', 'hex');
encrypted += cipher.final('hex');
// Slice off at 16 bytes to match the input length
encrypted = encrypted.slice(0, 32);
console.log(encrypted);
One last thing that might be worth mentioning is that MCRYPT_RIJNDAEL_128 in PHP can be used to do 128, 192, or 256 bit encryption. So in PHP if 0 < keylen <= 16 then 128-bit encryption will be used, 192-bit encryption will be used if 16 < keylen <= 24 and 256-bit encryption will be used if 24 < keylen <= 32. However in node, you will need to adjust the cipher name appropriately, as node does not do the kind of "automatic adjustment" that PHP does.
in nodejs - password must be a 'binary' encoded string or a buffer. in PHP, the deprecated #mcrypt_ecb expects a key to be a string

Decoding Rijndael with node.js

I have to decode a rijndael 128 string
the string can be successfully using this online tool http://www.tools4noobs.com/online_tools/decrypt/ with theses parameters :
Algorythm rijndael 128
Mode : CBC
Decode the output using base64
I have to decode this using node.js and crypto module
Here is my code
function Token(TokenBase64 )
{
var crypto = require('crypto');
this.TokenToCheck = new Buffer(TokenBase64,'base64').toString();
this.GameKey = 'xxxxxxxxxxxxxxxxx';
var cryptKey = crypto.createHash('sha256').update(this.GameKey).digest()
this.decipher = crypto.createDecipheriv('aes-128-cbc', cryptKey, '12345678901234561234567890123456');
var dec = this.decipher.update( this.TokenToCheck);
dec += this.decipher.final();
return dec;
}
module.exports = Token;
The error output by this code when called is :
Error: DecipherInitIv error at new Decipheriv (crypto.js:360:17) at Object.Decipheriv (crypto.js:357:12) at new Token
The size of your IV is 32 characters (which will probably be used as 32 bytes). AES always uses a 128 bit block size and the IV for CBC is always the size of a single block. So you've got 16 characters too many.

crypto-js cant decrypt what it encrypted

I need to encrypt a sting with javascript using AES CBC no pad, pass the IV and encrypted data as HEX over HTTP, then decrypt with javascript on the server side.
The decryption function works, in that I can correctly decrypt data ecrypted using hurlant AS3 libraries correctly. However, the below encryption is not working - the result cannot be decrypted using the decrypt function, nor can it be decrypted using the hurant demo at: http://crypto.hurlant.com/demo/
Instead of the actual data, I am using "1234" as the message in this example.
I have searched and found no documentation for any of this library or its functions, beyond the quickstart guide which only has trivial cases, so everything is by trial and error. I have tried hundreds of variations of the below.
Example generated IV as Hex: "15ae89d17f632d21f0cda04734d38694"
Example generated encrypte data as HEX: "44ddf295"
Example message: "15ae89d17f632d21f0cda04734d3869444ddf295"
Can anyone see what is wrong in my encrypt() function?
// this function doesnt work - the resultant message (which is
// IV+Ecypted text all as HEX cannot be decrypted.
function encrypt() {
var key = CryptoJS.enc.Hex.parse('48656c6c6f2c20576f726c6421888888');
var IVLEN = 16; // Im guessing this is 16 bytes.
var iv= CryptoJS.lib.WordArray.random(IVLEN);
var encrypted;
var message;
encrypted = CryptoJS.AES.encrypt("1234", key, { iv: iv, padding: CryptoJS.pad.NoPadding, mode: CryptoJS.mode.CBC });
message = CryptoJS.enc.Hex.stringify(iv) + CryptoJS.enc.Hex.stringify(encrypted.ciphertext);
var test = decrypt(message); // throws a malformed UTF-8 exception
alert (test); // should alert "1234"
return message;
}
// this function works perfectly with data generated using HURLANT crypto libs.
function decrypt(data) {
var key = CryptoJS.enc.Hex.parse('48656c6c6f2c20576f726c6421888888');
var ivHexStr, iv;
var encMessageHexStr;
var IVLEN = 32; // This is 16 bytes, as one byte is 2 Hex chars.
var encrypted = {};
var decrypted;
var result;
ivHexStr = data.substring(0,IVLEN);
encMessageHexStr = data.substring(IVLEN);
iv = CryptoJS.enc.Hex.parse(ivHexStr);
encrypted.key = key;
encrypted.iv = iv;
encrypted.ciphertext = CryptoJS.enc.Hex.parse(encMessageHexStr);
decrypted = CryptoJS.AES.decrypt(encrypted, key, { iv: iv, padding: CryptoJS.pad.NoPadding, mode: CryptoJS.mode.CBC });
result = CryptoJS.enc.Utf8.stringify(decrypted);
return(result);
}; //decrypt()
With CBC mode padding is required. Neither CFB or OFB need padding.
CryptoJS supports the following modes:
CBC (the default)
CFB
CTR
OFB
ECB
And CryptoJS supports the following padding schemes:
Pkcs7 (the default)
Iso97971
AnsiX923
Iso10126
ZeroPadding
NoPadding

Node.js Crypto input/output types

I am trying to figure out the Node.js Crypto library and how to use it properly for my situation.
My Goal is:
key in hex string 3132333435363738313233343536373831323334353637383132333435363738
text in hex string 46303030303030303030303030303030
ciphered text in hex string 70ab7387a6a94098510bf0a6d972aabe
I am testing this through a c implementation of AES 256 and through a website at http://www.hanewin.net/encrypt/aes/aes-test.htm
This is what I have to far, it's not working the way I would expect it to work. My best guess is that the input and output types are incorrect for the cipher function. The only one that works is utf8 if I use hex it fails with a v8 error. Any ideas on what I should convert or change to get it to work.
var keytext = "3132333435363738313233343536373831323334353637383132333435363738";
var key = new Buffer(keytext, 'hex');
var crypto = require("crypto")
var cipher = crypto.createCipher('aes-256-cbc',key,'hex');
var decipher = crypto.createDecipher('aes-256-cbc',key,'hex');
var text = "46303030303030303030303030303030";
var buff = new Buffer(text, 'hex');
console.log(buff)
var crypted = cipher.update(buff,'hex','hex')
The output in crypted in this example is 8cfdcda0a4ea07795945541e4d8c7e35 which is not what I would expect.
Your code is using aes-256-cbc when the website you are deriving test vectors from is using ecb mode. Also, you are calling createCipher, but with ECB you should use createCipheriv with no IV (see nodeJS: can't get crypto module to give me the right AES cipher outcome),
Here is some code that demonstrates this:
var crypto = require("crypto");
var testVector = { plaintext : "46303030303030303030303030303030",
iv : "",
key : "3132333435363738313233343536373831323334353637383132333435363738",
ciphertext : "70ab7387a6a94098510bf0a6d972aabe"};
var key = new Buffer(testVector.key, "hex");
var text = new Buffer(testVector.plaintext, "hex");
var cipher = crypto.createCipheriv("aes-256-ecb", key, testVector.iv);
var crypted = cipher.update(text,'hex','hex');
crypted += cipher.final("hex");
console.log("> " + crypted);
console.log("? " + testVector.ciphertext);
The output of running that code is not exactly what I expect, but the first block of the encrypted output matches your expectation. Probably another parameter that needs to be tweaked.:
$ node test-aes-ecb.js
> 70ab7387a6a94098510bf0a6d972aabeeebbdaed7324ec4bc70d1c0343337233
? 70ab7387a6a94098510bf0a6d972aabe

Categories

Resources