Coverage for src/couchers/crypto.py: 96%
90 statements
« prev ^ index » next coverage.py v7.5.0, created at 2024-12-20 18:03 +0000
« prev ^ index » next coverage.py v7.5.0, created at 2024-12-20 18:03 +0000
1import functools
2import secrets
3from base64 import urlsafe_b64decode, urlsafe_b64encode
4from typing import Optional, Union
6import nacl.pwhash
7import nacl.utils
8from nacl.bindings import crypto_aead
9from nacl.bindings.crypto_generichash import generichash_blake2b_salt_personal
10from nacl.bindings.utils import sodium_memcmp
11from nacl.exceptions import InvalidkeyError
12from nacl.public import PrivateKey, PublicKey, SealedBox
13from nacl.utils import random as random_bytes
15from couchers.config import config
18def b64encode(data: bytes) -> str:
19 return urlsafe_b64encode(data).decode("ascii")
22def b64decode(data: str) -> bytes:
23 return urlsafe_b64decode(data)
26def b64encode_unpadded(data: str) -> bytes:
27 return b64encode(data).replace("=", "")
30def b64decode_unpadded(data: bytes) -> str:
31 return b64decode(data + b"===="[len(data) % 4 :])
34def urlsafe_random_bytes(length=32) -> str:
35 return b64encode(random_bytes(length))
38def urlsafe_secure_token():
39 """
40 A cryptographically secure random token that can be put in a URL
41 """
42 return urlsafe_random_bytes(32)
45def cookiesafe_secure_token():
46 return random_hex(32)
49def hash_password(password: str):
50 return nacl.pwhash.str(password.encode("utf-8"))
53def verify_password(hashed: bytes, password: str):
54 try:
55 correct = nacl.pwhash.verify(hashed, password.encode("utf-8"))
56 return correct
57 except InvalidkeyError:
58 return False
61def random_hex(length=32):
62 """
63 Length in binary
64 """
65 return random_bytes(length).hex()
68def secure_compare(val1, val2):
69 return sodium_memcmp(val1, val2)
72def generate_hash_signature(message: bytes, key: bytes) -> bytes:
73 """
74 Computes a blake2b keyed hash for the message.
76 This can be used as a fast yet secure symmetric signature: by checking that
77 the hashes agree, we can make sure the signature was generated by a party
78 with knowledge of the key.
79 """
80 return generichash_blake2b_salt_personal(message, key=key, digest_size=32)
83def simple_hash_signature(message: Union[bytes, str], key_name: str) -> str:
84 if isinstance(message, str):
85 msg_bytes = message.encode("utf8")
86 else:
87 msg_bytes = message
88 return b64encode(generate_hash_signature(message=msg_bytes, key=get_secret(key_name)))
91def verify_hash_signature(message: bytes, key: bytes, sig: bytes) -> bool:
92 """
93 Verifies a hash signature generated with generate_hash_signature.
95 Returns true if the signature matches, otherwise false.
96 """
97 return secure_compare(sig, generate_hash_signature(message, key))
100def generate_random_5digit_string():
101 """Return a random 5-digit string"""
102 return f"{secrets.randbelow(100000):05d}"
105def verify_token(a: str, b: str):
106 """Return True if strings a and b are equal, in such a way as to
107 reduce the risk of timing attacks.
108 """
109 return secrets.compare_digest(a, b)
112@functools.lru_cache
113def get_secret(name: str):
114 """
115 Derives a secret key from the root secret using a key derivation function
116 """
117 return generate_hash_signature(name.encode("utf8"), config["SECRET"])
120UNSUBSCRIBE_KEY_NAME = "unsubscribe"
121EMAIL_SOURCE_DATA_KEY_NAME = "email-source-data"
122PAGE_TOKEN_KEY_NAME = "pagination"
125# AEAD: Authenticated Encryption with Associated Data
127_aead_key_len = crypto_aead.crypto_aead_xchacha20poly1305_ietf_KEYBYTES
128_aead_nonce_len = crypto_aead.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES
131def aead_generate_nonce():
132 return random_bytes(_aead_nonce_len)
135def aead_generate_key():
136 return random_bytes(_aead_key_len)
139def aead_encrypt(key: bytes, secret_data: bytes, plaintext_data: bytes = b"", nonce: Optional[bytes] = None) -> bytes:
140 if not nonce:
141 nonce = aead_generate_nonce()
142 encrypted = crypto_aead.crypto_aead_xchacha20poly1305_ietf_encrypt(secret_data, plaintext_data, nonce, key)
143 return nonce, encrypted
146def aead_decrypt(key: bytes, nonce: bytes, encrypted_secret_data: bytes, plaintext_data: bytes = b"") -> bytes:
147 return crypto_aead.crypto_aead_xchacha20poly1305_ietf_decrypt(encrypted_secret_data, plaintext_data, nonce, key)
150def simple_encrypt(key_name: str, data: bytes) -> bytes:
151 key = get_secret(key_name)
152 nonce, data = aead_encrypt(key, data)
153 return nonce + data
156def simple_decrypt(key_name: str, data: bytes) -> bytes:
157 key = get_secret(key_name)
158 nonce, data = data[:_aead_nonce_len], data[_aead_nonce_len:]
159 return aead_decrypt(key, nonce, data)
162def encrypt_page_token(plaintext_page_token: str):
163 return b64encode(simple_encrypt(PAGE_TOKEN_KEY_NAME, plaintext_page_token.encode("utf8")))
166def decrypt_page_token(encrypted_page_token: str):
167 return simple_decrypt(PAGE_TOKEN_KEY_NAME, b64decode(encrypted_page_token)).decode("utf8")
170# Public key cryptography
173def asym_encrypt(public_key: bytes, data: bytes) -> bytes:
174 return SealedBox(PublicKey(public_key)).encrypt(data)
177def asym_decrypt(private_key: bytes, encrypted_data: bytes) -> bytes:
178 return SealedBox(PrivateKey(private_key)).decrypt(encrypted_data)
181def generate_asym_keypair():
182 skey = PrivateKey.generate()
183 return skey.encode(), skey.public_key.encode()