1 from __future__ import annotations

2

3 import base64

4 import hashlib

5

6

7 def stable_hash(s: str | bytes) -> int:

8 """Returns a stable hash of the given string. not cryptographically secure, but stable between runs"""

9 # init hash object and update with string

10 s_bytes: bytes

11 if isinstance(s, str):

12 s_bytes = bytes(s, "UTF-8")

13 else:

14 s_bytes = s

15 hash_obj: hashlib._Hash = hashlib.sha256(s_bytes)

16 # get digest and convert to int

17 return int.from_bytes(hash_obj.digest(), "big")

18

19

20 def base64_hash(s: str | bytes) -> str:

21 """Returns a base64 representation of the hash of the given string. not cryptographically secure"""

22 s_bytes: bytes

23 if isinstance(s, str):

24 s_bytes = bytes(s, "UTF-8")

25 else:

26 s_bytes = s

27 hash_bytes: bytes = hashlib.sha256(s_bytes).digest()

28 hash_b64: str = base64.b64encode(hash_bytes, altchars=b"-_").decode()

29 return hash_b64