1

I have the following code to encrypt/decrypt data in node.js, which is working:

var cipher = crypto.createCipher('aes256', 'passphrase');  
var encrypted = cipher.update("test", 'utf8', 'base64') + cipher.final('base64');

var decipher = crypto.createDecipher('aes256', 'passphrase');   
var plain = decipher.update(encrypted, 'base64', 'utf8') + decipher.final('utf8');

I would like to be able to do the same in C#/.NET so that I can share data between two seperate systems. However the code that I have seen in .NET requires a Key and IV to entrypt/decrypt. How are these derived from the passphrase in the node.js Crypto library?

Tom Haigh
  • 57,217
  • 21
  • 114
  • 142

1 Answers1

2

From the node.js source I found this:

 bool CipherInit(char* cipherType, char* key_buf, int key_buf_len) {
cipher = EVP_get_cipherbyname(cipherType);
if(!cipher) {
  fprintf(stderr, "node-crypto : Unknown cipher %s\n", cipherType);
  return false;
}

unsigned char key[EVP_MAX_KEY_LENGTH],iv[EVP_MAX_IV_LENGTH];
int key_len = EVP_BytesToKey(cipher, EVP_md5(), NULL,
  (unsigned char*) key_buf, key_buf_len, 1, key, iv);

I found a c# implementation of EVP_BytesToKey in this question which can be used like this:

byte[] key, iv;
DeriveKeyAndIV(Encoding.ASCII.GetBytes("passphrase"),null, 1, out key, out iv);

                     //this is what node.js gave me as the base64 encrypted data
var encrytedBytes = Convert.FromBase64String("b3rbg+mniw7p9aiPUyGthg==");

The key and IV can then be used in an instance of RijndaelManaged to decrypt encrytedBytes

Community
  • 1
  • 1
Tom Haigh
  • 57,217
  • 21
  • 114
  • 142
  • If I use a passphrase with unicode, the encoding to bytes is different than node.js uses... any hints? – Tracker1 Aug 29 '13 at 04:44
  • Nodejs uses the [Latin1 encoding](https://nodejs.org/api/crypto.html#crypto_crypto_createcipher_algorithm_password). You need to use `Encoding.GetEncoding("ISO-8859-1")` instead of ASCII – Vladimir Vasilev Oct 26 '16 at 16:26