# Password handling.
#
# Copyright (C) 1999 Ian Jackson <ijackson@chiark.greenend.org.uk>
#
# This is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2,
# or (at your option) any later version.
#
# This is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public
# License along with this file; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

use MD5;

sub check_password () {
    my ($pw);
    $password= $in{'pw'};
    length $password or finish_error('nopassword');
    defined $ent or die;

    open P,"pwkeys" or die $!;
    for (;;) {
	$_= <P>; die $! unless length; chomp;
	finish_error('badpassword') if m/^end$/;
	$pw= calc_password($_,$id);
	last if lc $pw eq lc $password
    }
    close P;
}

sub calc_password ($$) {
    my ($keyhex,$id) = @_;
    # keys are hex-encoded octet strings; ids are just ASCII strings
    my ($key);

    $keyhex =~ m/^[0-9a-f]+$/ or die "$keyhex ?";
    $key= pack('H*',$keyhex);
    $digest= MD5->hash("BCP5Registry password 1 $id ".$key);
    return unpack('H20',$digest);
}

sub make_password ($) {
    my ($keyhex,$pw);

    open P,"pwkeys" or die $!;
    $keyhex= <P>; $keyhex =~ s/\n$// or die $!;
    $pw= calc_password($keyhex,$id);
    close P;
    return $pw;
}

sub send_password ($) {
    $password= make_password($id);
    process_file('notice.txt');
    open SM, "| /usr/sbin/sendmail -odb -oi -oee -f $nullemail -t" or die $!;
    print SM $out or die $!;
    close SM; $? and die $?;
}

1;
