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