Sha256 Hashes in Pascal

Here’s the translation of the SHA256 Hashes example from Go to Pascal, 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 Pascal.

program SHA256Hashes;

uses
  SysUtils, Hash;

var
  s: string;
  sha256: THashSHA2;
  digest: TBytes;
  i: Integer;

begin
  s := 'sha256 this string';

  // Create a new SHA256 hash object
  sha256 := THashSHA2.Create(SHA256);
  try
    // Update the hash with the input string
    sha256.Update(BytesOf(s));

    // Finalize the hash and get the result
    SetLength(digest, sha256.HashSize div 8);
    sha256.Final(digest);

    // Print the original string
    WriteLn(s);

    // Print the hash in hexadecimal format
    Write('Hash: ');
    for i := 0 to High(digest) do
      Write(IntToHex(digest[i], 2));
    WriteLn;
  finally
    sha256.Free;
  end;
end.

In this Pascal example, we use the Hash unit which provides cryptographic hash functions. The THashSHA2 class is used to compute the SHA256 hash.

  1. We start by creating a new THashSHA2 object with the SHA256 algorithm.
  2. We update the hash with our input string using the Update method. The BytesOf function converts the string to a byte array.
  3. We finalize the hash and get the result using the Final method.
  4. Finally, we print the original string and the computed hash in hexadecimal format.

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

$ fpc sha256_hashes.pas
$ ./sha256_hashes
sha256 this string
Hash: 1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a...

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

In Pascal, you can use other hash functions provided by the Hash unit, such as MD5, SHA1, or SHA512, by creating the appropriate hash object (e.g., THashMD5.Create for MD5).