1. Perl
  2. builtin functions
  3. here

crypt function - create a digest to check passwords

You can use the crypt function to save the password as a digest. If you save the password in clear text, it will be seen. The first argument is the password. The second argument is an arbitrary string called salt, which makes it difficult to decipher the digest.

my $digest = crypt($passwd, $salt);

If you want to create a digest, Digest::MD5 or Digest is now better than the crypt function. It is recommended to use::SHA.

Example crypt function

This is an example using the crypt function.

use strict;
use warnings;

# Create a password
# Create two random characters consisting of [./0-9A-Za-z] as salt
print "(1) Create a digest from the password.\n";
my $passwd = 'secret';
my $salt = join''. ('.','/', 0 .. 9,'A' ..'Z','a' ..'z') [rand 64, rand 64];
             
my $digest = crypt($passwd, $salt);
print "$digest\n\n";


print "(2) Password verification.\n";
if (crypt($passwd, $digest) eq $digest) {
  print "Password matched.\n";
}

Create a digest from password

my $passwd = 'secret'; # create password
my $salt = join'', ('.','/', 0 .. 9,'A' ..'Z','a' ..'z') [rand 64, rand 64];
my $digest = crypt($passwd, $salt);

Use the crypt function to create a digest from the password. The crypt function is a one-way hash function. The string converted by the one-way hash is called a digest.

The digest created by the crypt function is very difficult to combine.

In the first argument of crypt, specify the string that will be the source of the digest. Only the first 8 bytes make sense. Characters longer than that are ignored.

For the second argument of crypt, specify 2 of the 64 characters of [./0-9A-Za-z]. The second and subsequent characters are ignored. If you choose 2 random characters from these 64 characters, the safety of the digest will be higher.

These two characters are the beginning of the created digest.

Password verification

if (crypt($passwd, $digest) eq $digest) {}

When collating the password, use the crypt function to recreate the digest. If the digest you created matches the digest you created earlier, you know that the password is correct.

Since the first two characters of the digest are the two characters specified by $salt, they can be used as they are for the second argument of the crypt function.

Related Informatrion