Sha256 Hashes in Python

Here’s the translation of the SHA256 Hashes example from Go to Python, formatted in Markdown suitable for Hugo:

Python provides built-in modules for various cryptographic hash functions, including SHA256. Here’s how to compute SHA256 hashes in Python.

import hashlib

def main():
    s = "sha256 this string"

    # Create a new hash object
    h = hashlib.sha256()

    # Update the hash object with the bytes of the string
    h.update(s.encode('utf-8'))

    # Get the hexadecimal representation of the hash
    bs = h.hexdigest()

    print(s)
    print(bs)

if __name__ == "__main__":
    main()

In this example, we use the hashlib module, which provides a common interface to many different secure hash and message digest algorithms.

  1. We start by creating a new hash object using hashlib.sha256().

  2. We then use the update() method to feed the data to the hash object. The update() method expects bytes, so we encode our string to UTF-8 bytes using s.encode('utf-8').

  3. Finally, we use the hexdigest() method to get the hexadecimal representation of the hash.

Running the program computes the hash and prints it in a human-readable hex format:

$ python sha256_hashes.py
sha256 this string
1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a...

You can compute other hashes using a similar pattern. For example, to compute SHA512 hashes, you would use hashlib.sha512() instead.

Note that if you need cryptographically secure hashes, you should carefully research hash strength!