Sha256 Hashes in Ada

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

Our example demonstrates how to compute SHA256 hashes in Ada. 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.

with Ada.Text_IO;
with GNAT.SHA256;

procedure SHA256_Hashes is
   use Ada.Text_IO;
   use GNAT.SHA256;

   Input : constant String := "sha256 this string";
   Digest : Message_Digest;
begin
   -- Initialize the hash
   Reset(Digest);

   -- Update the hash with the input string
   Update(Digest, Input);

   -- Finalize the hash
   Digest := Digest_Value(Digest);

   -- Print the original string and its hash
   Put_Line(Input);
   Put_Line(Digest_To_String(Digest));
end SHA256_Hashes;

Ada implements several hash functions in various cryptographic libraries. In this example, we’re using the GNAT.SHA256 package, which is part of the GNAT compiler’s standard library.

We start by creating a new hash context using Reset. Then, we update the hash with our input string using Update. Finally, we finalize the hash and get the digest value with Digest_Value.

The Digest_To_String function is used to convert the binary digest to a human-readable hexadecimal string.

To run the program, save it as sha256_hashes.adb and use the GNAT compiler:

$ gnatmake sha256_hashes.adb
$ ./sha256_hashes
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 the GNAT.SHA512 package instead.

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