如何解密bcrypt存储的哈希 [英] How to decrypt hash stored by bcrypt
问题描述
我有这个脚本可以加密密码,但是我不知道如何反向密码和解密密码.这可能是一个非常简单的答案,但我不知道该怎么做.
I have this script that encrypts a password but I don't know how to reverse it and decrypt it. This may be a very simple answer but I don't understand how to do it.
#!/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));
}
推荐答案
您在哈希,而不是加密!
有什么区别?
区别在于哈希是单向函数,而加密是双向函数.
The difference is that hashing is a one way function, where encryption is a two-way function.
那么,如何确定密码正确?
因此,当用户提交密码时,您无需解密存储的哈希,而是对用户输入执行相同的bcrypt
操作并比较哈希.如果它们相同,则您接受身份验证.
Therefore, when a user submits a password, you don't decrypt your stored hash, instead you perform the same bcrypt
operation on the user input and compare the hashes. If they're identical, you accept the authentication.
您应该对密码进行哈希处理还是加密?
您现在正在执行的操作-对密码进行哈希处理-是正确的.如果仅加密密码,则违反应用程序安全性可能会导致恶意用户轻而易举地学习所有用户密码.如果您使用哈希密码(或更好的盐和哈希)密码,则用户需要破解密码(在bcrypt
上计算量很大)来获取该知识.
What you're doing now -- hashing the passwords -- is correct. If you were to simply encrypt passwords, a breach of security of your application could allow a malicious user to trivially learn all user passwords. If you hash (or better, salt and hash) passwords, the user needs to crack passwords (which is computationally expensive on bcrypt
) to gain that knowledge.
由于您的用户可能会在多个地方使用其密码,因此这将有助于保护它们.
As your users probably use their passwords in more than one place, this will help to protect them.
这篇关于如何解密bcrypt存储的哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!