Perl SHA-256 and HMAC with Digest::SHA
Digest::SHA is part of core Perl. sha256_hex returns the SHA-256 digest of a string as 64 hexadecimal characters. A cryptographic hash is deterministic and one-way, and any change to the input gives a completely different digest, so hashes are used to check integrity. Plain hashes are not suitable for storing passwords because they are fast to guess.
Perl
use strict;
use warnings;
use Digest::SHA qw(sha256_hex hmac_sha256_hex);
print sha256_hex("abc"), "\n";
print sha256_hex("abd"), "\n";
sub secure_equal {
my ($x, $y) = @_;
return 0 unless length($x) == length($y);
my $diff = 0;
$diff |= ord(substr($x, $_, 1)) ^ ord(substr($y, $_, 1)) for 0 .. length($x) - 1;
return $diff == 0;
}
my $message = "what do ya want for nothing?";
my $tag = hmac_sha256_hex($message, "Jefe");
print "$tag\n";
print "valid: ", (secure_equal($tag, hmac_sha256_hex($message, "Jefe")) ? "yes" : "no"), "\n";
print "forged: ", (secure_equal($tag, hmac_sha256_hex("what do ya want for something?", "Jefe")) ? "yes" : "no"), "\n";