Last active
May 6, 2016 13:38
-
-
Save AndyNovo/1c6c20f3b3e39c0a5e0c58531581250e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from cryptography.hazmat.primitives.ciphers import (Cipher, algorithms, modes ) | |
from cryptography.hazmat.backends import default_backend | |
def encrypt(key, plaintext, associated_data): | |
# Generate a random 96-bit IV. | |
iv = os.urandom(12) | |
# Construct an AES-GCM Cipher object with the given key and a | |
# randomly generated IV. | |
encryptor = Cipher( | |
algorithms.AES(key), | |
modes.GCM(iv), | |
backend=default_backend() | |
).encryptor() | |
# associated_data will be authenticated but not encrypted, | |
# it must also be passed in on decryption. | |
encryptor.authenticate_additional_data(associated_data) | |
# Encrypt the plaintext and get the associated ciphertext. | |
# GCM does not require padding. | |
ciphertext = encryptor.update(plaintext) + encryptor.finalize() | |
return (iv, ciphertext, encryptor.tag) | |
def decrypt(key, associated_data, iv, ciphertext, tag): | |
# Construct a Cipher object, with the key, iv, and additionally the | |
# GCM tag used for authenticating the message. | |
decryptor = Cipher( | |
algorithms.AES(key), | |
modes.GCM(iv, tag), | |
backend=default_backend() | |
).decryptor() | |
# We put associated_data back in or the tag will fail to verify | |
# when we finalize the decryptor. | |
decryptor.authenticate_additional_data(associated_data) | |
# Decryption gets us the authenticated plaintext. | |
# If the tag does not match an InvalidTag exception will be raised. | |
return decryptor.update(ciphertext) + decryptor.finalize() | |
key="andy love simone" | |
message="0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" | |
header="this stuff will be part of the authentication but not encrypted" | |
iv, ciphertext, tag = encrypt( | |
key, | |
message, | |
header | |
) | |
print(decrypt( | |
key, | |
header, | |
iv, | |
ciphertext, | |
tag | |
)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment