Coverage for muutils\misc\hashing.py: 56%
16 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-10-15 20:56 -0600
« prev ^ index » next coverage.py v7.6.1, created at 2024-10-15 20:56 -0600
1from __future__ import annotations
3import base64
4import hashlib
7def 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")
20def 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