Frequently Asked Questions

Is Python 2.7 supported?

No. Support for Python 2.7 was removed in version 4.0. The minimum supported version is now Python 3.9. If you are stuck with Python 2.7, you can still use PyCryptodome 3.x.

Why is PyCryptodome slower with bytearray data on PyPy?

While PyCryptodome processes data in C code, other Python threads keep running. On CPython, they cannot resize or free a bytearray or memoryview that the C code is still working on. PyPy 7.3 cannot prevent that, and PyPy 8.0 can only do it for bytearray.

So, on PyPy, if your program has more than one thread, PyCryptodome gives C code a private copy of any bytearray or memoryview that it cannot protect, both for the input data and for any output buffer. With large buffers, the extra copies make encryption and hashing noticeably slower and briefly need twice the memory.

To avoid the copies, pass the data as bytes, or use PyPy 8.0 or newer with bytearray objects. Single-threaded programs are not affected.

Only threads started from Python count: if native code calls into Python from threads of its own, pass data shared with them as bytes.

How can I encrypt using an ECC key?

Use Hybrid Public Key Encryption (HPKE, RFC 9180) and the module Crypto.Protocol.HPKE.

Is CTR cipher mode compatible with Java?

Yes. When you instantiate your AES cipher in Java:

Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");

SecretKeySpec keySpec = new SecretKeySpec(new byte[16], "AES");
IvParameterSpec ivSpec = new IvParameterSpec(new byte[16]);

cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);

You are effectively using CTR mode without a fixed nonce and with a 128-bit big endian counter starting at 0. The counter will wrap around only after 2¹²⁸ blocks.

You can replicate the same keystream in PyCryptodome with:

ivSpec = b'\x00' * 16
ctr = AES.new(keySpec, AES.MODE_CTR, initial_value=ivSpec, nonce=b'')

How do I get the nonce or the next counter value in CTR mode?

The cipher object only has the attribute nonce, and it does not reveal the current value of the counter (see CTR mode). In most cases, you do not need it: create a new random 12-byte nonce for each message, and deliver it with the ciphertext:

nonce = get_random_bytes(12)
cipher = AES.new(key, AES.MODE_CTR, nonce=nonce)
ciphertext = cipher.encrypt(message)

A message can then be up to 64 GiB long: beyond that, the cipher raises Crypto.MessageTooLongError instead of repeating the keystream.

If you really need to count across messages (for instance, to guarantee that no counter block is ever used twice), use the whole block as the counter, and compute the next value yourself:

cipher = AES.new(key, AES.MODE_CTR, nonce=b'', initial_value=counter)
ciphertext = cipher.encrypt(message)
# Deliver counter with the ciphertext, and store the next value in a safe place
counter += (len(message) + 15) // 16

The division must round up, because a block of the keystream that was only partially used cannot be used again. You must also store the new value of counter reliably before using it, so that it does not go back if your program restarts.

If you use Crypto.Util.Counter.new(), you choose the prefix, the suffix and the initial value yourself, so you already have all the values that the recipient needs.

Remember that CTR mode does not detect if the ciphertext was modified: either combine it with a MAC or, better, use an authenticated mode.

Are RSASSA-PSS signatures compatible with Java?

Yes. For Java, you must consider that by default the mask is generated by MGF1 with SHA-1 (regardless of how you hash the message) and the salt is 20 bytes long.

If you want to use another algorithm or another salt length, you must instantiate a PSSParameterSpec object, for instance:

Signature ss = Signature.getInstance("SHA256withRSA/PSS");
PSSParameterSpec pssParameterSpec = new PSSParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), 32, 1);
ss.setParameter(pssParameterSpec);

Are RSASSA-PSS signatures compatible with OpenSSL?

Yes, but one quirk of OpenSSL (and of a few other libraries, especially if they are wrappers to OpenSSL) is that the salt length is computed in two possible ways:

Salt length

Value for EVP_PKEY_CTX_set_rsa_pss_saltlen()

openssl pkeyutl command

Same as digest size

RSA_PSS_SALTLEN_DIGEST

-pkeyopt rsa_pss_saltlen:digest

Maximized

RSA_PSS_SALTLEN_MAX

-pkeyopt rsa_pss_saltlen:max

In PyCryptodome, the salt length matches the digest size by default (which is what RFC8017 recommends). However, you can also maximize the salt length with:

key = RSA.import_key(open('privkey.der', 'rb').read())
h = SHA256.new(message)
max_salt_bytes = key.size_in_bytes() - h.digest_size - 2
signature = pss.new(key, salt_bytes=max_salt_bytes).sign(h)

Why does a security scanner report private keys in PyCryptodome?

The self-tests in Crypto.SelfTest contain keys and certificates used as test data, for instance in Crypto/SelfTest/PublicKey/test_import_RSA.py. Some scanners for container images, disk images or build artifacts report them as leaked private keys or as expired certificates.

These keys are public test vectors and protect nothing: they are not used by the library itself, only by its tests.

If you cannot whitelist them, build PyCryptodome from source with the environment variable PYCRYPTODOME_NO_SELFTEST set, so that Crypto.SelfTest is left out of the package:

PYCRYPTODOME_NO_SELFTEST=1 pip install pycryptodome --no-binary pycryptodome

See Installing without the self-tests for details.

Why do I get the error No module named Crypto on Windows?

Check the directory where Python packages are installed, like:

/path/to/python/Lib/site-packages/

You might find a directory named crypto, with all the PyCryptodome files in it.

The most likely cause is described here and you can fix the problem with:

pip uninstall crypto
pip uninstall pycryptodome
pip install pycryptodome

The root cause is that, in the past, you most likely installed an unrelated but similarly named package called crypto, which happens to operate under the namespace crypto.

The Windows filesystem is case-insensitive so crypto and Crypto are effectively considered the same thing. When you subsequently install pycryptodome, pip finds that a directory named with the target namespace already exists (under the rules of the underlying filesystem), and therefore installs all the sub-packages of pycryptodome in it. This is probably a reasonable behavior, if it wasn’t that pip does not issue any warning even if it could detect the issue.

Why do I get the error Cannot load native module?

For instance, OSError: Cannot load native module 'Crypto.Hash._SHA256'.

This error means that the C extensions of PyCryptodome were built for a platform other than the one of the Python that is loading them. The error message ends with the reason given by the operating system, for instance:

  • incompatible architecture (have 'x86_64', need 'arm64'): on a Mac with Apple silicon, the package was installed by an Intel (x86_64) Python running under Rosetta, or it came from a cache filled by one.

  • invalid ELF header: a macOS or Windows build is used on Linux, for instance in an AWS Lambda layer or a container prepared on a Mac.

  • cannot open shared object file: No such file or directory, although the file exists: a library that the file needs is missing. For instance, a build for glibc (most Linux distributions) is used on musl (Alpine Linux), or a build for x86-64 is used on ARM64.

To fix it, reinstall the package with the Python that will run your code:

python -m pip install --force-reinstall --no-cache-dir pycryptodome

For AWS Lambda and containers, install the package in an image with the same operating system, CPU architecture and Python version as the target. Do not copy the Crypto directory from another machine.

What if both pycryptodome and the old pycrypto are installed?

The two packages install their files in the same Crypto directory, and pip does not detect the conflict: whichever package was installed last overwrites some of the files of the other one. Typical symptoms are:

  • Crypto.__version__ is 2.6.1, and modern features are missing (for instance, AES.MODE_GCM): pycrypto was installed last.

  • strxor raises TypeError for a bytearray (argument 2 must be bytes, not bytearray): pycryptodome was installed last, but the native strxor module (.so or .pyd file) left by pycrypto takes priority over the Python module of pycryptodome.

  • ImportError: cannot import name 'AES' from 'Crypto.Cipher': pycrypto was uninstalled, and it removed the files it shared with pycryptodome.

Uninstalling pycrypto is not enough. Remove both packages, and then install pycryptodome again:

python -m pip uninstall -y pycrypto pycryptodome
python -m pip install pycryptodome

If one of your dependencies requires pycrypto, replace that dependency or move it to another virtual environment: the two packages cannot work side by side.

Why does strxor raise TypeError: argument 2 must be bytes, not bytearray?

Most probably you have installed both the pycryptodome and the old pycrypto packages: see What if both pycryptodome and the old pycrypto are installed?.

Why do I get a translation_unit_or_empty undefined error with pycparser?

Unfortunately, pycparser does not work when Python runs with -OO, which strips out the docstrings, causing this error. This is a known issue and it will not be fixed.

The possible workarounds are:

  • Do not run Python with -OO

  • Remove cffi and pycparser. PyCryptodome will fall back to ctypes for interfacing with the native modules.

  • Use an earlier version of pycparser (2.14)