Created
July 8, 2011 12:12
-
-
Save gcrawshaw/1071698 to your computer and use it in GitHub Desktop.
Using bcrypt to secure passwords in a Perl application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use Crypt::Eksblowfish::Bcrypt; | |
$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(); | |
# Encrypt the password | |
my $hash = Crypt::Eksblowfish::Bcrypt::bcrypt_hash({ | |
key_nul => 1, | |
cost => 8, | |
salt => $salt, | |
}, $password); | |
# Return the salt and the encrypted password | |
return join('-', $salt, Crypt::Eksblowfish::Bcrypt::en_base64($hash)); | |
} | |
# Check if the passwords match | |
sub check_password { | |
my ($plain_password, $hashed_password) = @_; | |
my ($salt) = split('-', $hashed_password, 2); | |
return length $salt == 16 && encrypt_password($plain_password, $salt) eq $hashed_password; | |
} | |
# Return a random salt | |
sub salt { | |
my $itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; | |
my $salt = ''; | |
$salt .= substr($itoa64,int(rand(64)),1) while length($salt) < 16; | |
return $salt; | |
} |
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));
}
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
The salt can have a forward slash, so your regexp on line 31 should be,