Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi. Here is a simple encryption util
#!/usr/bin/perl -w my $x = shift; chomp $x; print reverse( substr( crypt( $x, "ar" ), 2))."\n";
How would I write a decryption of the string this prints out ?
Thanks Thanks

Replies are listed 'Best First'.
Re: Simple decrypt ?
by ikegami (Patriarch) on Feb 16, 2008 at 22:38 UTC

    crypt doesn't encrypt, it hashes. You can't decrypt it.

    If $x is a password and you want to check if the user submitted the right password $p, just repeat the process and check if the previously saved output for $x matches the output for $x.

    By the way, using a constant salt ("ar") is a bug. For that matter, the use of crypt should probably be considered a bug.

Re: Simple decrypt ?
by kyle (Abbot) on Feb 16, 2008 at 23:41 UTC

    As ikegami says, crypt is not a reversible process. That said, if you have a crypted string, the usual way of finding the original string is with a brute force dictionary attack.

    sub encrypt { my $x = shift; chomp $x; return reverse substr crypt( $x, 'ar' ), 2; } # choose a random dictionary word my $dictionary = '/usr/share/dict/words'; my $secret_word; open my $dict_fh, '<', $dictionary or die "Can't read '$dictionary': $!"; my $line_no = 0; while ( my $word = <$dict_fh> ) { chomp $word; $secret_word = $word if rand() < 1/++$line_no; } close $dict_fh or die "Can't close dict: $!"; print "my secret word is: $secret_word\n"; my $encrypted_word = encrypt( $secret_word ); undef $secret_word; # figure out which word it was open $dict_fh, '<', $dictionary or die "Can't read '$dictionary': $!"; while ( my $word = <$dict_fh> ) { chomp $word; if ($encrypted_word eq encrypt($word)) { print "secret word is: $word\n"; last; } } close $dict_fh or die "Can't close dict: $!";

    On my system, this runs in less than a second, even when it picks a word relatively late in the file. Also, the word it finds that works is not always the word that was originally selected. For example:

    my secret word is: shellfishes secret word is: shellfish

    This is because crypt ignores everything after eight characters of input. That means that even if you have to look for passwords outside the dictionary, you can restrict yourself to passwords eight characters or less.

Re: Simple decrypt ?
by samtregar (Abbot) on Feb 17, 2008 at 18:37 UTC
    Just to round out the fine advice given so far, if you really need reversible encryption you should use a real encryption algorithm. I like Crypt::Blowfish which is used via the Crypt::CBC module.

    -sam