How to get a SHA1 hash in Perl

Task. In Perl the code is variable. You need to calculate the SHA1 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.

To obtain a SHA1 hash, you can use this code:

▶ Run
#!/usr/bin/perl

use Digest::SHA qw(sha1_hex);

my $var = 123;

my $sha1_hash = sha1_hex($var);

print $sha1_hash;

This program displays the string '40bd001563085fc35165329ea1ff5c5ecbdbbeef'.

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

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

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

The format of the return value of a function sha1_hex

Function sha1_hex always returns a string. This string is always exactly 40 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 sha1_hex SHA1 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