Perl crypt() function
Jetpak is Public
Created By: jingliu
Last Modified: 05/09/06

Perl crypt() function

The crypt() function is a built-in Perl routine for DES encryption. DES is the standard 56-bit unix encryption. It is used, for instance in /etc/passwd /etc/shadow files and as default encryption in .htaccess files.
The crypt() function takes two arguments and returns a string.

$encrypted_string = crypt("string","salt");


A quick sample script to take a string from the user or STDIN and encrypt it:

#!/usr/bin/perl

print "Enter a string to encrypt with DES:n";
chomp(my $string = ); #Take the input from the user and remove the n

print "Enter two random alphanumerics to be used as a salt:n";
chomp(my $salt = );

my $encrypted_string = crypt($string,$salt); #take the string and the salt and put through crypt()

print qq~
"$string" encrypted using the perl crypt() function and salt "$salt" returns:
$encrypted_string
~;



When a string is encrypted using DES, the salt is stored in the encrypted string in the first two letters. For example if we encrypt the string "badpassword" with the salt "a3 " the string returned by crypt() is a3 bL.vfoZZTk6

The crypt function will take the previously encrypted string and use the first two letters as the salt. This allows for easy comparison with previously encrypted strings.

An example here requests a password from the user and compares it to a DES password hard-coded into the script:

#!/usr/bin/perl

my $encrypted_password = "a3bL.vfoZZTk6"; # "badpassword"

print "Please enter the password:n";
chomp(my $input = );

if (crypt($input,$encrypted_password) eq $encrypted_password) {
    print "Correct password!n";
}
else {
    print "Access Deniedn";
}


if (crypt($input,$encrypted_password) eq $encrypted_password) {
This is the important line in this example, the $input string is taken from the user and encrypted with the salt stored in $encrypted_password and then compared to the $encrypted_password DES string.

Whenever you are handling and storing passwords in any enviroment, no matter who is using it, its always worth using some form of encryption. This article was just a quick introduction to the most commonly used built-in perl crypt function.

From: http://www.osix.net/modules/article/?id=571

encrypting passwords with Perl

Passwords must not be generated with hash functions such as md5(1) or Digest::MD5 , as these do not implement security features required by passwords, such as salting. Instead, use the built-in Perl crypt function or Crypt::PasswdMD5 module to produce passwords. Examples of the legacy unix Data Encryption Standard (DES) and newer Message Digest Algorithm #5 (MD5) encrypted passwords are shown below.

des lRk62l2WdzX1k
md5 $1$43SgvNjO$5a68aNBxASAChyjBZ3hj2/

Some unix systems have updated the traditional crypt function to also generate MD5 or Blowfish encrypted passwords . For more portable code, use the module Crypt::PasswdMD5 over an operating system specific crypt call.

The crypt-example script demonstrates how to generate traditional DES passwords and new MD5 based ones. The code is duplicated below. Avoid using crypt , as modern systems can break DES passwords very quickly. MD5 will suffer a similar fate in a number of years, due to increasing processor power (brute force) and disk space (huge dictionary databases to lookup generated passwords).

#!/usr/bin/perl -wl
use strict;

use Crypt::PasswdMD5 qw(unix_md5_crypt);
my @salt = ( '.', '/', 0 .. 9, 'A' .. 'Z', 'a' .. 'z' );

# this takes password as argument: good for simple example, bad for
# security (perldoc -q password)
my $password = shift || die "usage: $0 password";

my %encrypted;

# generate traditional (weak!) DES password, and more modern md5
$encrypted{des} = crypt( $password, gensalt(2) );
$encrypted{md5} = unix_md5_crypt( $password, gensalt(8) );

print "$_ $encrypted{$_}" for sort keys %encrypted;

# uses global @salt to construct salt string of requested length
sub gensalt {
my $count = shift;

my $salt;
for (1..$count) {
$salt .= (@salt)[rand @salt];
}

return $salt;
}

Verifying Passwords

The crypt function documentation covers how to verify a password against an encrypted password. Briefly:

#!/usr/bin/perl -l

print "match" if crypt('password', 'QQjYbirnCGD7A') eq 'QQjYbirnCGD7A';


From: http://sial.org/howto/perl/password-crypt/

Perl crypt() on unix

What is crypt(), and what is DES

The Perl crypt() functions allows you to store data such as passwords or other sensitive information as an encrypted string using ASCII characters. Unix / linux servers use DES (the Digital Encryption Standard) which is a Unix encryption system using 56 bit keys in a complicated 16 round substitution process. The Perl crypt() function is a one way encryption method meaning, once a password has been encrypted, it cannot be decrypted.

How to encrypt passwords on a unix system

To encrypt passwords on a unix server, you can make use of Perl's crypt() function. It takes two arguments, the first is the string or password you want to encrypt, and the second argument is the salt.

$VAR{pass} = "mypass";
$VAR{salt} = "ab";
$VAR{pass} = crypt($VAR{pass}, $VAR{salt});
print $VAR{pass};
What is the salt

The salt is any any two characters which are to be subsequently used as part of the encryption's algorithm. It's stored by Unix as the first two characters of the encrypted string for later comparison. If you're storing your passwords for Apache's Basic Authentication (.htaccess), it's a good idea to remember how you generated your salt, or at least read the first two characters of the encrypted password and re-use them as the salt when comparing User input.

How to compare encrypted passwords

The key is in the salt. If you're using a different salt to compare form input against an already encrypted password, you're in trouble. The form input must be encrypted using the same method used to encrypt the stored password. You then check the new encryption against the stored encryption for a perfect match.

A good encryption method

The following is a safe and sound encryption method suitable for .htaccess and non-htaccess encryption. It uses the first two non-encrypted characters of the password typed in by a User logging in to generate the salt. The stored password also used the same salt.

$VAR{check} = $FORM{pass};
$VAR{salt} = substr($VAR{check}, 0, 2);
$VAR{check} = crypt($VAR{check}, $VAR{salt});
print $VAR{check};

$VAR{pass} = "myNSG/MN.H5b3";
$VAR{salt} = substr($VAR{pass}, 0, 2);
$VAR{pass} = crypt($VAR{pass}, $VAR{salt});
print $VAR{pass};

if($VAR{check} eq $VAR{pass}{
# you're in like Flynn
}

From: http://www.perlscriptsjavascripts.com/tutorials/howto/encrypt_unix_passwords.html

Perl Command Line

As many of you know, Perl is a useful scripting language. However, you can also write many useful one liners with it - there are plenty of options available to modify its behaviour.

The standard way of doing things as a Perl one-liner is as follows:

     $ perl -e 'print "Hello World\n";'

As you can see, you simply put the perl code between quotes - this is useful for testing out perl idioms, or for simple code. A slightly more advanced one-liner for crypting passwords would be:

     $ perl -e 'print crypt("password", "salt"),"\n"'

Note that this will be put in any shell history files, and be viewable from the process list, so don't run this with any sensitive passwords. A better way to do this would be as follows:

     $ perl
     print crypt("password", "salt"),"\n";
     ^D

This will output the crypted password on STDOUT. This is useful in many other cases for testing code.

Perl also has syntax checking, which is useful when combined with use strict and #!/usr/bin/perl -w - which is important to use on all scripts. To test out syntax, try the following:

     $ perl -c script.pl

This is useful when debugging code, as it shows you syntax errors. It also doesn't actually execute the code.

The next useful idiom that command options gives you is options that let you loop over a given file. This can be useful for editing a file, and taking actions based on the contents, or even editing it in place. There are many variants on this, as follows.

The basic option to do this is -p. It is equivalent to the following code, and makes perl operate a little like sed.

while (<>) {
     ...          # your script goes here
} continue {
     print or die "-p destination: $!\n";
}

For those of you who don't know perl, <> is effectivelly a loop over the file, putting each line into a variable available for processing.

This is useful when you want to make a change, and print each line after processing it. An example of this would be:

File:
     The cat sat on the mat.

     $ perl -pe 's/cat/dog/' file
     The dog sat on the mat.

Slightly different to this is -n - this is almost the same as -p, but it doesn't print every line. This is equivalent to the following code.

while (<>) {
     ...          # your script goes here
}

Another useful modifier is -i. This allows you to either edit the files in place, or back them up. As in the previous example, you can edit the file in place.

     $ perl -pi -e 's/cat/dog/' file

This edits the file in place - this can be useful for global search and replacements. If you're cautious, however, you can leave a backup by adding an extension, such as -i.bak. This will leave a backup file with the contents unmodified.

For even more fun, you can use -a, which turns on autosplit mode. This modifier to -n or -p adds an implicit split inside the while loop, and is useful for columned data. By default, it splits on space, but you can change it with -F, which specifies a regular expression to split on. A useful example of parsing password files would be:

     $ perl -an -F: -e 'if ($F[2] > 100) { print $F[0],"\n"; }' /etc/passwd

This splits on a colon, and puts the result into @F . This can be useful for finding out information based on context.

To include modules in these scripts, use the -M option. For example:

     $ perl -Mfoo -e '....';

This is equivalent to:

     #!/usr/bin/perl
     use foo;

One thing to note however, is that perl one-liners are rarely run with use strict or -w. If you find yourself using these, it might be time to consider a script. It is important to known when to keep with one-liners, and when to use a script. Additionally, remember that you can use any of these options in a script.

As you can see you can get quite a lot of functionality for very little code, and can save yourself a lot of time, both in script development time, and in finding out information from files. These options allow you to use the functionality of perl, without having to write a full blown script by giving you well tested, well known code. For more information about these options and more, see both perl(1p) and perlrun(1p) .


From: http://quark.humbug.org.au/publications/perl/perlline.html




ADVERTISING