6a9d044afb4a8d6a6ca55b37c3858b536ed4465f
[iotcloud.git] / PyORAM / src / pyoram / crypto / aes.py
1 __all__ = ("AES",)
2
3 import os
4 import cryptography.hazmat.primitives.ciphers
5 import cryptography.hazmat.backends
6
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
12
13 class AES(object):
14
15     key_sizes = [k//8 for k in sorted(_aes.key_sizes)]
16     block_size = _aes.block_size//8
17
18     @staticmethod
19     def KeyGen(size_bytes):
20         assert size_bytes in AES.key_sizes
21         return os.urandom(size_bytes)
22
23     @staticmethod
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()
28
29     @staticmethod
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:]) + \
34                cipher.finalize()
35
36     @staticmethod
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
41
42     @staticmethod
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]) + \
48                cipher.finalize()