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

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_bytes(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_bytes(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 

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

118 

119 

120UNSUBSCRIBE_KEY_NAME = "unsubscribe" 

121EMAIL_SOURCE_DATA_KEY_NAME = "email-source-data" 

122PAGE_TOKEN_KEY_NAME = "pagination" 

123 

124 

125# AEAD: Authenticated Encryption with Associated Data 

126 

127_aead_key_len = crypto_aead.crypto_aead_xchacha20poly1305_ietf_KEYBYTES 

128_aead_nonce_len = crypto_aead.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES 

129 

130 

131def aead_generate_nonce(): 

132 return random_bytes(_aead_nonce_len) 

133 

134 

135def aead_generate_key(): 

136 return random_bytes(_aead_key_len) 

137 

138 

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 

144 

145 

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) 

148 

149 

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 

154 

155 

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) 

160 

161 

162def encrypt_page_token(plaintext_page_token: str): 

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

164 

165 

166def decrypt_page_token(encrypted_page_token: str): 

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

168 

169 

170# Public key cryptography 

171 

172 

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

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

175 

176 

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

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

179 

180 

181def generate_asym_keypair(): 

182 skey = PrivateKey.generate() 

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