[Chapter 3] 3.2.22 crypt
Author: Larry Wall, Tom Christiansen & Randal L. Schwartz
Date: 1999-07-02T01:48:13Z

#

| Chapter 3 Functions |

### 3.2.22 crypt

    crypt PLAINTEXT, SALT

This function encrypts a string exactly in the manner of crypt(3). This is useful for checking the password file for lousy passwords.[2] Only the guys wearing white hats are allowed to do this.

> [2] What you really want to do is prevent people from adding the bad passwords in the first place.

To see whether a typed-in password `$guess` matches the password `$pass` obtained from a file (such as /etc/passwd), try something like the following:

    if (crypt($guess, $pass) eq $pass) {
        # guess is correct
    }

Note that there is no easy way to decrypt an encrypted password apart from guessing. Also, truncating the salt to two characters is a waste of CPU time, although the manpage for crypt(3) would have you believe otherwise.

Here's an example that makes sure that whoever runs this program knows their own password:

    $pwd = (getpwuid ($<))[1];
    $salt = substr $pwd, 0, 2;

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

    if (crypt($word, $salt) ne $pwd) {
        die "Sorry...\n";
    } else {
        print "ok\n";
    }

Of course, typing in your own password to whoever asks for it is unwise.

The crypt function is unsuitable for encrypting large quantities of data. Find a library module for PGP (or something like that) for something like that.

3.2.21 cos |  | 3.2.23 dbmclose