| 1 | import hashlib |
| 2 | import hmac |
| 3 | from cryptography.hazmat.primitives.asymmetric import rsa, padding |
| 4 | from cryptography.hazmat.primitives import serialization, hashes |
| 5 | import os |
| 6 | |
| 7 | |
| 8 | def hash_data(data: str, password: str): |
| 9 | return hmac.new(password.encode(), data.encode(), hashlib.sha256).hexdigest() |
| 10 | |
| 11 | |
| 12 | def verify_data(data: str, hash: str, password: str): |
| 13 | return hash_data(data, password) == hash |
| 14 | |
| 15 | |
| 16 | def _generate_private_key(): |
| 17 | return rsa.generate_private_key( |
| 18 | public_exponent=65537, |
| 19 | key_size=2048, |
| 20 | ) |
| 21 | |
| 22 | |
| 23 | def _generate_public_key(private_key: rsa.RSAPrivateKey): |
| 24 | return ( |
| 25 | private_key.public_key() |
| 26 | .public_bytes( |
| 27 | encoding=serialization.Encoding.PEM, |
| 28 | format=serialization.PublicFormat.SubjectPublicKeyInfo, |
| 29 | ) |
| 30 | .hex() |
| 31 | ) |
| 32 | |
| 33 | def _decode_public_key(public_key: str) -> rsa.RSAPublicKey: |
| 34 | # Decode hex string back to bytes |
| 35 | pem_bytes = bytes.fromhex(public_key) |
| 36 | # Load the PEM public key |
| 37 | key = serialization.load_pem_public_key(pem_bytes) |
| 38 | if not isinstance(key, rsa.RSAPublicKey): |
| 39 | raise TypeError("The provided key is not an RSAPublicKey") |
| 40 | return key |
| 41 | |
| 42 | def encrypt_data(data: str, public_key_pem: str): |
| 43 | return _encrypt_data(data.encode("utf-8"), _decode_public_key(public_key_pem)) |
| 44 | |
| 45 | def _encrypt_data(data: bytes, public_key: rsa.RSAPublicKey): |
| 46 | b = public_key.encrypt( |
| 47 | data, |
| 48 | padding.OAEP( |
| 49 | mgf=padding.MGF1(algorithm=hashes.SHA256()), |
| 50 | algorithm=hashes.SHA256(), |
| 51 | label=None, |
| 52 | ), |
| 53 | ) |
| 54 | return b.hex() |
| 55 | |
| 56 | def decrypt_data(data: str, private_key: rsa.RSAPrivateKey): |
| 57 | b = private_key.decrypt( |
| 58 | bytes.fromhex(data), |
| 59 | padding.OAEP( |
| 60 | mgf=padding.MGF1(algorithm=hashes.SHA256()), |
| 61 | algorithm=hashes.SHA256(), |
| 62 | label=None, |
| 63 | ), |
| 64 | ) |
| 65 | return b.decode("utf-8") |
| 66 |