Skip to content

Instantly share code, notes, and snippets.

@Torikova
Created December 15, 2013 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Torikova/5236687ae9c45a4332ef to your computer and use it in GitHub Desktop.
Save Torikova/5236687ae9c45a4332ef to your computer and use it in GitHub Desktop.
import hmac
from Crypto.Util import Counter
from Crypto import Random
from Crypto.Cipher import AES
SIGN_LENGTH = 4
class Encryptor(object):
def __init__(self, key):
self.key = key
self.counter = Counter.new(128, initial_value=0)
def process(self, data):
tag = hmac.new(self.key, data).digest()[:SIGN_LENGTH]
cipher = AES.new(self.key, AES.MODE_CTR, counter=self.counter)
return tag + cipher.encrypt(data)
class Decryptor(object):
def __init__(self, key):
self.key = key
self.counter = Counter.new(128, initial_value=0)
def process(self, data):
tag = data[:SIGN_LENGTH]
ciphertext = data[SIGN_LENGTH:]
cipher = AES.new(self.key, AES.MODE_CTR, counter=self.counter)
plaintext = cipher.decrypt(ciphertext)
assert(hmac.new(self.key, plaintext).digest()[:SIGN_LENGTH] == tag)
return plaintext
if __name__ == '__main__':
secret_key = Random.new().read(16)
e = Encryptor(secret_key)
plain_text = 'The Magic Words are Squeamish Ossifrage'
cipher = e.process(plain_text)
d = Decryptor(secret_key)
assert(d.process(cipher) == plain_text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment