Perl 5 version 6.1 documentation

crypt

  • crypt PLAINTEXT,SALT

    Encrypts a string exactly like the crypt(3) function in the C library (assuming that you actually have a version there that has not been extirpated as a potential munition). This can prove useful for checking the password file for lousy passwords, amongst other things. Only the guys wearing white hats should do this.

    Note that crypt is intended to be a one-way function, much like breaking eggs to make an omelette. There is no (known) corresponding decrypt function. As a result, this function isn't all that useful for cryptography. (For that, see your nearby CPAN mirror.)

    When verifying an existing encrypted string you should use the encrypted text as the salt (like crypt($plain, $crypted) eq $crypted ). This allows your code to work with the standard crypt and with more exotic implementations. When choosing a new salt create a random two character string whose characters come from the set [./0-9A-Za-z] (like join '', ('.', '/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64] ).

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

    1. $pwd = (getpwuid($<))[1];
    2. system "stty -echo";
    3. print "Password: ";
    4. chomp($word = <STDIN>);
    5. print "\n";
    6. system "stty echo";
    7. if (crypt($word, $pwd) ne $pwd) {
    8. die "Sorry...\n";
    9. } else {
    10. print "ok\n";
    11. }

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

    The crypt function is unsuitable for encrypting large quantities of data, not least of all because you can't get the information back. Look at the by-module/Crypt and by-module/PGP directories on your favorite CPAN mirror for a slew of potentially useful modules.