Sha256 Hashes in Nim
Here’s the translation of the SHA256 Hashes example from Go to Nim, formatted in Markdown suitable for Hugo:
Our example demonstrates how to compute SHA256 hashes in Nim. 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.
import std/sha
proc main() =
let s = "sha256 this string"
# Here we start with a new hash.
var h = secureHash(s)
# Convert the hash to a string of hexadecimal digits
let bs = $h
echo s
echo bs
main()
Nim implements several hash functions in the std/sha
module.
To run the program, save it as sha256_hashes.nim
and use the Nim compiler:
$ nim c -r sha256_hashes.nim
sha256 this string
1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a0678c2836757fff
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 can use the secureHash512
function from the same std/sha
module.
Note that if you need cryptographically secure hashes, you should carefully research hash strength!
In Nim, the process of creating and using hash functions is more straightforward compared to some other languages. The secureHash
function directly returns the hash of the input string, eliminating the need for separate New()
, Write()
, and Sum()
calls. The resulting hash is then converted to a string of hexadecimal digits using the $
operator.