Skip to content

Instantly share code, notes, and snippets.

@devvspaces
Created August 25, 2022 01:07
Show Gist options
  • Save devvspaces/469ff5d5efa641f44ffc04fd365a8679 to your computer and use it in GitHub Desktop.
Save devvspaces/469ff5d5efa641f44ffc04fd365a8679 to your computer and use it in GitHub Desktop.
Creating keyed sha1 hashes and comparing them in time constant
import hashlib
import hmac
def compare_digest(a, b):
"""Compare hashes in constant time."""
return hmac.compare_digest(a, b)
def sha1_hash(message: str, key: str):
"""Creates a keyed hash for a message using the SHA1 algorithm."""
return hmac.new(
key.encode(), message.encode(), hashlib.sha1
).hexdigest()
@devvspaces
Copy link
Author

For other hashing algorithms just change hashlib.sha1 to hashlib.ALGORITHM, other algorithms are sha256, sha512 and more. Check out python hashlib docs for more algorithms you can use.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment