我有这个加密密码的脚本,但我不知道如何反转它并解密它.这可能是一个非常简单的答案,但我不明白该怎么做.
#!/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));
}
Run Code Online (Sandbox Code Playgroud)
Gli*_*ire 103
有什么不同?
不同之处在于散列是一种单向函数,其中加密是双向函数.
那么,你如何确定密码是对的?
因此,当用户提交密码时,您不会解密存储的哈希值,而是bcrypt对用户输入执行相同的操作并比较哈希值.如果它们相同,则接受身份验证.
你应该对密码进行哈希或加密吗?
你现在正在做什么 - 散列密码 - 是正确的.如果您只是简单地加密密码,则违反应用程序安全性可能会使恶意用户轻易学会所有用户密码.如果您使用哈希(或更好,盐和哈希)密码,用户需要破解密码(这在计算上非常昂贵bcrypt)才能获得这些知识.
由于您的用户可能在多个地方使用他们的密码,这将有助于保护他们.