secret
Created

  • Download Gist
gistfile1.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
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)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.