Sha256 Hashes in D Programming Language

Here’s the translation of the SHA256 hashes example from Go to D Programming Language, formatted in Markdown suitable for Hugo:

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 D.

import std.stdio;
import std.digest.sha;

void main()
{
    string s = "sha256 this string";

    // Here we start with a new hash.
    auto hash = new SHA256Digest();

    // We can write bytes directly to the hash object.
    hash.put(cast(ubyte[])s);

    // This gets the finalized hash result as a byte array.
    ubyte[] result = hash.finish();

    writeln(s);
    writefln("%(%02x%)", result);
}

D implements several hash functions in the std.digest module.

Running the program computes the hash and prints it in a human-readable hex format.

$ rdmd sha256_hashes.d
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 can use SHA512Digest from the same std.digest.sha module.

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

In this D version:

  1. We import std.digest.sha which provides SHA hash functions.
  2. We create a SHA256Digest object instead of using a New() function.
  3. We use the put method to add data to the hash, which can accept a ubyte[] (unsigned byte array). We cast our string to this type.
  4. We use the finish() method to get the final hash value as a ubyte[].
  5. We use writefln with a special format string "%(%02x%)" to print each byte of the result as a two-digit hexadecimal number.

The overall structure and functionality remain the same as the original example, adapted to D’s syntax and standard library.