-
-
Save Torikova/5236687ae9c45a4332ef 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
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