Encrypt string with Blowfish in NodeJS - javascript

I need to encrypt a string but I almost get the output I desire, I read online that it has something to do with padding and iv_vector at the end to complete for the remaining 8 bytes to be same length as txtToEncrypt.
I'm using this library https://github.com/agorlov/javascript-blowfish
// function in Java that I need
// javax.crypto.Cipher.getInstance("Blowfish/CBC/NoPadding").doFinal("spamshog")
var iv_vector = "2278dc9wf_178703";
var txtToEncrypt = "spamshog";
var bf = new Blowfish("spamshog", "cbc");
var encrypted = bf.encrypt(txtToEncrypt, iv_vector);
console.log(bf.base64Encode(encrypted));
Actual output: /z9/n0FzBJQ=
What I need: /z9/n0FzBJRGS6nPXso5TQ==
If anyone has any clue please let me know. I searched all over Google all day.

Finally, here is how to encrypt a string in NodeJS with Blowfish
// Module crypto already included in NodeJS
var crypto = require('crypto');
var iv = "spamshog";
var key = "spamshog";
var text = "2278dc9wf_178703";
var decipher = crypto.createCipheriv('bf-cbc', key, iv);
decipher.setAutoPadding(false);
var encrypted = decipher.update(text, 'utf-8', "base64");
encrypted += decipher.final('base64');
console.log(encrypted);
Returns: /z9/n0FzBJRGS6nPXso5TQ==

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');

TripleDES encryption - c# and javascript differences

I have data encrypted in c#, and need to put together a demo of how to decrypt in javascript. (Note, this is just for a demo - we will not be putting keys into client side code!)
I cannot get the settings right using Crypto-js - I've tried lots of variations, but am getting nowhere.
I cannot change the c# code, so need to get the javascript to work the same way.
Current skeleton code is as follows -
C# (encrypt)
var EncryptionKey = Encoding.ASCII.GetBytes("14ggh11dd3fvv4n4aabb33a3");
var IV = Encoding.ASCII.GetBytes("312a44de");
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = EncryptionKey;
tdes.IV = IV;
byte[] buffer = Encoding.ASCII.GetBytes("test");
var ciphertext = Convert.ToBase64String(tdes.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length));
Console.WriteLine(HttpUtility.UrlEncode(ciphertext));
which generates the cipher VrB1Ih0Ll%2fQ%3d
javascript (decrypt)
function decryptByDESModeCBC(ciphertext) {
var key = '14ggh11dd3fvv4n4aabb33a3';
var iv = '312a44de'
ciphertext = decodeURIComponent(ciphertext);
var keyBytes = CryptoJS.enc.Utf8.parse(key);
var ivBytes = CryptoJS.enc.Utf8.parse(iv);
var decrypted = CryptoJS.DES.decrypt({
ciphertext: CryptoJS.enc.Base64.parse(ciphertext)
}, keyBytes, {
iv:ivBytes,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
});
return decrypted.toString(CryptoJS.enc.Utf8);
}
function test()
{
console.log(decryptByDESModeCBC("VrB1Ih0Ll%2fQ%3d"));
}
Expected result is "test", but I am getting blank.
Any pointers would be great.
As answered by #Topaco in the comments
I needed to use CryptoJS.TripleDES instead of CryptoJS.DES

Using CryptoJS to encrypt and Aes Manager to decrypt

I am using CryptoJS to encrypt a message and send it to the server, and decrypting it on the other end in C# using Aes Manager. I get a response back when I send it to the server, but it isn't correct.
Javascript:
this.CryptoJS=require("crypto-js");
var temp=this.CryptoJS.AES.encrypt("hello","yyyyyyyyyyyyyyyyyyyyyyyyyyyyykey",{
keySize:128/8,
iv:this.CryptoJS.enc.Utf8.parse("helllooohelllooo"),
mode:this.CryptoJS.mode.CBC,
padding:this.CryptoJS.pad.ZeroPadding
});
data.text=temp.toString(); // This is how I send it to the server
C#:
byte[] Key = UTF8Encoding.UTF8.GetBytes("yyyyyyyyyyyyyyyyyyyyyyyyyyyyykey");
byte[] toBytes = UTF8Encoding.UTF8.GetBytes("helllooohelllooo");
AesManaged aes = new AesManaged();
aes.Key = Key;
aes.IV = toBytes;
aes.Padding = PaddingMode.Zeros;
aes.Mode = CipherMode.CBC;
aes.KeySize = 128;
aes.BlockSize = 128;
byte[] bytes = Convert.FromBase64String(data.text);
UTF8Encoding utf8 = new UTF8Encoding();
using (ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV))
{
MemoryStream MS = new MemoryStream(bytes);
CryptoStream CS = new CryptoStream(MS, decryptor, CryptoStreamMode.Write);
CS.Write(bytes, 0, bytes.Length);
CS.FlushFinalBlock();
MS.Position = 0;
bytes = new byte[MS.Length];
MS.Read(bytes, 0, bytes.Length);
Plaintext = utf8.GetString(bytes);
var temp = 5;
}
This is what I get as a result from the Plaintext variable: t�k�\a``\u007f������\f^,F~\u0017�\u001fp��#5�\u007f\\
You should explicitly pass the key, plaintext and IV as binary data rather than strings:
let iv = CryptoJS.enc.Utf8.parse("helllooohelllooo");
let pt = CryptoJS.enc.Utf8.parse("hello");
let key = CryptoJS.enc.Utf8.parse("yyyyyyyyyyyyyyyyyyyyyyyyyyyyykey");
Then use in the code like so:
CryptoJS.AES.encrypt(pt, key, ...);
Note that your use of zero padding, fixed IV, and no HMAC or AEAD mode makes the code you have completely insecure. You definitely should not use it. Consult this GitHub repository for examples of secure encryption between JavaScript and C#.
I was able to fix my problem i was not converting the original key to utf8 and once i did that it fixed itself
Resource

Javascript encryption in Crypto decryption in CryptoJS

I'm trying to encrypt server side (crypto Node) and decrypt client side (CryptoJS). I can create the key using cryptoJS, and can encrypt and decrypt when the same individual library is used however the issue is I cannot encrypt with Crypto but decrypt with CryptoJS, which is the real world scenario. There are no errors, just an empty response.
Any help greatly appreciated please!
iv = crypto.randomBytes(16),
orig = 'A confidential message.';
//Crypto JS creates key
var password = "sixteen byte key";
var salt = CryptoJS.lib.WordArray.random(128/8);
var key = CryptoJS.PBKDF2(password, salt, { keySize: 128 / 32, iterations: 1000 });
console.log("step1 generated key: "+ key);
//Convert key for crypto use - as a Buffer
var hashHex = key.toString(CryptoJS.enc.Hex);
var hash = new Buffer(hashHex,'hex');
//Test encryption and decryption with crypto (Node)
//use CryptoJS key to encrypt data using crypto cipheriv
var cipher2 = crypto.createCipheriv('aes-128-cbc', hash, iv); //iv must be a buffer
var encrypted1 = cipher2.update(orig, 'utf8', 'hex');
var encrypted2 = encrypted1 += cipher2.final('hex');
console.log("Crypto string:", encrypted2.toString());
// Start decrypt
var decipher = crypto.createDecipheriv('aes-128-cbc', hash, iv);
var dec = decipher.update(encrypted2, 'hex', 'utf8')
dec += decipher.final('utf8');
console.log("Crypto decrypted msg:", dec);
//test with crypto JS (ie the client)
//CryptoJS key is a string
var encryptedCJS = CryptoJS.AES.encrypt(orig, key.toString(), { iv: iv, mode: CryptoJS.mode.CBC});
console.log("CryptoJS encrypted: "+encryptedCJS);
var decryptedCryptoJS = CryptoJS.AES.decrypt(encryptedCJS, key.toString(), { mode: CryptoJS.mode.CBC, iv: iv });
console.log("CryptoJS decrypted msg: "+decryptedCryptoJS.toString(CryptoJS.enc.Utf8));
//This part does not work - use message encrypted by crypto but cannot decrypt with CryptoJS. decryptedCryptoJSFinal is empty
var decryptedCryptoJSFinal = CryptoJS.AES.decrypt(encrypted2, key.toString(), {iv: iv, mode: CryptoJS.mode.CBC});
console.log("FINAL CryptoJS decrypted: "+decryptedCryptoJSFinal.toString(CryptoJS.enc.Utf8));
I think the output of crypto encryption must be a different format to output of CryptoJS encryption but I cannot find the issue.
Overall I then intend to send the encrypted data as JSON for decryption on the client by CryptoJS.
I think your problem is in the client, if you pass the 'key' and the 'iv' as strings into 'CryptoJS.AES.encrypt', then CryptoJS takes your 'key' and a random 'salt' and generates a different secret key for the cipher. You can verify it generating different cipherTexts from the same clearText with the same key and iv, they will always be different, because a different secret key is generated inside CryptoJS each time you run the function.
To avoid this you need to pass the 'key' and 'iv' encoded (in 'hex' or 'base64' depending in the code you use) and then CryptoJS interprets that it doesn't have to generate a secret key and takes your 'key' to cipher.
Check this example:
//BACKEND with node crypto aes-256-cbc-> generate key and ciphertext
/////////////////////////////////////////////////////////////////////
var crypto = require('crypto');
var algorithm = 'aes-256-cbc';
var inputEncoding = 'utf8';
var outputEncoding = 'base64';
var pt = 'HELLO';
//generate key and iv
var masterKey = "253D3FB468A0E24677C28A624BE0F939";
var salt = "0000000000000000";
var keySize = 256/8;
var ivSize = 128/8;
var iterations = 100;
var outputKey = crypto.pbkdf2Sync(masterKey, salt, iterations, keySize+ivSize, "sha1");
// obtain key and IV splitting outputKey
var buffer = new Buffer(outputKey, inputEncoding);
var secretKey = buffer.slice(0, keySize);
var iv = buffer.slice(keySize, (keySize+ivSize));
console.log('secretKey->',secretKey.toString('base64'));
console.log('iv->',iv.toString('base64'));
//encrypt
var encrypt = crypto.createCipheriv(algorithm, secretKey, iv);
var encrypted = encrypt.update(pt, inputEncoding, outputEncoding);
encrypted += encrypt.final(outputEncoding);
console.log('Ciphering "%s"', pt);
//We obtain a
console.log('CipherText base64' string "%s ', encrypted.toString());
//FRONTEND with node CryptoJS aes-256-cbc-> generate same key and obtain cleartext
////////////////////////////////////////////////////////////////////
var masterKey = "253D3FB468A0E24677C28A624BE0F939";
var salt ="0000000000000000";
var iterations = 100;
var keySize = 256;
var ivSize = 128;
var outputKey = CryptoJS.PBKDF2(masterKey, salt, {
keySize: (keySize+ivSize)/32,
iterations: iterations
});
// the underlying words arrays might have more content than was asked: remove insignificant words
outputKey.clamp();
// split key and IV
var secretKey = CryptoJS.lib.WordArray.create(outputKey.words.slice(0,
keySize/32));
var iv = CryptoJS.lib.WordArray.create(outputKey.words.slice(keySize/32));
console.log('secretKey->', secretKey.toString(CryptoJS.enc.Base64));
console.log('iv->', iv.toString(CryptoJS.enc.Base64));
var decrypted = CryptoJS.AES.decrypt(ct, secretKey,{iv: iv});//Default mode CBC { mode: CryptoJS.mode.CFB });
console.log('CipherText->', ct);
console.log('ClearText decrypted', decrypted.toString(CryptoJS.enc.Utf8));

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