Commit | Line | Data |
6bc89f92 |
1 | # Test against SHA-1 Sample Vectors from NIST |
2 | # |
3 | # ref: http://csrc.nist.gov/cryptval/shs.html |
4 | # |
5 | # Uses files "nist/bit-messages.sha1" and "nist/bit-hashes.sha1" |
6 | |
7 | use Test; |
8 | use strict; |
9 | use integer; |
10 | |
11 | use File::Basename qw(dirname); |
12 | use File::Spec; |
13 | use Digest::SHA; |
14 | |
41c686de |
15 | BEGIN { |
77d2a621 |
16 | if ($ENV{PERL_CORE}) { |
17 | chdir 't' if -d 't'; |
18 | @INC = '../lib'; |
19 | } |
41c686de |
20 | } |
21 | |
6bc89f92 |
22 | my @hashes; |
23 | |
24 | BEGIN { |
77d2a621 |
25 | my $file = File::Spec->catfile(dirname($0), "nist", "bit-hashes.sha1"); |
cccd5831 |
26 | open(my $fh, q{<}, $file); |
27 | while (<$fh>) { |
6bc89f92 |
28 | next unless (/^[0-9A-F]/); |
29 | s/[\r\n]+$//; |
30 | if (/\^$/) { |
31 | s/\s*\^$//; |
32 | push(@hashes, $_); |
33 | } |
34 | } |
cccd5831 |
35 | close($fh); |
6bc89f92 |
36 | plan tests => scalar(@hashes); |
37 | } |
38 | |
39 | sub doType3 { |
40 | my $hash; |
41 | my $str = pack("B*", shift); |
42 | my $ctx = Digest::SHA->new(1); |
43 | for (my $j = 0; $j <= 99; $j++) { |
44 | for (my $i = 1; $i <= 50000; $i++) { |
45 | $str .= chr(0x00) x (int($j/4)+3); |
46 | $str .= pack("N", $i); |
47 | $str = $ctx->add($str)->digest; |
48 | } |
49 | ok(uc(unpack("H*", $str)), $hash = shift(@hashes)); |
50 | } |
51 | } |
52 | |
53 | my @msgs; |
54 | my @cnts; |
55 | my $bitstr; |
56 | my $bitval; |
57 | my $line; |
58 | my $hash; |
59 | my $type3 = 0; |
60 | my $ctx = Digest::SHA->new(1); |
61 | |
77d2a621 |
62 | my $file = File::Spec->catfile(dirname($0), "nist", "bit-messages.sha1"); |
cccd5831 |
63 | open(my $fh, q{<}, $file); |
64 | while (<$fh>) { |
6bc89f92 |
65 | $type3 = 1 if (/Type 3/); |
66 | $type3 = 0 if (/^<D/); |
67 | next unless (/^[0-9^ ]/); |
68 | s/[\r\n]+$//; |
69 | $line .= $_; |
70 | if (/\^$/) { |
71 | $line =~ s/\s*\^$//; |
72 | @cnts = split(/\s+/, $line); |
73 | $bitstr = ""; |
74 | $bitval = $cnts[1]; |
75 | for (my $i = 0; $i < $cnts[0]; $i++) { |
76 | $bitstr .= $bitval x $cnts[$i+2]; |
77 | $bitval = $bitval eq "1" ? "0" : "1"; |
78 | } |
79 | ok( |
80 | uc($ctx->add_bits($bitstr)->hexdigest), |
81 | $hash = shift(@hashes) |
82 | ) unless $type3; |
83 | doType3($bitstr) if ($type3); |
84 | $line = ""; |
85 | } |
86 | } |
cccd5831 |
87 | close($fh); |