md5.pm revision 1.16
1# ex:ts=8 sw=4:
2# $OpenBSD: md5.pm,v 1.16 2014/01/31 15:48:44 espie Exp $
3#
4# Copyright (c) 2003-2007 Marc Espie <espie@openbsd.org>
5#
6# Permission to use, copy, modify, and distribute this software for any
7# purpose with or without fee is hereby granted, provided that the above
8# copyright notice and this permission notice appear in all copies.
9#
10# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
18use strict;
19use warnings;
20
21package OpenBSD::digest;
22
23sub new
24{
25	my ($class, $filename) = @_;
26	$class = ref($class) || $class;
27	my $digest = $class->digest_file($filename);
28	bless \$digest, $class;
29}
30
31sub key
32{
33	my $self = shift;
34	return $$self;
35}
36
37sub write
38{
39	my ($self, $fh) = @_;
40	print $fh "\@", $self->keyword, " ", $self->stringize, "\n";
41}
42
43sub digest_file
44{
45	my ($self, $fname) = @_;
46	open(my $file, '<', $fname) or die "can't open $fname: $!";
47	my $digest = $self->digest_fh($file);
48	close($file) or die "problem closing $fname: $!";
49	return $digest;
50}
51
52
53sub digest_fh
54{
55	my ($self, $file) = @_;
56
57	my $d = $self->algo;
58
59	$d->addfile($file);
60	return $d->digest;
61}
62
63sub fromstring
64{
65	my ($class, $arg) = @_;
66	$class = ref($class) || $class;
67	my $d = $class->unstringize($arg);
68	bless \$d, $class;
69}
70
71sub equals
72{
73	my ($a, $b) = @_;
74	return ref($a) eq ref($b) && $$a eq $$b;
75}
76
77package OpenBSD::sha;
78our @ISA=(qw(OpenBSD::digest));
79
80use Digest::SHA;
81use MIME::Base64;
82
83sub algo
84{
85	my $self = shift;
86
87	return Digest::SHA->new(256);
88}
89
90sub stringize
91{
92	my $self = shift;
93
94	return encode_base64($$self, '');
95}
96
97sub unstringize
98{
99	my ($class, $arg) = @_;
100	if ($arg =~ /^[0-9a-f]{64}$/i) {
101		return pack('H*', $arg);
102	}
103	return decode_base64($arg);
104}
105
106sub keyword
107{
108	return "sha";
109}
110
1111;
112