RSA encryption in .NET, decryption in python
Question: I'm trying to encrypt a short message using RSA algorithm in C# and decrypt
the message using a python skript.

I'd like to use the .NET classes on the C# side and
[pycrypto](http://www.dlitz.net/software/pycrypto/) on python side. I've
managed both sides to use the same key (which was not even trivial since .NET
doesn't support the standard PEM/DER format directly). Encryption/decryption
works on both sides independently.

I'm using PKCS#1 padding on the C# side (setting the `fOAEP` parameter of
`RSACryptoServiceProvider.Encrypt` to `false`), so I'd expect that after
decrypting the block in python I should see some kind of clear text (i.e. my
"message" together with padding bytes)

But all I see is garbage :(.

Are there any caveats/pitfalls I'm not aware of on either side? I'm kind of
out of ideas ...

Thx Martin

**Sample code**

_C# / Encryption_

    
    
    Console.Write("Input string:");
    var s = Console.ReadLine();
    var b = Encoding.Default.GetBytes(s);
    var encrypted = rsa.Encrypt(b, false);
    using (var file = new FileStream(filename, FileMode.Create)) {
      file.Write(encrypted, 0, encrypted.Length);
      file.Flush();
      file.Close();
    }
    

_Python / Decryption_

    
    
    f = open(filename, "rb")
    msg = f.read()
    f.close()
    decrypted = rsa.decrypt(msg)
    print "Decrypted message:"
    print_hex(decrypted)
    

For Key transfer I'm using the `ToXmlString()` method of
`RSACryptoServiceProvider`. The resulting XML is parsed in python and the
_pycrypto_ -RSA object is initialized with

    
    
    r = Crypto.PublicKey.RSA.construct((modulus, exponent, d, p, q))
    

where `modulus`, `exponent`, `d`, `p` and `q` are the respective fields of the
.NET-`RSAParameters` structure. (as I've mentioned, I can encrypt/decrypt a
message using this key in python, also `p*q` yields `modulus`, so I think the
key import is working correctly ...)


Answer: Ok, it was my fault, I just didn't look at the results: The leading zero (from
PKCS#1 padding) is not part of the python result string, which looks (in hex)
like:

    
    
    02 a2 16 4e 51 45 aa 8d 
    94 b0 de 64 4d 4c 4c bd 
    0b 01 b8 d2 de dc ed 23 
    0b 25 c2 11 6c 0a 0b 1f 
    4f 19 d0 33 18 db e0 81 
    25 33 f6 e3 70 8d 97 d2 
    c7 ef 32 ef 27 3c c0 ac 
    47 68 c0 5b 7b 6d 0d ba 
    44 da cb bf e8 71 75 d3 
    2f 9a b1 97 6b 70 4f ff 
    98 6f 5a 9a 74 3c 65 94 
    eb 57 52 8a 2f 73 1f 14 
    7d 76 08 d3 e5 8b 82 b8 
    5d ed 2b 75 52 29 b5 22 
    af 76 55 bc 5d e9 41 99 
    00 4d 61 72 74 69 6e 
    

So, `02` at the beginning points to random padding (somehow I was expecting
0xff padding...). The last 6 bytes (after the zero) are exactly the "Message"
I was expecting, but a normal `print` didn't show them just because of the
zero byte...

