Skip to content

Instantly share code, notes, and snippets.

@wernerb
Forked from evandrix/gist:1076041
Last active August 28, 2015 08:31
Show Gist options
  • Save wernerb/6a52e77b0b8974714263 to your computer and use it in GitHub Desktop.
Save wernerb/6a52e77b0b8974714263 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));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment