'C# to python RC2 encryption / decrypt

Looking for some help porting some code from c# to python. A long time ago some code was written to encrypt decrypt a column in our database. The problem is the code was written in c# and i am not familiar with that language. Mostly python, scala programmer.

From reading through the code I believe that the code is using rc2 for their algorithm. As seen on these 2 lines

var rc2Csp    = new RC2CryptoServiceProvider();
var encryptor = rc2Csp.CreateEncryptor(_Keys[keyOffset % numKeys], _Vs[keyOffset % numIVs]);

what I don't understand is how the cypher is being stored there is a key value pair that looks as following

(the actual values in the snippet below have been changed for security purposes)

 private static readonly byte[][] _Keys =
        {
            new byte[] {0x7a,0xca,0x7a,0xca,0x7a,0xca,0x7a,0xca,0x7a,0xca,0x7a,0xca,0x7a,0xca,0x7a,0xca}
         }
  private static readonly byte[][] _Vs =
        {   
         new byte[] {0xf3,0x1c,0xf3,0x1c,0xf3,0x1c,0xf3,0x1c}
        }

Im not sure how to use that key value pair inside python so that the cryptography library can decode the string.

Here is what i have so far that does not work

from Crypto.Cipher import AES
import Crypto.Cipher.AES
from binascii import hexlify, unhexlify
key        = unhexlify(b'0x7a,0xca,0x7a,0xca,0x7a,0xca,0x7a,0xca,0x7a,0xca,0x7a,0xca,0x7a,0xca,0x7a,0xca')
IV         = unhexlify('0xf3,0x1c,0xf3,0x1c,0xf3,0x1c,0xf3,0x1c')
plaintext1 = unhexlify('6bc1bee22e409f96e93d7e117393172a')
cipher = AES.new(key,AES.MODE_CBC,IV)
ciphertext = cipher.encrypt(plaintext1)
hexlify(ciphertext)


Solution 1:[1]

You need to find Python library which support RC2 encryption. Perhaps you can try that one: https://github.com/0xEBFE/RC2-python/blob/master/rc2.py

Create class of type RC2 and pass Key to it. Then call encrypt/decrypt methods which have 3 parameters:

  • input_buffer - data to encrypt/decrypt
  • mode - MODE_CBC or any other
  • IV - IV from C# code

In C# code, both _Keys and _Vs arrays contains multiple arrays of bytes (you left only one but they are declared as byte[][], so you need to replicate logic which picks up right key and IV.

For example,

_Keys[keyOffset % numKeys]

here there is numberic parameter keyOffset, code would pick key with index

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pakeha_by