Oldville
Oldville

Reputation: 111

issue with RSA encryption with PyCryptodome

I need to fix a client/server interaction based on PyCryptodome.

The client generates its RSA keys and sends the public one to a server:

n_bin_size = 1024
e = 65537
key = RSA.generate(n_bin_size, None, e) # RsaKey object
public_key = key.publickey().exportKey('PEM')
print(str(len(public_key)))
conn.send(public_key)

The server gets the private key and uses it to encrypt a session key:

data = conn.recv(271).decode()
pub_key = RSA.import_key(data)
session_key = b"key1key1key1key1"
cipher_rsa = PKCS1_OAEP.new(pub_key)
try:
  enc_session_key = cipher_rsa.encrypt(session_key)
except (AttributeError):
  print("Attribute error..")

The session_key is actually encrypted correctly, but an AttributeError exception is always raised, with the following message:

Traceback (most recent call last):
  File "Bob.py", line 33, in <module>
    enc_session_key = cipher_rsa.encrypt(session_key)
  File "/usr/local/lib/python3.7/site-packages/Cryptodome/Cipher/PKCS1_OAEP.py", line 107, in encrypt
    modBits = Cryptodome.Util.number.size(self._key.n)
AttributeError: 'int' object has no attribute 'n'

Is it possible to fix this issue?

Update: there is a similar question, at:

RSA decryption of AES Session key fails with 'AttributeError: 'bytes' object has no attribute 'n'

But the answer to that question does not solve my issue. Of course the exception is not raised if I use a "full" RsaKey object instead of the public-key RsaKey object, but I think it would be wrong to send the "full" RsaKey object to the server, isn't it?

Upvotes: 1

Views: 1206

Answers (2)

Oldville
Oldville

Reputation: 111

Actually, there was an error in the communication protocol: I didn't noticed the server received a second message and tried to use it to create an RsaKey. Now everything works fine (with the code I posted). Thank you for the useful feedback.

Upvotes: 0

ron
ron

Reputation: 186

Everything I have read agrees with your code, and you match the examples well.
The next step to trouble shooting would be to verify the sent data matches the recived data. Start looking at the data your sending to import_key().

Upvotes: 0

Related Questions