2

I am trying to find out how to use Crypt function to verify stored hashed password with user's entered data.

I use below code to generate password's digest using randomly generated salt. In next step, I use previously generated digest to be used as salt for crypt function and user's input. Based on information in this link, if the output of the crypt function is the same as our previously generated digest, then we are good to go.

The crypt function in CheckThis function, generates different output using previously generated digest, and this causes the problem. What am I not doing correctly?

Here's my code:

use strict;
use warnings;

sub HashThis {
    # To generate random salt
    my @temp = (0..9, 'A'..'Z', 'a'..'z');
    my $salt;
    $salt .= $temp[rand @temp] for 1..16;
    print "\nSalt is:\t\t",$salt,"\n";

    # makes digest for real password using salt
    my $digest = crypt(@_, '$6$'.$salt);

    return ($digest);
}

sub CheckThis {
    # compares if crypt return same digest as using digest as salt for userinput
    my $result;
    my ($ui, $digest) = @_;

    if (crypt($ui, $digest) eq $digest) {
        $result = "matching";
    } else {
        $result = "not matching";
    }    
    return ($result);
}

system "stty -echo";
print "\nReal password:\t\t ";
chomp(my $userpass = <STDIN>);
print "\n";
system "stty echo";

my $digest = HashThis($userpass);
print "\nDigest is:\t\t",$digest,"\n";

system "stty -echo";
print "\nTest password:\t\t ";
chomp(my $userinput = <STDIN>);
print "\n";
system "stty echo";

my $final_result = CheckThis($userinput, $digest);
print "\n",$final_result,"\n\n";
toolic
  • 57,801
  • 17
  • 75
  • 117
shahesam84
  • 33
  • 6

1 Answers1

3

Change:

my $digest = crypt(@_, '$6$'.$salt);

to:

my $digest = crypt($_[0], '$6$'.$salt);

My guess is that crypt expects to be passed 2 scalar values, and it evaluates the @_ array variable in scalar context, which is 1 since you pass a single value to the HashThis sub.

toolic
  • 57,801
  • 17
  • 75
  • 117