1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 # OpenSSL exception added in commit 22711f81f4e79da6b796820e37803a05cae14645
4 # (README: add OpenSSL exception, 2015-10-05)
6 # Replaces most uses of Digest::SHA with OpenSSL via Net::SSLeay if
7 # possible. OpenSSL SHA-256 is nearly twice as fast as Digest::SHA on
8 # x86-64, and SHA-1 is a bit faster as well.
9 # I don't think we can implement Digest::SHA->clone with what Net::SSLeay
10 # gives us... (maybe EVP_MD_CTX_copy+EVP_MD_CTX_copy_ex need to be added
12 package PublicInbox::SHA;
15 our @EXPORT_OK = qw(sha1_hex sha256_hex sha256);
19 push @ISA, 'Exporter';
20 unless (eval(<<'EOM')) {
23 1 => Net::SSLeay::EVP_get_digestbyname('sha1'),
24 256 => Net::SSLeay::EVP_get_digestbyname('sha256'),
29 my $mdctx = Net::SSLeay::EVP_MD_CTX_create();
30 Net::SSLeay::EVP_DigestInit($mdctx, $SHA{$n}) or
31 die "EVP_DigestInit $n: $!";
37 Net::SSLeay::EVP_DigestUpdate($$self, $_) for @_;
41 sub digest { Net::SSLeay::EVP_DigestFinal(${$_[0]}) };
42 sub hexdigest { unpack('H*', Net::SSLeay::EVP_DigestFinal(${$_[0]})) }
43 sub DESTROY { Net::SSLeay::EVP_MD_CTX_destroy(${$_[0]}) };
45 sub sha1_hex { unpack('H*', Net::SSLeay::SHA1($_[0])) };
46 sub sha256_hex { unpack('H*', Net::SSLeay::SHA256($_[0])) };
47 *sha256 = \&Net::SSLeay::SHA256;
50 require Digest::SHA; # stdlib fallback
51 push @ISA, 'Digest::SHA';
52 *sha1_hex = \&Digest::SHA::sha1_hex;
53 *sha256_hex = \&Digest::SHA::sha256_hex;
54 *sha256 = \&Digest::SHA::sha256;