hash_utils.py 857 B

123456789101112131415161718192021222324252627282930
  1. # Copyright (c) Opendatalab. All rights reserved.
  2. import hashlib
  3. import json
  4. def bytes_md5(file_bytes):
  5. hasher = hashlib.md5()
  6. hasher.update(file_bytes)
  7. return hasher.hexdigest().upper()
  8. def str_md5(input_string):
  9. hasher = hashlib.md5()
  10. # 在Python3中,需要将字符串转化为字节对象才能被哈希函数处理
  11. input_bytes = input_string.encode('utf-8')
  12. hasher.update(input_bytes)
  13. return hasher.hexdigest()
  14. def str_sha256(input_string):
  15. hasher = hashlib.sha256()
  16. # 在Python3中,需要将字符串转化为字节对象才能被哈希函数处理
  17. input_bytes = input_string.encode('utf-8')
  18. hasher.update(input_bytes)
  19. return hasher.hexdigest()
  20. def dict_md5(d):
  21. json_str = json.dumps(d, sort_keys=True, ensure_ascii=False)
  22. return hashlib.md5(json_str.encode('utf-8')).hexdigest()