Common encrypt/decrypt code example for C# and Node.js/crypto
Here is a work example using DES algorithm. reference
using System;
using System.Text;
using System.Security.Cryptography;
public class Test
{
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);
var tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
// tdes.Mode = CipherMode.CBC; // which is default
// tdes.Padding = PaddingMode.PKCS7; // which is default
Console.WriteLine("iv: {0}", Convert.ToBase64String(tdes.IV));
ICryptoTransform cTransform = tdes.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0,
toEncryptArray.Length);
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
public static void Main()
{
Console.WriteLine("encrypted as: {0}", Encrypt("12345", "abcdefghijklmnop", false));
}
}
which outputs
iv: pdMBMjdeFdo=
encrypted as: 3uDkdT6aQ3c=
And use the right algorithm des-ede-cbc in node.js:
var crypto = require('crypto');
var alg = 'des-ede-cbc';
var key = new Buffer('abcdefghijklmnop', 'utf-8');
var iv = new Buffer('pdMBMjdeFdo=', 'base64');
var encrypted = new Buffer('3uDkdT6aQ3c=', 'base64');
var source = '12345';
var cipher = crypto.createCipheriv(alg, key, iv);
var encoded = cipher.update(source, 'ascii', 'base64');
encoded += cipher.final('base64');
console.log(encoded, encrypted.toString('base64'));
var decipher = crypto.createDecipheriv(alg, key, iv);
var decoded = decipher.update(encrypted, 'binary', 'ascii');
decoded += decipher.final('ascii');
console.log(decoded, source);
which outputs
3uDkdT6aQ3c= 3uDkdT6aQ3c=
12345 12345