md5.pm revision 1.20
1# ex:ts=8 sw=4: 2# $OpenBSD: md5.pm,v 1.20 2023/06/13 09:07:17 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 v5.36; 19 20# XXX even though there is ONE current implementation of OpenBSD::digest 21# (SHA256) we keep the framework open in case we ever need to switch, 22# as we did in the past with md5 -> sha256 23package OpenBSD::digest; 24 25sub new($class, $filename) 26{ 27 $class = ref($class) || $class; 28 my $digest = $class->digest_file($filename); 29 bless \$digest, $class; 30} 31 32sub key($self) 33{ 34 return $$self; 35} 36 37sub write($self, $fh) 38{ 39 print $fh "\@", $self->keyword, " ", $self->stringize, "\n"; 40} 41 42sub digest_file($self, $fname) 43{ 44 my $d = $self->_algo; 45 eval { 46 $d->addfile($fname); 47 }; 48 if ($@) { 49 $@ =~ s/\sat.*//; 50 die "can't compute ", $self->keyword, " on $fname: $@"; 51 } 52 return $d->digest; 53} 54 55sub fromstring($class, $arg) 56{ 57 $class = ref($class) || $class; 58 my $d = $class->_unstringize($arg); 59 bless \$d, $class; 60} 61 62sub equals($a, $b) 63{ 64 return ref($a) eq ref($b) && $$a eq $$b; 65} 66 67package OpenBSD::sha; 68our @ISA=(qw(OpenBSD::digest)); 69 70use Digest::SHA; 71use MIME::Base64; 72 73sub _algo($self) 74{ 75 76 return Digest::SHA->new(256); 77} 78 79sub stringize($self) 80{ 81 return encode_base64($$self, ''); 82} 83 84sub _unstringize($class, $arg) 85{ 86 if ($arg =~ /^[0-9a-f]{64}$/i) { 87 return pack('H*', $arg); 88 } 89 return decode_base64($arg); 90} 91 92sub keyword($) 93{ 94 return "sha"; 95} 96 971; 98