Coverage for muutils/misc/hashing.py: 58%

19 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-04-04 03:33 -0600

1from __future__ import annotations 

2 

3import base64 

4import hashlib 

5import json 

6 

7 

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 = s.encode("utf-8") 

14 else: 

15 s_bytes = s 

16 hash_obj: hashlib._Hash = hashlib.md5(s_bytes) 

17 # get digest and convert to int 

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

19 

20 

21def stable_json_dumps(d) -> str: 

22 return json.dumps( 

23 d, 

24 sort_keys=True, 

25 indent=None, 

26 ) 

27 

28 

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

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

31 s_bytes: bytes 

32 if isinstance(s, str): 

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

34 else: 

35 s_bytes = s 

36 hash_bytes: bytes = hashlib.md5(s_bytes).digest() 

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

38 return hash_b64