Last active
December 25, 2015 20:29
-
-
Save Ivoz/7035239 to your computer and use it in GitHub Desktop.
This file contains 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
from __future__ import absolute_import, division, print_function | |
from cryptography.bindings import _default_api | |
class BlockCipher(object): | |
def __init__(self, cipher, mode, api=None): | |
super(BlockCipher, self).__init__() | |
if api is None: | |
api = _default_api | |
self.cipher = cipher | |
self.mode = mode | |
self._api = api | |
@property | |
def name(self): | |
return "{0}-{1}-{2}".format( | |
self.cipher.name, self.cipher.key_size, self.mode.name, | |
) | |
def encryptor(self): | |
return BlockCipherContext(self, 'encrypt') | |
def decryptor(self): | |
return BlockCipherContext(self, 'decrypt') | |
class BlockCipherContext(object): | |
def __init__(self, template, mode): | |
super(BlockCipherContext, self).__init__() | |
self.templ = template | |
# TODO: better values than encrypt and decrypt could be used... | |
if mode == 'encrypt': | |
self._ctx = template._api.create_block_cipher_encrypt_context( | |
template.cipher, template.mode) | |
updater = template._api.update_encrypt_context | |
elif mode == 'decrypt': | |
self._ctx = template._api.create_block_cipher_decrypt_context( | |
template.cipher, template.mode) | |
updater = template._api.update_decrypt_context | |
else: | |
raise ValueError('bad mode supplied') | |
# Assuming that None can be passed into api.update_*_context() | |
def update(self, data=None): | |
if self._ctx is None: | |
raise ValueError("Context was already finalized") | |
return updater(self._ctx, data) | |
self.update = update | |
def finalize(self): | |
result = self.update() | |
self._ctx = None | |
return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment