Sha256 Hashes in Perl

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

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

use strict;
use warnings;
use Digest::SHA qw(sha256_hex);

my $s = "sha256 this string";

# Create a new SHA256 hash object
my $sha = Digest::SHA->new(256);

# Add data to the hash object
$sha->add($s);

# Get the hexadecimal representation of the hash
my $hash = $sha->hexdigest;

print "$s\n";
print "$hash\n";

In this example, we use the Digest::SHA module, which provides an interface to the SHA family of hash algorithms.

We start by creating a new SHA256 hash object using Digest::SHA->new(256).

The add method is used to add data to the hash object. In this case, we’re adding the string $s.

Finally, we use the hexdigest method to get the finalized hash result as a hexadecimal string.

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

$ perl sha256_hashes.pl
sha256 this string
1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a...

You can compute other hashes using a similar pattern. For example, to compute SHA512 hashes, you can use Digest::SHA->new(512).

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