The error ImportError: No module named Crypto.Cipher typically occurs when Python cannot find the Crypto.Cipher module. This module is a part of the PyCryptodome library.

Install the pycryptodome

Install the pycryptodome using the following command. You can install it using the following command.

pip install pycryptodome

Uninstall PyCrypto (If Installed)

If the older version of PyCrypto library is installed, it can cause conflicts. Uninstall it using the pip command.

pip uninstall pycrypto

Check the python environment

We need to make sure that we are working in a correct Python environment where PyCryptodome is installed. Use pip list or pip freeze commands to check the installed packages.

Check the import statement

We need to ensure that the import statement is correct. It should be as shown below.

from Crypto.Cipher import AES

We tried to import the AES cipher in the above example. You can replace it with the specific cipher you need. Python is case-sensitive. We need to ensure that the import statement matches that of the actual module (Crypto, not crypto).

Following is the example:

from Crypto.Cipher import AES
import os

key = os.urandom(16)  # Random 16-byte key
cipher = AES.new(key, AES.MODE_EAX)

# Encrypt a message
message = b'Secret Message'
nonce = cipher.nonce
ciphertext, tag = cipher.encrypt_and_digest(message)

print(f'Ciphertext: {ciphertext}')

Categorized in:

Tagged in: