RC2CryptoServiceProvider .NET algorithm differences with node js rc2 algorithm

1.7k Views Asked by At

Does .NET's RC2CryptoServiceProvider conform to OpenSSL. I'm using RC2CryptoServiceProvider with CBC but the encrypted value for the same text (using the same key and init vector) is different from what nodejs crypto library's rc2-cbc produces. Node js crypto library conforms to OpenSSL.

Someone had already asked about this discrepancy but no answers yet - Node.JS RC2-CBC Encryption and Decryption ciphers are not matching with C#

Can someone point me to the complete source code RC2CryptoServiceProvider? Is the encrypt/decrypt code a completely managed one available in C# or does it use C++ underneath?

I'm interested in finding the differences as I'm looking for a way to decrypt a .NET application encrypted string in node js.

Below is the C# code and the corresponding node js code. For the same data (HelloWorld), key and iv, the encrypted values produced are different.

public static string Encrypt(string data, string key, string iv)
{
    try
    {
        byte[] ivBytes = Encoding.ASCII.GetBytes(iv);
        byte[] keyBytes = Encoding.ASCII.GetBytes(key);
        byte[] dataBytes = Encoding.ASCII.GetBytes(data);
        RC2 rc = new RC2CryptoServiceProvider();
        rc.Mode = CipherMode.CBC;
        rc.Key = keyBytes;
        rc.IV = ivBytes;
        MemoryStream stream = new MemoryStream();
        CryptoStream stream2 = new CryptoStream(stream, rc.CreateEncryptor(), CryptoStreamMode.Write);
        stream2.Write(dataBytes, 0, dataBytes.Length);
        stream2.Close();
        return Convert.ToBase64String(stream.ToArray());
    }
    catch
    {
        return string.Empty;
    }
}

Below is the node js code.

algo = 'rc2-cbc'
key = '1234567890'
iv = 'someInit'

keyBuffer = new Buffer(key)
ivBuffer = new Buffer(iv)

cipher = crypto.createCipheriv(algo, keyBuffer, ivBuffer)
textBuffer = new Buffer('HelloWorld')
encrypted = cipher.update(textBuffer)
encryptedFinal = cipher.final()
encryptedText = encrypted.toString('base64') + encryptedFinal.toString('base64')

console.log encryptedText
1

There are 1 best solutions below

1
On

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!