This repository was archived by the owner on Apr 28, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCryptWrapper.py
More file actions
36 lines (30 loc) · 1.7 KB
/
Copy pathCryptWrapper.py
File metadata and controls
36 lines (30 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import os
from typing import Tuple
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.dh import DHPrivateKey, DHParameters
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
class CryptWrapper:
@classmethod
def generate_dh_keys(cls, dh_parameters: DHParameters) -> Tuple[DHPrivateKey, bytes]:
private = dh_parameters.generate_private_key()
return private, private.public_key().public_bytes(encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo)
@classmethod
def generate_aes_gcm_key(cls, self_private_dh: DHPrivateKey, other_public_dh: bytes) -> AESGCM:
hkdf = HKDF(algorithm=hashes.SHA256(), length=32, salt=None, info=None, backend=default_backend())
received_public_key = serialization.load_pem_public_key(other_public_dh, backend=default_backend())
shared_key = self_private_dh.exchange(received_public_key)
aesgcm_key = hkdf.derive(shared_key)
# TODO: Force overwrite other_public, self_private, shared_key, and aesgcm_key
return AESGCM(aesgcm_key)
@classmethod
def encrypt(cls, aesgcm: AESGCM, plaintext: bytes) -> bytes:
nonce = os.urandom(12)
return nonce + aesgcm.encrypt(nonce, plaintext, None)
@classmethod
def decrypt(cls, aesgcm: AESGCM, ciphertext: bytes) -> bytes:
nonce, ciphertext = ciphertext[:12], ciphertext[12:]
return aesgcm.decrypt(nonce, ciphertext, None)