1use strict;
2use FileHandle;
3
4my $MODULE;
5
6BEGIN {
7	$MODULE = ($ENV{PERL_CORE} || -d "src") ? "Digest::SHA" : "Digest::SHA::PurePerl";
8	eval "require $MODULE" || die $@;
9	$MODULE->import(qw());
10}
11
12BEGIN {
13	if ($ENV{PERL_CORE}) {
14		chdir 't' if -d 't';
15		@INC = '../lib';
16	}
17}
18
19my @out = (
20	"ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0",
21	"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1",
22);
23
24my $numtests = 6 + scalar @out;
25print "1..$numtests\n";
26
27	# attempt to use an invalid algorithm, and check for failure
28
29my $testnum = 1;
30my $NSA = "SHA-42";	# No Such Algorithm
31print "not " if $MODULE->new($NSA);
32print "ok ", $testnum++, "\n";
33
34my $tempfile = "methods.tmp";
35END { 1 while unlink $tempfile }
36
37	# test OO methods using first two SHA-256 vectors from NIST
38
39my $fh = FileHandle->new($tempfile, "w");
40binmode($fh);
41print $fh "bcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq";
42$fh->close;
43
44my $sha = $MODULE->new()->reset("SHA-256")->new();
45$sha->add_bits("a", 5)->add_bits("001");
46
47my $rsp = shift(@out);
48print "not " unless $sha->clone->add("b", "c")->b64digest eq $rsp;
49print "ok ", $testnum++, "\n";
50
51$rsp = shift(@out);
52
53	# test addfile with bareword filehandle
54
55open(FILE, "<$tempfile");
56binmode(FILE);
57print "not " unless
58	$sha->clone->addfile(*FILE)->hexdigest eq $rsp;
59print "ok ", $testnum++, "\n";
60close(FILE);
61
62	# test addfile with indirect filehandle
63
64$fh = FileHandle->new($tempfile, "r");
65binmode($fh);
66print "not " unless $sha->clone->addfile($fh)->hexdigest eq $rsp;
67print "ok ", $testnum++, "\n";
68$fh->close;
69
70	# test addfile using file name instead of handle
71
72print "not " unless $sha->addfile($tempfile, "b")->hexdigest eq $rsp;
73print "ok ", $testnum++, "\n";
74
75	# test addfile portable mode
76
77$fh = FileHandle->new($tempfile, "w");
78binmode($fh);
79print $fh "abc\012" x 2048;		# using UNIX newline
80$fh->close;
81
82print "not " unless $sha->new(1)->addfile($tempfile, "p")->hexdigest eq
83	"d449e19c1b0b0c191294c8dc9fa2e4a6ff77fc51";
84print "ok ", $testnum++, "\n";
85
86$fh = FileHandle->new($tempfile, "w");
87binmode($fh);
88print $fh "abc\015\012" x 2048;		# using DOS/Windows newline
89$fh->close;
90
91print "not " unless $sha->new(1)->addfile($tempfile, "p")->hexdigest eq
92	"d449e19c1b0b0c191294c8dc9fa2e4a6ff77fc51";
93print "ok ", $testnum++, "\n";
94
95$fh = FileHandle->new($tempfile, "w");
96binmode($fh);
97print $fh "abc\015" x 2048;		# using early-Mac newline
98$fh->close;
99
100print "not " unless $sha->new(1)->addfile($tempfile, "p")->hexdigest eq
101	"d449e19c1b0b0c191294c8dc9fa2e4a6ff77fc51";
102print "ok ", $testnum++, "\n";
103