AES¶
AES (Advanced Encryption Standard) is a symmetric block cipher standardized by NIST . It has a fixed data block size of 16 bytes. Its keys can be 128, 192, or 256 bits long.
AES is very fast and secure, and it is the de facto standard for symmetric encryption.
On its own, a block cipher can only encrypt a single block of 16 bytes.
To protect messages of any length, you combine it with a mode of operation,
which you select with the mode parameter of new().
The table in Modes of operation lists the modes you can choose from.
Tip
For a step-by-step explanation of how to encrypt data with AES, including large files, see the guide Encrypt data with a secret key.
For instance, you can encrypt and authenticate a message with AES in GCM mode:
>>> from Crypto.Cipher import AES
>>> from Crypto.Random import get_random_bytes
>>>
>>> data = b'The secret message'
>>> key = get_random_bytes(16)
>>> nonce = get_random_bytes(12)
>>> cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
>>> ciphertext, tag = cipher.encrypt_and_digest(data)
You must deliver the triple (nonce, ciphertext, tag) to the recipient.
The nonce and the tag are not secret, but the key is.
With the same key, the recipient decrypts the message and checks that it is authentic:
>>> from Crypto.Cipher import AES
>>>
>>> cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
>>> try:
... plaintext = cipher.decrypt_and_verify(ciphertext, tag)
... print("The message is authentic:", plaintext)
... except ValueError:
... print("Key incorrect or message corrupted")
Modes of operation¶
The object returned by new() depends on the mode of operation:
follow the link in the last column for its methods and attributes.
|
Mode of operation |
Protects |
Cipher object |
|---|---|---|---|
|
confidentiality + authenticity |
||
|
confidentiality + authenticity |
||
|
confidentiality + authenticity |
||
|
confidentiality + authenticity |
||
|
confidentiality + authenticity |
||
|
confidentiality + authenticity |
||
|
confidentiality only |
||
|
confidentiality only |
||
|
confidentiality only |
||
|
confidentiality only |
||
|
confidentiality only |
||
|
confidentiality only (weak) |
||
|
confidentiality only, for storage |
||
|
keys (confidentiality + authenticity) |
||
|
keys (confidentiality + authenticity) |
Which mode should I use?¶
If in doubt, use GCM, with a random 12-byte nonce. It is an authenticated mode (AEAD): the recipient detects if the message was modified or encrypted with a different key. It is also the most widely supported by other libraries. The other authenticated modes (EAX, OCB, CCM) are equally secure.
Use GCM-SIV if you cannot guarantee that a nonce is never reused with the same key (or SIV, if you need a nonce of another size, or none at all).
Use the confidentiality only modes, like CTR or CBC, only to interoperate with existing protocols, and then combine them with a MAC (like
Crypto.Hash.HMAC). Never use ECB to encrypt more than one block.Use KW or KWP only to wrap other cryptographic keys.
Using the cipher object¶
encrypt()anddecrypt()process data. You can call them several times, each with the next piece of the message.The authenticated modes also have
update()(for associated data, that is, data that is authenticated but not encrypted, like a header),digest()andverify()(to create and check the MAC tag), andencrypt_and_digest()anddecrypt_and_verify()(to do everything in one call). See the introduction to modern modes.KW and KWP only have
seal()andunseal().The object also holds the parameters you must deliver to the recipient, such as
nonceoriv, whichnew()generates if you don’t pass them.
A cipher object is stateful and it can only process one message, either for encryption or for decryption. Create a new object (with a new nonce or IV) for each message.
API¶
- Crypto.Cipher.AES.new(key, mode, *args, **kwargs)¶
Create a new AES cipher.
- Parameters:
key (bytes/bytearray/memoryview) –
The secret key to use in the symmetric cipher.
It must be 16 (AES-128), 24 (AES-192) or 32 (AES-256) bytes long.
For
MODE_SIVonly, it doubles to 32, 48, or 64 bytes.For
MODE_GCM_SIVonly, it must be 16 or 32 bytes long.For
MODE_XTSonly, it must be 32 or 64 bytes long: two AES-128 or AES-256 keys (concatenated), which must be different.mode (a
MODE_*constant) – The chaining mode to use for encryption or decryption. If in doubt, useMODE_GCM(with a random 12-bytenonce).
- Keyword Arguments:
iv (bytes/bytearray/memoryview) –
(Only applicable for
MODE_CBC,MODE_CFB,MODE_OFB, andMODE_OPENPGPmodes).The initialization vector to use for encryption or decryption.
For
MODE_CBC,MODE_CFB, andMODE_OFBit must be 16 bytes long.For
MODE_OPENPGPmode only, it must be 16 bytes long for encryption and 18 bytes for decryption (in the latter case, it is actually the encrypted IV which was prefixed to the ciphertext).If not provided, a random byte string is generated (you must then read its value with the
ivattribute).nonce (bytes/bytearray/memoryview) –
(Only applicable for
MODE_CCM,MODE_EAX,MODE_GCM,MODE_SIV,MODE_GCM_SIV,MODE_OCB, andMODE_CTR).A value that must never be reused for any other encryption done with this key (except possibly for
MODE_SIVandMODE_GCM_SIV, see below).For
MODE_EAX,MODE_GCMandMODE_SIVthere are no restrictions on its length (recommended: 16 bytes).For
MODE_CCM, its length must be in the range [7..13]. Bear in mind that with CCM there is a trade-off between nonce length and maximum message size. Recommendation: 11 bytes.For
MODE_OCB, its length must be in the range [1..15] (recommended: 15).For
MODE_CTR, its length must be in the range [0..15] (recommended: 8).For
MODE_SIV, the nonce is optional, if it is not specified, then no nonce is being used, which renders the encryption deterministic.For
MODE_GCM_SIV, it must be 12 bytes long. Reusing a nonce only reveals if the same message was encrypted twice (with the same key, nonce and associated data).If not provided, for modes other than
MODE_SIV, a random byte string of the recommended length is used (you must then read its value with thenonceattribute).segment_size (integer) – (Only
MODE_CFB).The number of bits the plaintext and ciphertext are segmented in. It must be a multiple of 8. If not specified, it will be assumed to be 8.mac_len (integer) –
(Only
MODE_EAX,MODE_GCM,MODE_OCB,MODE_CCM) Length of the authentication tag, in bytes.It must be even and in the range [4..16]. The recommended value (and the default, if not specified) is 16.
msg_len (integer) – (Only
MODE_CCM). Length of the message to (de)cipher. If not specified,encryptmust be called with the entire message. Similarly,decryptcan only be called once.assoc_len (integer) – (Only
MODE_CCM). Length of the associated data. If not specified, all associated data is buffered internally, which may represent a problem for very large messages.initial_value (integer or bytes/bytearray/memoryview) – (Only
MODE_CTR). The initial value for the counter. If not present, the cipher will start counting from 0. The value is incremented by one for each block. The counter number is encoded in big endian mode.counter (object) – (Only
MODE_CTR). Instance ofCrypto.Util.Counter, which allows full customization of the counter block. This parameter is incompatible to bothnonceandinitial_value.use_aesni – (boolean): Use the AES instructions of the CPU (default: use if available): AES-NI on x86, or the Cryptography Extensions on 64-bit ARM.
threads (integer) – (Only
MODE_CTR,MODE_GCM,MODE_GCM_SIVandMODE_OCB). The maximum number of threads used to encrypt or decrypt long data (default: 1, no extra threads). Use 0 for as many threads as the CPU cores available to this process. Each thread processes at least 1 MiB of a single call toencrypt()ordecrypt(): with shorter inputs, fewer threads are used, or none at all. For best results, do not exceed the number of physical cores. The output does not depend on the number of threads.tweak (bytes/bytearray/memoryview) – (Only
MODE_XTS, where it is mandatory). The value that identifies the data unit, 16 bytes long. For a sector number, usenumber.to_bytes(16, "little").
- Returns:
Its class depends on
mode, see the table in Modes of operation.- Return type: