0

I am trying to use the pycryptodome example of encrypting a file with an RSA key. The example is as follows

from Crypto.PublicKey import RSA
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES, PKCS1_OAEP

file_out = open("encrypted_data.bin", "wb")

recipient_key = RSA.import_key(open("receiver.pem").read())
session_key = get_random_bytes(16)

# Encrypt the session key with the public RSA key
cipher_rsa = PKCS1_OAEP.new(recipient_key)
file_out.write(cipher_rsa.encrypt(session_key))

# Encrypt the data with the AES session key
cipher_aes = AES.new(session_key, AES.MODE_EAX)
ciphertext, tag = cipher_aes.encrypt_and_digest(data)
[ file_out.write(x) for x in (cipher.nonce, tag, ciphertext) ]

And the error I receive is

AttributeError: module 'Crypto.PublicKey.RSA' has no attribute 'import_key'

I found another thread where this error was identified as a version problem with pyCrypto but I am trying to use PyCryptodome and I do have the latest version.

Legorooj
  • 2,646
  • 2
  • 15
  • 35
jaydoe
  • 1
  • 1
  • 2

1 Answers1

0

The method import_key was added in PyCryptodome v3.4. If you get that error message, it means you are in reality using PyCrypto or an older version of PyCryptodome.

  • How do I make sure I am using the correct version and not PyCrypto? – jaydoe Nov 14 '17 at 19:48
  • You can check the `Cipher.version_info` tuple. PyCryptodome will have version >=3.0.0. Or you can install `pycryptodomex`, which is still PyCryptodome but under the `Cryptodome` package (instead of `Crypto`, to avoid the collision). – SquareRootOfTwentyThree Feb 05 '18 at 16:02