2018-01-24 21:34:14 +00:00
|
|
|
import os
|
|
|
|
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
|
2018-01-23 07:40:36 +00:00
|
|
|
|
|
|
|
|
|
|
|
class UmbralDEM(object):
|
2018-01-23 09:40:13 +00:00
|
|
|
def __init__(self, symm_key: bytes):
|
|
|
|
"""
|
|
|
|
Initializes an UmbralDEM object. Requires a key to perform
|
2018-01-24 21:34:14 +00:00
|
|
|
ChaCha20-Poly1305.
|
2018-01-23 09:40:13 +00:00
|
|
|
"""
|
2018-01-24 21:34:14 +00:00
|
|
|
if len(symm_key) != 32:
|
2018-01-23 09:40:13 +00:00
|
|
|
raise ValueError(
|
|
|
|
"Invalid key size, must be {} bytes".format(SecretBox.KEY_SIZE)
|
|
|
|
)
|
|
|
|
|
2018-01-24 21:34:14 +00:00
|
|
|
self.cipher = ChaCha20Poly1305(symm_key)
|
2018-01-23 09:40:13 +00:00
|
|
|
|
2018-01-24 21:34:14 +00:00
|
|
|
def encrypt(self, data: bytes, authenticated_data: bytes=None):
|
2018-01-23 09:40:13 +00:00
|
|
|
"""
|
2018-01-24 21:34:14 +00:00
|
|
|
Encrypts data using ChaCha20-Poly1305 with optional authenticated data.
|
2018-01-23 09:40:13 +00:00
|
|
|
"""
|
2018-01-24 21:34:14 +00:00
|
|
|
nonce = os.urandom(12)
|
|
|
|
enc_data = self.cipher.encrypt(nonce, data, authenticated_data)
|
|
|
|
return nonce + enc_data
|
2018-01-23 09:40:13 +00:00
|
|
|
|
2018-01-24 21:34:14 +00:00
|
|
|
def decrypt(self, enc_data: bytes, authenticated_data: bytes=None):
|
2018-01-23 09:40:13 +00:00
|
|
|
"""
|
2018-01-24 21:34:14 +00:00
|
|
|
Decrypts data using ChaCha20-Poly1305 and validates the provided
|
|
|
|
authenticated data.
|
2018-01-23 09:40:13 +00:00
|
|
|
"""
|
2018-01-24 21:34:14 +00:00
|
|
|
nonce = enc_data[:12]
|
|
|
|
ciphertext = enc_data[12:]
|
|
|
|
plaintext = self.cipher.decrypt(nonce, ciphertext, authenticated_data)
|
2018-01-23 09:40:13 +00:00
|
|
|
return plaintext
|