Last active
May 20, 2022 00:18
-
-
Save nmalkin/e287f71788c57fd71bd0a7eec9345add to your computer and use it in GitHub Desktop.
SHA-256 hash of a string in Python 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import hashlib | |
def hash_string(string): | |
""" | |
Return a SHA-256 hash of the given string | |
""" | |
return hashlib.sha256(string.encode('utf-8')).hexdigest() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@newtfrank You can truncate the hash value (take only a subset of the returned string and use that), but if you take too much of it out, it will negate the useful properties of the hash function. Here are a couple of StackExchange answers talking about when truncation is safe (and when it might not be): [1] [2]. Also take a look at this page for a bit of background on hash functions and the difference between them and encryption. Cheers!