_compat.py 1.1 KB

12345678910111213141516171819202122232425262728
  1. import hashlib
  2. # Compat wrapper to always include the `usedforsecurity=...` parameter,
  3. # which is only added from Python 3.9 onwards.
  4. # We use this flag to indicate that we use `md5` hashes only for non-security
  5. # cases (our ETag checksums).
  6. # If we don't indicate that we're using MD5 for non-security related reasons,
  7. # then attempting to use this function will raise an error when used
  8. # environments which enable a strict "FIPs mode".
  9. #
  10. # See issue: https://github.com/encode/starlette/issues/1365
  11. try:
  12. # check if the Python version supports the parameter
  13. # using usedforsecurity=False to avoid an exception on FIPS systems
  14. # that reject usedforsecurity=True
  15. hashlib.md5(b"data", usedforsecurity=False) # type: ignore[call-arg]
  16. def md5_hexdigest(
  17. data: bytes, *, usedforsecurity: bool = True
  18. ) -> str: # pragma: no cover
  19. return hashlib.md5( # type: ignore[call-arg]
  20. data, usedforsecurity=usedforsecurity
  21. ).hexdigest()
  22. except TypeError: # pragma: no cover
  23. def md5_hexdigest(data: bytes, *, usedforsecurity: bool = True) -> str:
  24. return hashlib.md5(data).hexdigest()