Skip to content

Instantly share code, notes, and snippets.

@evandrix
Created July 11, 2011 15:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save evandrix/1076041 to your computer and use it in GitHub Desktop.
Save evandrix/1076041 to your computer and use it in GitHub Desktop.
Using bcrypt to secure passwords in a Perl application
#!/usr/bin/perl
use Crypt::Eksblowfish::Bcrypt;
use Crypt::Random;
$password = 'bigtest';
$encrypted = encrypt_password($password);
print "$password is encrypted as $encrypted\n";
print "Yes the password is $password\n" if check_password($password, $encrypted);
print "No the password is not smalltest\n" if !check_password('smalltest', $encrypted);
# Encrypt a password
sub encrypt_password {
my $password = shift;
# Generate a salt if one is not passed
my $salt = shift || salt();
# Set the cost to 8 and append a NUL
my $settings = '$2a$08$'.$salt;
# Encrypt it
return Crypt::Eksblowfish::Bcrypt::bcrypt($password, $settings);
}
# Check if the passwords match
sub check_password {
my ($plain_password, $hashed_password) = @_;
# Regex to extract the salt
if ($hashed_password =~ m!^\$2a\$\d{2}\$([A-Za-z0-9+\\.]{22})!) {
return encrypt_password($plain_password, $1) eq $hashed_password;
} else {
return 0;
}
}
# Return a random salt
sub salt {
return Crypt::Eksblowfish::Bcrypt::en_base64(Crypt::Random::makerandom_octet(Length=>16));
}
@infopac
Copy link

infopac commented Aug 9, 2012

All day I've been reading / trying to figure out how to store a bcrypt password in a database, then load it (from database), and verify the password. This is the only example online I found that provides everything I need to know. Kudos to you for providing this extremely easy to understand example! The salt is random and the use of the regex to verify the stored password in the appropriate format is excellent!

@infopac
Copy link

infopac commented Aug 10, 2012

Just an update here: the regex fails on any salt with a forward slash '/'.

According to wikipedia, Base64 character set includes the forward slash:

http://en.wikipedia.org/wiki/Base64

Thus, regex (line 31) should read:

if ($hashed_password =~ m!^$2a$\d{2}$([A-Za-z0-9+./]{22})!)

I've tested this on 1,000 iterations and it worked.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment