package Passwords;
use strict;
use vars qw (@ISA @EXPORT_OK);
use Exporter;
@ISA = ('Exporter');
@EXPORT_OK = qw( GetUserIDFromShell GetPasswordFromShell Seed GetRandomSalt
		EncryptString VerifyClearPassword );

# Author   : jces
# Modified : Gavin Sherlock
# Date     : October 1999

# This package contains utilities for encrypting passwords.

use Carp;

############################################################################
sub GetUserIDFromShell{
############################################################################

    my( $word );
    
    print "UserID: ";
    chomp ($word = <STDIN>);
    
    return( $word );
}

#############################################################################
sub GetPasswordFromShell{
#############################################################################

    my $word;

    system "stty -echo";
    print "Password: ";
    chomp ($word = <STDIN>);
    print "\n";
    system "stty echo";

    return $word;
}

#############################################################################
sub Seed{
#############################################################################

    # stolen from http://channel.zdjournals.com/sun/s_sun/9809/sun9894.htm
    # Seed the random number generator. XOR the time with the process
    # ID with the checksum of the output of the vmstat -s command.
    
    srand (time ^ $$ ^ unpack "%32L*", `vmstat -s`);

}

#############################################################################
sub GetRandomSalt{
#############################################################################

    # stolen from http://channel.zdjournals.com/sun/s_sun/9809/sun9894.htm

    my( $random_num, $salt, $i );

    # Initialize @salt_chars to hold legal salt characters 
    my( @salt_chars ) = ('a'..'z','A'..'Z','0'..'9','.','/');

    $salt = "";

    for( $i = 0; $i < 2; $i++ ) {

	$random_num = int( rand( $#salt_chars + 1 ) );
	$salt .= $salt_chars[$random_num];

    }
    
    return $salt;

}

############################################################################
sub EncryptString{
############################################################################

    my $str = shift;
    my $enc;
    my $salt;

    $salt = GetRandomSalt();
    $enc = crypt( $str, $salt );
    
    return $enc;

}

############################################################################
sub VerifyClearPassword{
############################################################################
# $try is clear text to check.
# $pwd is the real thing,
#  e.g.: from /etc/passwd,
#  2 salt characters + encrypted text.

    my $try = shift;
    my $pwd = shift;
    
    my $okP;
    my $salt;
    my $encodedTry;
    
    $salt = substr( $pwd, 0, 2 );
    $encodedTry = crypt( $try, $salt );
    
    # NB crypt automatically prepends the
    # salt for future reference.
    
    return ($encodedTry eq $pwd);

}

1;
