RSA encryption in .NET, decryption in python

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 ...)

+3
source share
1 answer

, , : ( PKCS # 1) python, ( ) :

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 

, 02 (- 0xff...). 6 ( ) - "", , print - ...

+2

Source: https://habr.com/ru/post/1794692/


All Articles