From e1dd24d58f8e12e272f8025d2b62460c0ceb3157 Mon Sep 17 00:00:00 2001 From: "Kyle J. McKay" Date: Mon, 1 Mar 2021 18:16:40 -0700 Subject: [PATCH] Girocco/HashUtil.pm: take advantage of Digest::SHA::hmac_sha1 If Digest::SHA::hmac_sha1 can be imported, then use that as the hmac_sha1 implementation. It's approximately twice as fast (almost) as the included hmac_sha1 implementation. When using the Digest::SHA::hmac_sha1 implementation, double the maximum key rounds since that's approximately the same CPU cost. Clients of the HashUtil module automatically get whatever is implementing hmac_sha1 imported as hmac_sha1 and do not need to make any changes whatsoever. Signed-off-by: Kyle J. McKay --- Girocco/HashUtil.pm | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/Girocco/HashUtil.pm b/Girocco/HashUtil.pm index 5e5d0c5..a4a0375 100644 --- a/Girocco/HashUtil.pm +++ b/Girocco/HashUtil.pm @@ -1,5 +1,6 @@ # Girocco::HashUtil.pm -- HMAC SHA-1 Utility Functions -# Copyright (C) 2013,2020 Kyle J. McKay. All rights reserved. +# Copyright (C) 2013,2020,2021 Kyle J. McKay. +# All rights reserved. # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License @@ -30,12 +31,13 @@ BEGIN { } use MIME::Base64; +my $have_sha_hmac_sha1; BEGIN { eval { require Digest::SHA; Digest::SHA->import( - qw(sha1) - );1} || + qw(sha1 hmac_sha1) + );$have_sha_hmac_sha1=1;1} || eval { require Digest::SHA1; Digest::SHA1->import( @@ -88,7 +90,7 @@ sub _xor5C {use bytes; $_[0]=~tr # $_[1] -> key # To match other Perl Digest modules even though RFC 2104 # talks about the key and then the text in that order! -sub hmac_sha1 { +sub _hmac_sha1 { use bytes; my $text = shift || ''; my $key = shift || ''; @@ -123,6 +125,10 @@ sub hmac_sha1 { return sha1($data5); } +BEGIN { + $have_sha_hmac_sha1 or eval 'sub hmac_sha1 {goto &_hmac_sha1}'; +} + # An 8-byte salt is considered sufficient # We take the first 6 bytes of the sha1 hash of the rand output and pass # that through _encode_base64_alt to get a compatible 8-byte salt @@ -177,9 +183,11 @@ sub crypt_sha1 { # A convenience function similar to scrypt but producing a crypt_sha1 result. # Note that while 256 rounds is rather small, it's enough to allow some variation # in the number of rounds while still not taxing the CPU running Perl hmac_sha1. +# If we have the Digest::SHA::hmac_sha1 version, it's approximately twice as +# fast and we can allow up to 512 rounds for approximately the same CPU cost. sub scrypt_sha1 { my $pw = shift || ''; - return crypt_sha1($pw, '', 256); + return crypt_sha1($pw, '', $have_sha_hmac_sha1 ? 512 : 256); } 1; -- 2.11.4.GIT