Coverage for src/couchers/crypto.py: 96%

98 statements  

« prev     ^ index     » next       coverage.py v7.6.10, created at 2025-06-01 15:07 +0000

1import functools 

2import secrets 

3from base64 import urlsafe_b64decode, urlsafe_b64encode 

4from typing import Optional, Union 

5 

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 

14 

15from couchers.config import config 

16 

17 

18def b64encode(data: bytes) -> str: 

19 return urlsafe_b64encode(data).decode("ascii") 

20 

21 

22def b64decode(data: str) -> bytes: 

23 return urlsafe_b64decode(data) 

24 

25 

26def b64encode_unpadded(data: str) -> bytes: 

27 return b64encode(data).replace("=", "") 

28 

29 

30def b64decode_unpadded(data: bytes) -> str: 

31 return b64decode(data + b"===="[len(data) % 4 :]) 

32 

33 

34def _urlsafe_random_b64(length=32) -> str: 

35 return b64encode(random_bytes(length)) 

36 

37 

38def urlsafe_secure_token(): 

39 """ 

40 A cryptographically secure random token that can be put in a URL 

41 """ 

42 return _urlsafe_random_b64(32) 

43 

44 

45def cookiesafe_secure_token(): 

46 return random_hex(32) 

47 

48 

49def hash_password(password: str): 

50 return nacl.pwhash.str(password.encode("utf-8")) 

51 

52 

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 

59 

60 

61def random_hex(length=32): 

62 """ 

63 Length in binary 

64 """ 

65 return random_bytes(length).hex() 

66 

67 

68def secure_compare(val1, val2): 

69 return sodium_memcmp(val1, val2) 

70 

71 

72def generate_hash_signature(message: bytes, key: bytes) -> bytes: 

73 """ 

74 Computes a blake2b keyed hash for the message. 

75 

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) 

81 

82 

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))) 

89 

90 

91def verify_hash_signature(message: bytes, key: bytes, sig: bytes) -> bool: 

92 """ 

93 Verifies a hash signature generated with generate_hash_signature. 

94 

95 Returns true if the signature matches, otherwise false. 

96 """ 

97 return secure_compare(sig, generate_hash_signature(message, key)) 

98 

99 

100def generate_random_5digit_string(): 

101 """Return a random 5-digit string""" 

102 return f"{secrets.randbelow(100000):05d}" 

103 

104 

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) 

110 

111 

112def stable_secure_uniform(key: bytes, seed: bytes): 

113 random_bytes = generate_hash_signature(message=seed, key=key) 

114 assert len(random_bytes) > 7 

115 # taken from cpython 

116 rr = random_bytes[:7] 

117 # Number of bits in a float 

118 BPF = 53 

119 RECIP_BPF = 2**-BPF 

120 return (int.from_bytes(rr) >> 3) * RECIP_BPF 

121 

122 

123@functools.lru_cache 

124def get_secret(name: str): 

125 """ 

126 Derives a secret key from the root secret using a key derivation function 

127 """ 

128 return generate_hash_signature(name.encode("utf8"), config["SECRET"]) 

129 

130 

131UNSUBSCRIBE_KEY_NAME = "unsubscribe" 

132EMAIL_SOURCE_DATA_KEY_NAME = "email-source-data" 

133PAGE_TOKEN_KEY_NAME = "pagination" 

134USER_LOCATION_RANDOMIZATION_NAME = "user-location-randomization-v1" 

135 

136 

137# AEAD: Authenticated Encryption with Associated Data 

138 

139_aead_key_len = crypto_aead.crypto_aead_xchacha20poly1305_ietf_KEYBYTES 

140_aead_nonce_len = crypto_aead.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES 

141 

142 

143def aead_generate_nonce(): 

144 return random_bytes(_aead_nonce_len) 

145 

146 

147def aead_generate_key(): 

148 return random_bytes(_aead_key_len) 

149 

150 

151def aead_encrypt(key: bytes, secret_data: bytes, plaintext_data: bytes = b"", nonce: Optional[bytes] = None) -> bytes: 

152 if not nonce: 

153 nonce = aead_generate_nonce() 

154 encrypted = crypto_aead.crypto_aead_xchacha20poly1305_ietf_encrypt(secret_data, plaintext_data, nonce, key) 

155 return nonce, encrypted 

156 

157 

158def aead_decrypt(key: bytes, nonce: bytes, encrypted_secret_data: bytes, plaintext_data: bytes = b"") -> bytes: 

159 return crypto_aead.crypto_aead_xchacha20poly1305_ietf_decrypt(encrypted_secret_data, plaintext_data, nonce, key) 

160 

161 

162def simple_encrypt(key_name: str, data: bytes) -> bytes: 

163 key = get_secret(key_name) 

164 nonce, data = aead_encrypt(key, data) 

165 return nonce + data 

166 

167 

168def simple_decrypt(key_name: str, data: bytes) -> bytes: 

169 key = get_secret(key_name) 

170 nonce, data = data[:_aead_nonce_len], data[_aead_nonce_len:] 

171 return aead_decrypt(key, nonce, data) 

172 

173 

174def encrypt_page_token(plaintext_page_token: str): 

175 return b64encode(simple_encrypt(PAGE_TOKEN_KEY_NAME, plaintext_page_token.encode("utf8"))) 

176 

177 

178def decrypt_page_token(encrypted_page_token: str): 

179 return simple_decrypt(PAGE_TOKEN_KEY_NAME, b64decode(encrypted_page_token)).decode("utf8") 

180 

181 

182# Public key cryptography 

183 

184 

185def asym_encrypt(public_key: bytes, data: bytes) -> bytes: 

186 return SealedBox(PublicKey(public_key)).encrypt(data) 

187 

188 

189def asym_decrypt(private_key: bytes, encrypted_data: bytes) -> bytes: 

190 return SealedBox(PrivateKey(private_key)).decrypt(encrypted_data) 

191 

192 

193def generate_asym_keypair(): 

194 skey = PrivateKey.generate() 

195 return skey.encode(), skey.public_key.encode()