How to get the SHA256 hash in Perl

Task. In Perl the code is variable. You need to calculate SHA256 hash of the value of this variable.

The decision

The solution is to use Perl library Digest::SHA. Library Digest::SHA comes with Perl, so if you have Perl, this library is available to additionally install nothing.

Get SHA256 hash, you can use this code:

▶ Run
#!/usr/bin/perl

use Digest::SHA qw(sha256_hex);

my $var = 123;

my $sha256_hash = sha256_hex($var);

print $sha256_hash;

This program displays the string 'a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3'.

  • use Digest::SHA qw(sha256_hex); — we connect Perl library and say that from this library we need a function sha256_hex
  • my $var = 123; — created a variable and put the value 123
  • my $sha256_hash = sha256_hex($var); — using functions sha256_hex we calculated the SHA256 hash of the value of the variable $var and put the result in a variable $sha256_hash
  • print $sha256_hash; — brought the value of the variable $sha256_hash on the screen

If the library does not indicate that we need a function sha256_hex, and just write use Digest::SHA;, when execution of the program will be error:

Undefined subroutine &main::sha256_hex called at script.pl line 7.

The format of the return value of a function sha256_hex

Function sha256_hex always returns a string. In this line, always exactly 64 characters. This line can be the numbers from 0 to 9 and Latin letters in lower case from 'a' to 'f'. Other symbols in this row can not be.

Function sha256_hex SHA256 returns a string which contains a number in hexadecimal notation.

Which versions of Perl library Digest::SHA available immediately

At the beginning of this text says that the library Digest::SHA comes with Perl if you have Perl, this library immediately available. Actually it is not so. Library Digest::SHA was first introduced in Perl version 5.10. So if you have Perl version 5.8 or lower, then this library should be put additionally. But even better to upgrade Perl to a more recent one. Perl 5.8 was released in 2002.

Other articles

Comments