tripledes encryption not yielding same results in PHP and C#
public static string Encrypt(string toEncrypt, string key, bool useHashing)
{
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
if (useHashing)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(key);
TripleDESCryptoServiceProvider tdes
= new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0,
toEncryptArray.Length);
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
The above post and code has a bit of pretty straight forward (or so I thought) logic to encrypt/decrypt a string using 3DES and a private key.
I've found a few examples of how to implement something similar in nodejs using the crypt library but everything I've tried thus far has produced garbage (and rightfully so).
Thoughts?
UPDATE1:
Here is a bit of C# code to generate the data I'm working with:
String key = "abcdefghijklmnop";
String text = "12345";
String encrypted = Encrypt(text, key, false);
//Returns "QI3I65+aWSk="
And here's the latest revision of the nodejs code I was working with:
var crypto = require('crypto');
var key = 'abcdefghijklmnop';
var encrypted = 'QI3I65+aWSk=';
var expected = '12345';
var algs = [ 'des3', 'des-ede', 'des-ede3', 'des-ecb', 'aes-128-ecb'];
for(var i in algs)
{
var decipher = crypto.createDecipher(algs[i], key);
var result = ''
result += decipher.update(encrypted, 'hex', 'binary');
result += decipher.final('binary');
console.log('Algorithm: ' + algs[i]
+ ', Matched Expected: ' + (result === expected));
}
.. which returns
Algorithm: des3, Matched Expected: false
Algorithm: des-ede, Matched Expected: false
Algorithm: des-ede3, Matched Expected: false
Algorithm: des-ecb, Matched Expected: false
Algorithm: aes-128-ecb, Matched Expected: false
I wasn't clear as to exactly which algorithm to use (my list was significantly longer in previous attempts) now was I sure as to what encoding combination (binary/hex) to use.
Thanks again.
UPDATE2: Copied over the Encrypt method from the referenced post:
tripledes encryption not yielding same results in PHP and C#