aboutsummaryrefslogtreecommitdiffstats
path: root/docs/hazmat/primitives
diff options
context:
space:
mode:
Diffstat (limited to 'docs/hazmat/primitives')
-rw-r--r--docs/hazmat/primitives/symmetric-encryption.rst51
1 files changed, 38 insertions, 13 deletions
diff --git a/docs/hazmat/primitives/symmetric-encryption.rst b/docs/hazmat/primitives/symmetric-encryption.rst
index e05248ff..d3ba731a 100644
--- a/docs/hazmat/primitives/symmetric-encryption.rst
+++ b/docs/hazmat/primitives/symmetric-encryption.rst
@@ -365,20 +365,45 @@ Modes
:param bytes tag: The tag bytes to verify during decryption. When encrypting
this must be None.
- .. doctest::
+ .. code-block:: python
- >>> from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
- >>> from cryptography.hazmat.backends import default_backend
- >>> cipher = Cipher(algorithms.AES(key), modes.GCM(iv), backend=default_backend())
- >>> encryptor = cipher.encryptor()
- >>> encryptor.authenticate_additional_data(b"authenticated but not encrypted payload")
- >>> ct = encryptor.update(b"a secret message") + encryptor.finalize()
- >>> tag = encryptor.tag
- >>> cipher = Cipher(algorithms.AES(key), modes.GCM(iv, tag), backend)
- >>> decryptor = cipher.decryptor()
- >>> decryptor.authenticate_additional_data(b"authenticated but not encrypted payload")
- >>> decryptor.update(ct) + decryptor.finalize()
- 'a secret message'
+ def encrypt(key, plaintext, associated_data):
+ iv = os.urandom(12)
+ cipher = Cipher(
+ algorithms.AES(key),
+ modes.GCM(iv),
+ backend=default_backend()
+ )
+
+ encryptor = cipher.encryptor()
+ encryptor.authenticate_additional_data(associated_data)
+ ciphertext = encryptor.update(plaintext) + encryptor.finalize()
+
+ return (associated_data, iv, ciphertext, encryptor.tag)
+
+ def decrypt(key, associated_data, iv, ciphertext, tag):
+ cipher = Cipher(
+ algorithms.AES(key),
+ modes.GCM(iv, tag),
+ backend=default_backend()
+ )
+
+ decryptor = cipher.decryptor()
+ decryptor.authenticate_additional_data(associated_data)
+
+ return decryptor.update(ciphertext) + decryptor.finalize()
+
+ associated_data, iv, ciphertext, tag = encrypt(
+ key,
+ b"a secret message",
+ b"authenticated but not encrypted payload"
+ )
+
+ print(decrypt(key, associated_data, iv, ciphertext, tag))
+
+ .. testoutput::
+
+ a secret message
Insecure Modes