Sha256 Hashes in F#
Here’s the translation of the SHA256 Hashes example from Go to F#:
Our first program demonstrates how to compute SHA256 hashes. SHA256 hashes are frequently used to compute short identities for binary or text blobs. For example, TLS/SSL certificates use SHA256 to compute a certificate’s signature. Here’s how to compute SHA256 hashes in F#.
F# implements several hash functions in the System.Security.Cryptography
namespace.
Here we define a function computeSHA256
that takes a string input and returns its SHA256 hash as a lowercase hexadecimal string.
Inside the computeSHA256
function:
- We create a new SHA256 hash object.
- We convert the input string to a byte array.
- We compute the hash of the byte array.
- We convert the resulting byte array to a hexadecimal string and format it.
In the main
function:
- We define a string to be hashed.
- We call our
computeSHA256
function to compute the hash. - We print the original string and its hash.
Running the program computes the hash and prints it in a human-readable hex format.
You can compute other hashes using a similar pattern to the one shown above. For example, to compute SHA512 hashes, you would use SHA512.Create()
instead of SHA256.Create()
.
Note that if you need cryptographically secure hashes, you should carefully research hash strength!