Sha256 Hashes in Idris
Here’s the translation of the SHA256 hashes example to Idris, formatted in Markdown suitable for Hugo:
Our example demonstrates how to compute SHA256 hashes in Idris. 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.
module Main
import Data.Buffer
import Data.String
import Crypto.Hash.SHA256
main : IO ()
main = do
let s = "sha256 this string"
-- Convert the string to a buffer
let buf = fromString s
-- Compute the SHA256 hash
let hash = sha256 buf
-- Convert the hash to a hexadecimal string
let hexHash = toHexString hash
putStrLn s
putStrLn hexHash
In this example, we’re using the Crypto.Hash.SHA256
module, which provides the SHA256 hashing functionality.
We start by defining our input string s
. Then, we convert this string to a Buffer
using fromString
. The Buffer
type in Idris is similar to a byte array, which is what the SHA256 function expects.
Next, we compute the SHA256 hash using the sha256
function, which takes a Buffer
and returns the hash as another Buffer
.
Finally, we convert the resulting hash to a hexadecimal string representation using toHexString
, and print both the original string and the hash.
To run the program:
$ idris -o sha256-hashes sha256-hashes.idr
$ ./sha256-hashes
sha256 this string
1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a...
This computes the hash and prints it in a human-readable hex format.
Note that if you need cryptographically secure hashes, you should carefully research hash strength!
Idris provides cryptographic functions through various libraries. The exact implementation might differ based on the specific library you’re using. Always ensure you’re using up-to-date and secure cryptographic libraries for production code.