perlencryptionpasswords

How could I hide/protect password from a Perl script


I'm writing a Perl script that needs to connect to an SMTP server in order to send a mail, but I really don't like this kind of things :

my $pass = '123456';

And I found Data::Encrypted, that should allow the user to prompt it the first time and then store it encrypted.

use Data::Encrypted file => ".passwd", qw(encrypted);
my $password = encrypted('password');

But I cannot make it work, it makes a running time error :

Bad key file format at /Library/Perl/5.12/Data/Encrypted.pm line 78

Is anybody having the same issue, or know another way to hide/protect password?


Solution

  • The Data::Encrypted module was last released in 2001. I'd say that's a good sign not to use it.

    Normally, I'd say storing passwords at all is a bad idea even encrypted. However, if you must store a password for use contacting another system, encrypting it is the way to go. The way I would do it is something like this:

    # Rijndael is also known as AES, which is the encryption standard used by the NSA
    use Crypt::Rijndael;
    use IO::Prompter;
    
    # This secret is exactly 32 bytes long, you could prompt for this as a
    # passphrase or something and pad it with spaces or whatever you need
    my $app_secret = 'this_is_the_key_the_app_uses....';
    
    # Setup the encryption system
    my $crypto = Crypt::Rijndael->new( $app_secret, Crypt::Rijndael::MODE_CBC() );
    
    # Ask the user to enter the password the first time
    my $password = prompt "password: ", -echo => ''; # from IO::Prompter
    
    # Encrypt the password. You can save this off into a file however you need to
    my $enc_password = $crypto->encrypt($password);
    
    # Later load it from the file and decrypt it:
    my $password = $crypto->decrypt($password);
    

    For more information see Crypt::Rijndael and IO::Prompter.