4 import cryptography.hazmat.primitives.ciphers
5 import cryptography.hazmat.backends
7 _backend = cryptography.hazmat.backends.default_backend()
8 _aes = cryptography.hazmat.primitives.ciphers.algorithms.AES
9 _cipher = cryptography.hazmat.primitives.ciphers.Cipher
10 _ctrmode = cryptography.hazmat.primitives.ciphers.modes.CTR
11 _gcmmode = cryptography.hazmat.primitives.ciphers.modes.GCM
15 key_sizes = [k//8 for k in sorted(_aes.key_sizes)]
16 block_size = _aes.block_size//8
19 def KeyGen(size_bytes):
20 assert size_bytes in AES.key_sizes
21 return os.urandom(size_bytes)
24 def CTREnc(key, plaintext):
25 iv = os.urandom(AES.block_size)
26 cipher = _cipher(_aes(key), _ctrmode(iv), backend=_backend).encryptor()
27 return iv + cipher.update(plaintext) + cipher.finalize()
30 def CTRDec(key, ciphertext):
31 iv = ciphertext[:AES.block_size]
32 cipher = _cipher(_aes(key), _ctrmode(iv), backend=_backend).decryptor()
33 return cipher.update(ciphertext[AES.block_size:]) + \
37 def GCMEnc(key, plaintext):
38 iv = os.urandom(AES.block_size)
39 cipher = _cipher(_aes(key), _gcmmode(iv), backend=_backend).encryptor()
40 return iv + cipher.update(plaintext) + cipher.finalize() + cipher.tag
43 def GCMDec(key, ciphertext):
44 iv = ciphertext[:AES.block_size]
45 tag = ciphertext[-AES.block_size:]
46 cipher = _cipher(_aes(key), _gcmmode(iv, tag), backend=_backend).decryptor()
47 return cipher.update(ciphertext[AES.block_size:-AES.block_size]) + \