Skip to content

Instantly share code, notes, and snippets.

@nmalkin
Last active May 20, 2022 00:18
Show Gist options
  • Save nmalkin/e287f71788c57fd71bd0a7eec9345add to your computer and use it in GitHub Desktop.
Save nmalkin/e287f71788c57fd71bd0a7eec9345add to your computer and use it in GitHub Desktop.
SHA-256 hash of a string in Python 3
#!/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()
@mbuguanewton
Copy link

Hey, is there a way to reduce the number of hash values you get without affecting the encryption.

@nmalkin
Copy link
Author

nmalkin commented Aug 29, 2018

@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!

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