Checking an admin password

Top Japanese page




Overview

Read a administrator's password file and verify with the plain text.

Flow

  1. Read admin password file
  2. Compare the plain text and encrypted text
  3. Retun result

A sample code

 my $adminpwd = 'adminpwd.dat';
 
 if (&checkadmin($plain_pwd)){
     print "Password matched.";
 } else {
     print "Password did not match.";
 }
 
 sub checkadmin {
  my $pwd = shift;
  
  if (open(FILE,"< $adminpwd")){
    my $filepwd = <FILE>;
    close(FILE);
    my $inpwd = crypt($pwd,$filepwd);
    return ("$inpwd" eq "$filepwd");
  } else {
    print 'Cannot open the password file.';
    exit;
  }
 }

Description of the code

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

$plain_pwd is the password passed from input form. It is given to the checkadmin function and the checkadmin verifies the plain text with the encrypted text and if they match, return 1, if not return 0.

 sub checkadmin {
  my $pwd = shift;
  
  if (open(FILE,"< $adminpwd")){
    my $filepwd = <FILE>;
    close(FILE);
    my $inpwd = crypt($pwd,$filepwd);
    return ("$inpwd" eq "$filepwd");
  } else {
    print 'Cannot open the password file.';
    exit;
  }
 }

Open the admin password file and put the contents into a variable. And put the plain text passed from parent function into a variable too. Encrypt the plain text using the salt value of the admin password which is already generated. If the encrypted text is equal to the original admin password, return 1. If not return 0. The crypt function automatically detect salt value from the second argument. It does not need to extract the salt part from the original encrypted text. If the admin password file does not exist, terminate the script with a message.