Danger
This is a “Hazardous Materials” module. You should ONLY use it if you’re 100% absolutely sure that you know what you’re doing because this module is full of land mines, dragons, and dinosaurs with laser guns. You may instead be interested in Fernet (symmetric encryption) .
Symmetric encryption
Symmetric encryption is a way to encrypt or hide the contents of material where the sender and receiver both use the same secret key. Note that symmetric encryption is not sufficient for most applications because it only provides secrecy but not authenticity. That means an attacker can’t see the message but an attacker can create bogus messages and force the application to decrypt them. In many contexts, a lack of authentication on encrypted messages can result in a loss of secrecy as well.
For this reason in nearly all contexts it is necessary to combine encryption
with a message authentication code, such as
HMAC
, in an “encrypt-then-MAC”
formulation as
described by Colin Percival
.
cryptography
includes a
recipe named
Fernet (symmetric encryption)
that does this for you.
To minimize the risk of
security issues you should evaluate Fernet to see if it fits your needs before
implementing anything using this module.
If
Fernet (symmetric encryption)
is not
appropriate for your use-case then you may still benefit from
Authenticated encryption
which combines encryption and authentication
securely.
- class cryptography.hazmat.primitives.ciphers. Cipher ( algorithm , mode ) [source]
-
Cipher objects combine an algorithm such as
AESwith a mode likeCBCorCTR. A simple example of encrypting and then decrypting content with AES is:>>> import os >>> from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes >>> key = os.urandom(32) >>> iv = os.urandom(16) >>> cipher = Cipher(algorithms.AES(key), modes.CBC(iv)) >>> encryptor = cipher.encryptor() >>> ct = encryptor.update(b"a secret message") + encryptor.finalize() >>> decryptor = cipher.decryptor() >>> decryptor.update(ct) + decryptor.finalize() b'a secret message'