TripleDES encryption - c# and javascript differences - javascript

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

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

Incorrect decryption output when using CryptoJS library for AES

I am trying to encrypt and decrypt some random data using AES. I can successfully encrypt data using the following code,
function padString(source) {
var paddingChar = 'x';
var size = 16;
var padLength = size - source.length;
for (var i = 0; i < padLength; i++) source += paddingChar;
return source;
}
var key = CryptoJS.enc.Hex.parse('dassdadsasad');
var iv = CryptoJS.enc.Hex.parse('fedcba9876543210');
var message = "0x72648174091c3f7cd41773f636ca9a15756798";
var padMsg = padString(message);
var encrypted = CryptoJS.AES.encrypt(padMsg, key, {
iv: iv,
padding: CryptoJS.pad.NoPadding,
mode: CryptoJS.mode.CBC
});
but when I try to decrypt it,
var decrypted = CryptoJS.AES.decrypt(encrypted, key, {
iv: iv,
padding: CryptoJS.pad.NoPadding,
mode: CryptoJS.mode.CBC
});
I get the incorrect output for decryption instead of getting back my plain text.
Here is the output for instance,
Message: "0x72648174091c3f7cd41773f636ca9a15756798" 40
Padded message: "0x72648174091c3f7cd41773f636ca9a15756798" 40
Encrypted: 8qCjEtSLhchErbhJu8jo/xy8T5T1eSAFazuWLKwKdAW9F0ZUjJLlZw==
Encrypted text: f2a0a312d48b85c844adb849bbc8e8ff1cbc4f94f57920056b3b962cac0a7405bd1746548c92e567
Decrypted c748c55c0212d1688e79de5f00379eb0d802789501e6cbab3e6255b902eaa528a40d32123bcd0ce1
Can someone please tell me what am I doing wrong or if I am missing something ?
Here is the live demonstration, https://jsfiddle.net/4zb9hrxb/267/
Your key is invalid:
var key = CryptoJS.enc.Hex.parse('dassdadsasad');
does not make much sense in the first place since s does not exist in hexadecimal notation. Either specify a 256 bit key as hex, like this:
key = CryptoJS.enc.Hex.parse("123456789012345678901234567890ab");
(note: only hexadecimal characters) or let CryptoJS derive the key from a passphrase:
var key = 'dassdadsasad';
either follow what phihag said, or you can use some key derivation function such as, PBKDF2 to derive key from passphrase (as phihag suggested).
consider this for example,
import pbkdf2,
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/pbkdf2.js"></script>
and generate key as follows,
var passphrase = "dassdadsasad"
var keySize = 256;
var iterations = 100;
var salt = CryptoJS.lib.WordArray.random(128/8);
var key = CryptoJS.PBKDF2(passphrase, salt, {
keySize: keySize/32,
iterations: iterations
});
there is a very good example available here,
http://www.adonespitogo.com/articles/encrypting-data-with-cryptojs-aes/

Encrypt string with Blowfish in NodeJS

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==

AES decryption fails in forge but works in crypto-js

I am decrypting a message string at a regular interval. After studying multiple jsperf's I've noticed forge and stanford are faster than cryptojs - I need that extra speed as I am bound to support older mobile devices, so I'm attempting to migrate.
Here is the working crpto-js code:
var feed = message.data.msg;
var iv = CryptoJS.enc.Hex.parse(_iv);
var key = CryptoJS.enc.Hex.parse(_key);
var decrypted = CryptoJS.AES.decrypt(feed.substr(32), key, { iv: iv });
feed = decrypted.toString(CryptoJS.enc.Utf8);
And now the non-working forge code:
var feed = message.data.msg;
var iv = forge.util.hexToBytes(_iv);
var key = forge.util.hexToBytes(_key);
var buffer = forge.util.createBuffer( feed.substr(32) );
var cipher = forge.aes.createDecryptionCipher(key);
cipher.start( iv );
cipher.update( buffer );
cipher.finish();
feed = cipher.output.toHex();
After decryption with forge I get a random jumble of characters. While stepping through the code, the only thing of note is a failure in forge/aes.js, line 969:
if(count > (Nb << 2)) {
rval = false;
}
Is firing and returning false.
I'm at a loss here as both libraries use CBC as the default for AES so everything should just work.
Have you tried changing:
var buffer = forge.util.createBuffer( feed.substr(32) );
To:
var buffer = forge.util.createBuffer( forge.util.decode64( feed.substr(32) ) );
And changing:
feed = cipher.output.toHex();
To:
feed = cipher.output.getBytes();

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

Categories

Resources