diff options
author | Alex Gaynor <alex.gaynor@gmail.com> | 2013-10-30 14:16:13 -0700 |
---|---|---|
committer | Alex Gaynor <alex.gaynor@gmail.com> | 2013-10-30 14:16:13 -0700 |
commit | 02fad008d3e99a49871144b56a692c2237a0d396 (patch) | |
tree | 55d76e02136cb46d5e8b795af13487719719903a | |
parent | d5e9c8ddf0e644a740945a29cfa486ba25426300 (diff) | |
download | cryptography-02fad008d3e99a49871144b56a692c2237a0d396.tar.gz cryptography-02fad008d3e99a49871144b56a692c2237a0d396.tar.bz2 cryptography-02fad008d3e99a49871144b56a692c2237a0d396.zip |
Started implementating encryption for fernet
-rw-r--r-- | cryptography/fernet.py | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/cryptography/fernet.py b/cryptography/fernet.py new file mode 100644 index 00000000..a0996afc --- /dev/null +++ b/cryptography/fernet.py @@ -0,0 +1,36 @@ +import base64 +import os +import struct +import time + +from cryptography.hazmat.primitives import padding, hashes +from cryptography.hazmat.primitives.hmac import HMAC +from cryptography.hazmat.primitives.block import BlockCipher, ciphers, modes + + +class Fernet(object): + def __init__(self, key): + super(Fernet, self).__init__() + self.signing_key = key[:16] + self.encryption_key = key[16:] + + def encrypt(self, data): + current_time = int(time.time()) + iv = os.urandom(16) + return self._encrypt_from_parts(data, current_time, iv) + + def _encrypt_from_parts(self, data, current_time, iv): + padder = padding.PKCS7(ciphers.AES.block_size).padder() + padded_data = padder.update(data) + padder.finalize() + encryptor = BlockCipher(ciphers.AES(self.encryption_key), modes.CBC(iv)).encryptor() + ciphertext = encryptor.update(padded_data) + encryptor.finalize() + + h = HMAC(self.signing_key, digestmod=hashes.SHA256) + h.update(b"\x80") + h.update(struct.pack(">Q", current_time)) + h.update(iv) + h.update(ciphertext) + hmac = h.digest() + return base64.urlsafe_b64encode( + b"\x80" + struct.pack(">Q", current_time) + iv + ciphertext + hmac + ) |