Checking a Password

Top Japanese page




Overview

This script compares an encrypted password and a plain text, and returns a result as true or false.

Flow

  1. Check a plain text and encrypted text with the crypt function
  2. Return the result

A sample code

 if (&checkcrypt($plain_pwd,$enc_pwd)){
     print "Password matched.";
 } else {
     print "Password did not match.";
 }
 
 sub checkcrypt {
     my ($pwd,$encpwd)=@_;
     return(crypt($pwd,$encpwd) eq "$encpwd");
 }

Description of the code

 if (&checkcrypt($plain_pwd,$enc_pwd)){
     print "Password matched.";
 } else {
     print "Password did not match.";
 }

$plain_pwd contains a plain text word passed from a input form. $enc_pwd is an encrypted password stored in a password file. Sends both values into the checkcrypt routine. The checkcrypt routine returns 1 if matches and 0 if does not match.

 sub checkcrypt {
     my ($pwd,$encpwd)=@_;
     return(crypt($pwd,$encpwd) eq "$encpwd");
 }

This encrypt the text in $pwd with the salt value contained in $encpwd. When the result of it is equal to the contents of $encpwd, return 1. If not return 0. The crypt function detect the salut value in the second argument automatically. Do not need to separate first two character of the $encpwd. This works even though the salt value is the one starting from $1$.