_compat.py 1.1 KB

1234567891011121314151617181920212223242526
  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(data: bytes, *, usedforsecurity: bool = True) -> str: # pragma: no cover
  17. return hashlib.md5( # type: ignore[call-arg]
  18. data, usedforsecurity=usedforsecurity
  19. ).hexdigest()
  20. except TypeError: # pragma: no cover
  21. def md5_hexdigest(data: bytes, *, usedforsecurity: bool = True) -> str:
  22. return hashlib.md5(data).hexdigest()