I am trying to encrypt a short message using RSA algorithm in C # and decrypt the message using python script.
I would like to use .NET classes on the C # side and pycrypto on the python side. I managed to use both sides of the same key (which was not even trivial, since .NET does not support the standard PEM / DER format). Encryption / decryption works on both sides independently.
I use the PKCS # 1 add-on on the C # side (setting the parameter fOAEPfrom RSACryptoServiceProvider.Encryptto false), so I expect that after decrypting the block in python, I should see some kind of clear text (i.e. my "message" along with fill bytes)
But all I see is trash: (.
Are there any reservations / pitfalls that I am not familiar with on either side? I'm partly out of ideas ...
thanks Martin
Code example
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)
To transfer the keys, I use the method ToXmlString() RSACryptoServiceProvider. The resulting XML is processed in python, and the pycrypto-RSA object is initialized with
r = Crypto.PublicKey.RSA.construct((modulus, exponent, d, p, q))
where modulus, exponent, d, pand q- the corresponding fields .NET- structure RSAParameters. (as I mentioned, I can encrypt / decrypt the message using this key in python, also p*qgives modulus, so I think that importing the key works correctly ...)