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#.
open System
open System.Security.Cryptography
open System.Text
let computeSHA256 (input: string) =
use sha256 = SHA256.Create()
let inputBytes = Encoding.UTF8.GetBytes(input)
let hashBytes = sha256.ComputeHash(inputBytes)
BitConverter.ToString(hashBytes).Replace("-", "").ToLower()
[<EntryPoint>]
let main argv =
let s = "sha256 this string"
let hash = computeSHA256 s
printfn "%s" s
printfn "%s" hash
0
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.
$ dotnet run
sha256 this string
1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a...
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!