1"""
2Plain's standard crypto functions and utilities.
3"""
4
5import hashlib
6import hmac
7import secrets
8from collections.abc import Callable
9from typing import Any
10
11from plain.runtime import settings
12from plain.utils.encoding import force_bytes
13
14
15class InvalidAlgorithm(ValueError):
16 """Algorithm is not supported by hashlib."""
17
18
19def salted_hmac(
20 key_salt: str | bytes,
21 value: str | bytes,
22 secret: str | bytes | None = None,
23 *,
24 algorithm: str = "sha1",
25) -> hmac.HMAC:
26 """
27 Return the HMAC of 'value', using a key generated from key_salt and a
28 secret (which defaults to settings.SECRET_KEY). Default algorithm is SHA1,
29 but any algorithm name supported by hashlib can be passed.
30
31 A different key_salt should be passed in for every application of HMAC.
32 """
33 if secret is None:
34 secret = settings.SECRET_KEY
35
36 key_salt = force_bytes(key_salt)
37 secret = force_bytes(secret)
38 try:
39 hasher = getattr(hashlib, algorithm)
40 except AttributeError as e:
41 raise InvalidAlgorithm(
42 f"{algorithm!r} is not an algorithm accepted by the hashlib module."
43 ) from e
44 # We need to generate a derived key from our base key. We can do this by
45 # passing the key_salt and our base key through a pseudo-random function.
46 key = hasher(key_salt + secret).digest()
47 # If len(key_salt + secret) > block size of the hash algorithm, the above
48 # line is redundant and could be replaced by key = key_salt + secret, since
49 # the hmac module does the same thing for keys longer than the block size.
50 # However, we need to ensure that we *always* do this.
51 return hmac.new(key, msg=force_bytes(value), digestmod=hasher)
52
53
54RANDOM_STRING_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
55
56
57def get_random_string(length: int, allowed_chars: str = RANDOM_STRING_CHARS) -> str:
58 """
59 Return a securely generated random string.
60
61 The bit length of the returned value can be calculated with the formula:
62 log_2(len(allowed_chars)^length)
63
64 For example, with default `allowed_chars` (26+26+10), this gives:
65 * length: 12, bit length =~ 71 bits
66 * length: 22, bit length =~ 131 bits
67 """
68 return "".join(secrets.choice(allowed_chars) for i in range(length))
69
70
71def pbkdf2(
72 password: str | bytes,
73 salt: str | bytes,
74 iterations: int,
75 dklen: int = 0,
76 digest: Callable[[], Any] | None = None,
77) -> bytes:
78 """Return the hash of password using pbkdf2."""
79 if digest is None:
80 digest = hashlib.sha256
81 dklen_value: int | None = dklen if dklen else None
82 password = force_bytes(password)
83 salt = force_bytes(salt)
84 return hashlib.pbkdf2_hmac(digest().name, password, salt, iterations, dklen_value)