1use strict; 2use FileHandle; 3use Digest::SHA; 4 5my @out = ( 6 "ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0", 7 "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1", 8); 9 10my $numtests = 6 + scalar @out; 11print "1..$numtests\n"; 12 13 # attempt to use an invalid algorithm, and check for failure 14 15my $testnum = 1; 16my $NSA = "SHA-42"; # No Such Algorithm 17print "not " if Digest::SHA->new($NSA); 18print "ok ", $testnum++, "\n"; 19 20my $tempfile = "methods.tmp"; 21END { unlink $tempfile if $tempfile } 22 23 # test OO methods using first two SHA-256 vectors from NIST 24 25my $fh = FileHandle->new($tempfile, "w"); 26binmode($fh); 27print $fh "bcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"; 28$fh->close; 29 30my $sha = Digest::SHA->new()->reset("SHA-256")->new(); 31$sha->add_bits("a", 5)->add_bits("001"); 32 33my $rsp = shift(@out); 34print "not " unless $sha->clone->add("b", "c")->b64digest eq $rsp; 35print "ok ", $testnum++, "\n"; 36 37$rsp = shift(@out); 38 39 # test addfile with bareword filehandle 40 41open(FILE, "<$tempfile"); 42binmode(FILE); 43print "not " unless 44 $sha->clone->addfile(*FILE)->hexdigest eq $rsp; 45print "ok ", $testnum++, "\n"; 46close(FILE); 47 48 # test addfile with indirect filehandle 49 50$fh = FileHandle->new($tempfile, "r"); 51binmode($fh); 52print "not " unless $sha->clone->addfile($fh)->hexdigest eq $rsp; 53print "ok ", $testnum++, "\n"; 54$fh->close; 55 56 # test addfile using file name instead of handle 57 58print "not " unless $sha->addfile($tempfile, "b")->hexdigest eq $rsp; 59print "ok ", $testnum++, "\n"; 60 61 # test addfile "universal newlines" mode 62 63$fh = FileHandle->new($tempfile, "w"); 64binmode($fh); 65print $fh "MacOS\r" . "MSDOS\r\n" . "UNIX\n" . "Quirky\r\r\n"; 66$fh->close; 67 68my $d = $sha->new(1)->addfile($tempfile, "U")->hexdigest; 69if ($d eq "f4c6855783c737c7e224873c90e80a9df5c2bc97") { 70 print "ok ", $testnum++, "\n"; 71} 72elsif ($d eq "42335d4a517a5e31399e948e9d842bafd9194d8f") { 73 print "ok ", $testnum++, " # skip: flaky -T\n"; 74} 75else { 76 print "not ok ", $testnum++, "\n"; 77} 78 79 # test addfile BITS mode 80 81$fh = FileHandle->new($tempfile, "w"); 82print $fh "0100010"; # using NIST 7-bit test vector 83$fh->close; 84 85print "not " unless $sha->new(1)->addfile($tempfile, "0")->hexdigest eq 86 "04f31807151181ad0db278a1660526b0aeef64c2"; 87print "ok ", $testnum++, "\n"; 88 89$fh = FileHandle->new($tempfile, "w"); 90binmode($fh); 91print $fh map(chr, (0..127)); # this is actually NIST 2-bit test 92$fh->close; # vector "01" (other chars ignored) 93 94print "not " unless $sha->new(1)->addfile($tempfile, "0")->hexdigest eq 95 "ec6b39952e1a3ec3ab3507185cf756181c84bbe2"; 96print "ok ", $testnum++, "\n"; 97