#!/usr/bin/perlml -Tw
use strict;
use CGI;
use CGI::Carp qw(fatalsToBrowser); # show errors in browser
use Authen::Passphrase::BlowfishCrypt;
use Bytes::Random::Secure;
print "Content-type:text/html\n\n";
# read the CGI params
my $cgi = CGI->new;
my $username = $cgi->param("username");
my $password = $cgi->param("password");
if ($username =~ /[^a-zA-Z0-9]/) { die "Illegal characters" };
if ($password =~ /[^a-zA-Z0-9]/) { die "Illegal characters" };
my $settings = './settings.cnf';
use DBI;
my $dsn =
"DBI:mysql:DB;" .
"mysql_read_default_file=$dbsettings";
my $dbh = DBI->connect($dsn, undef, undef,{RaiseError=>1})
or die "Could not connect to database: $DBI::errstr";
# check the username and password in the database
my $statement = qq{SELECT username,password FROM table WHERE username=? and password=?};
my $sth = $dbh->prepare($statement)
or die $dbh->errstr;
$sth->execute($username, $password)
or die $sth->errstr;
my ($userID) = $sth->fetchrow_array;
# create a JSON string according to the database result
my $json = ($userID) ?
qq{{"success" : "login is successful", "userid" : "$userID"}} :
qq{{"error" : "username or password is wrong"}};
# return JSON string
print $json;
$dbh->disconnect();
我现在正试图在这里实施bcrypt ......但是找不到任何好的例子可供学习。我无法生成随机盐,因为cpan的文档对于像我这样的perl nobie来说是如此模糊。
我试过这样的事情:
my $gen = Authen::Passphrase::SaltedSHA512->new( passphrase => 'Sneaky!' );
my $salt = $gen->salt_hex;
my $hash = bcrypt_hash({
key_nul => 1,
cost => 8,
salt => $salt,
}, $password);
尝试打印$ hash,得到“salt必须精确到16个八位字节”错误
那只是我懒惰,无知......在黑暗中射箭。经过5个小时的流浪思考和谷歌搜索,我真的需要一个很好的例子,我的头疼。
真的很感激帮助。
PS:我看过2-3个非常模糊的例子,其中一个在stackflow中,那些没有给我任何线索。想要新鲜的东西。答案 0 :(得分:4)
如果您已经在使用Authen::Passphrase
,则可以让它为您完成所有工作:
use Authen::Passphrase::BlowfishCrypt;
my $password = "Sneaky!";
my $ppr = Authen::Passphrase::BlowfishCrypt->new(
cost => 8,
salt_random => 1,
passphrase => $password,
);
my $string = $ppr->as_rfc2307;
print $string, "\n";
# Then, to verify the password
$ppr = Authen::Passphrase->from_rfc2307($string);
if ($ppr->match($password)) {
print "OK\n";
}
如果您想直接使用Crypt::Eksblowfish::Bcrypt
,请注意它需要一个16字节的字符串作为salt:
use Crypt::Eksblowfish::Bcrypt qw(bcrypt bcrypt_hash en_base64);
my $password = "Sneaky!";
my $salt = '';
for my $i (0..15) {
$salt .= chr(rand(256));
}
my $hash = bcrypt_hash({
key_nul => 1,
cost => 8,
salt => $salt,
}, $password);
# or
my $salt_base64 = en_base64($salt);
my $string = bcrypt($password, "\$2a\$08\$$salt_base64");
print $string, "\n";
答案 1 :(得分:0)
我在这里找到了剩余答案的一部分,任何人都需要它。
非常感谢nwellnhof的所有帮助:)