docs for muutils v0.6.20
View Source on GitHub

muutils.misc.hashing


 1from __future__ import annotations
 2
 3import base64
 4import hashlib
 5
 6
 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")
18
19
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

def stable_hash(s: str | bytes) -> int:
 8def stable_hash(s: str | bytes) -> int:
 9    """Returns a stable hash of the given string. not cryptographically secure, but stable between runs"""
10    # init hash object and update with string
11    s_bytes: bytes
12    if isinstance(s, str):
13        s_bytes = bytes(s, "UTF-8")
14    else:
15        s_bytes = s
16    hash_obj: hashlib._Hash = hashlib.sha256(s_bytes)
17    # get digest and convert to int
18    return int.from_bytes(hash_obj.digest(), "big")

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

def base64_hash(s: str | bytes) -> str:
21def base64_hash(s: str | bytes) -> str:
22    """Returns a base64 representation of the hash of the given string. not cryptographically secure"""
23    s_bytes: bytes
24    if isinstance(s, str):
25        s_bytes = bytes(s, "UTF-8")
26    else:
27        s_bytes = s
28    hash_bytes: bytes = hashlib.sha256(s_bytes).digest()
29    hash_b64: str = base64.b64encode(hash_bytes, altchars=b"-_").decode()
30    return hash_b64

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