I have an existing encryption and decryption login inplemented in C# using RSC2-cbc algorithm using Key and IV. Now I am going to implement the same in node.js. So I have written following code to encryprt and decrypt. The problem I am facing is the node.js encrypted string (chiper) or decrypted string are not matching with C# encryptrd strings.
Existing C# code
byte[] arrbIV = Encoding.ASCII.GetBytes("dleftaba");
byte[] arrbKey = Encoding.ASCII.GetBytes(Key);
byte[] arrbData = Encoding.ASCII.GetBytes(sData); //Text to be encryptrd
RC2 oEncryptor = new RC2CryptoServiceProvider();
oEncryptor.Mode = CipherMode.CBC;
oEncryptor.Key = arrbKey;
oEncryptor.IV = arrbIV;
// Create memory stream to store encrypted string
MemoryStream oMemoryStream = new MemoryStream();
CryptoStream oCryptoStream = new CryptoStream(oMemoryStream, oEncryptor.CreateEncryptor(),
CryptoStreamMode.Write);
// Peform the encryption
oCryptoStream.Write(arrbData, 0, arrbData.Length);
// We have written all the data in the stream and now we can apply padding
oCryptoStream.Close();
string sRetVal = Convert.ToBase64String(oMemoryStream.ToArray());
Equivalent/ Translated node.js code
var crypto = require('crypto')
var SECRET_KEY = "435353553"
var IV = "dleftaba"
var ENCODING = 'base64'
var text = "My Text"
Encryption
var cipher = crypto.createCipheriv('rc2-cbc',key, iv)
var cryptedPassword = cipher.update(text, 'utf-8', 'base64')
cryptedPassword+= cipher.final('base64')
Decryption
var decipher = crypto.createDecipheriv('rc2-cbc', SECRET_KEY, IV)
var decryptedPassword = decipher.update(cryptedPassword, 'base64','utf-8')
decryptedPassword += decipher.final('utf-8')
Please suggest what is going wrong over here. Why node. js is not resulting into the identical chiper like C#.
This appears to be a duplicate of this question. Answering here too in case it helps.
I hit a similar situation. There is existing .NET (core) code using
RC2CryptoServiceProvider
to decrypt a string. I wanted to replicate this in node.The .NET code uses keysize 128 (which also appears to be the default) so I assumed the comparable algorithm in node (openssl) would be
rc2-128
. But this always failed when decrypting.After some trial and error I discovered that using using the
rc2-64
algorithm in node behaves the same as the .NET code using keysize 128. Just don't ask me why!