Skip to content

@Torikova /gist:5236687ae9c45a4332ef secret
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.