Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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})!) {
# Use a letter by letter match rather than a complete string match to avoid timing attacks
my $match = encrypt_password($plain_password, $1);
my $bad = 0;
for (my $n=0; $n < length $match; $n++) {
$bad++ if substr($match, $n, 1) ne substr($hashed_password, $n, 1);
}
return $bad == 0;
} else {
return 0;
}
}
# Return a random salt
sub salt {
return Crypt::Eksblowfish::Bcrypt::en_base64(Crypt::Random::makerandom_octet(Length=>16));
}
@tantalor
Copy link

tantalor commented May 16, 2012

The salt can have a forward slash, so your regexp on line 31 should be,

^\$2a\$\d{2}\$([A-Za-z0-9+\\.\/]{22})

@roycewilliams
Copy link

roycewilliams commented Aug 29, 2018

It might be better to use Crypt::Random for salt generation:

sub salt {
    return Crypt::Eksblowfish::Bcrypt::en_base64(Crypt::Random::makerandom_octet(Length=>16));
}

@kordaff
Copy link

kordaff commented Sep 3, 2018

Turning an octet binary string into base64 adds 1/3 the length of the binary string, so this works better yet in the above gist, no additional $salt=substr($salt,0,16), on a 22 character base64 string that I was getting, will be required:

sub salt
{
return Crypt::Eksblowfish::Bcrypt::en_base64(Crypt::Random::makerandom_octet(Length=>12));
}

PS Thank you both, this was what i was looking for to avoid sending plaintext pw to database to compare to hashed pw there. Much better.

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