简体   繁体   English

PHP salt加密/解密密码

[英]PHP salt encrypt/decrypt password

I'm trying to make register and log in forms having salt encryption, and I'm not really familiar with it. 我正在尝试进行注册并登录具有盐加密的表单,我并不熟悉它。 So everything is working except that log in can't recognize password so I'm pretty sure it's encryption problem. 所以一切正常,除了登录无法识别密码所以我很确定它是加密问题。 These are lines for register: 这些是注册行:

$hash = hash('sha256', $password1);
function createSalt()
{
$text = md5(uniqid(rand(), true));
return substr($text, 0, 3);
}
$salt = createSalt();
$password = hash('sha256', $salt . $hash);

and these are for login: 这些是用于登录:

$userData = mysql_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );
if($hash != $userData['password'])
{
echo "Incorrect password";
}

Can anybody point the problem. 任何人都可以指出这个问题。 Thanks! 谢谢!

Actually your code should work as far as i can see, though it is very unsafe! 实际上你的代码应该尽我所能,虽然它是非常不安全的!

  1. Problem: SHA256 is not appropriate to hash passwords, because it is ways too fast. 问题:SHA256不适合散列密码,因为它太快了。 Use a slow key-derivation function like BCrypt. 使用像BCrypt这样的慢键派生函数。
  2. Problem: A three character salt with only letters is nearly no protection. 问题:只有字母的三字盐几乎没有保护。

Maybe your database field is smaller than 64 characters, or you are comparing different passwords. 也许您的数据库字段小于64个字符,或者您正在比较不同的密码。 In every case there is an easier and safer way to hash passwords, just use the new functions password_hash() and password_verify() . 在每种情况下,都有一种更简单,更安全的哈希密码方法,只需使用新功能password_hash()password_verify() There exists also a compatibility pack for earlier PHP versions. 还存在早期PHP版本的兼容包

// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);

// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);

There are quite a few things wrong with this. 这有很多不妥之处。 For starters: Are you storing the salt with the password? 对于初学者:您是否使用密码存储盐? If not, then passwords become unverifiable. 如果没有,则密码变得无法验证。

Security considerations: 安全考虑:

hash('sha256', ... is insufficient; consider bcrypt, scrypt, or pbkdf2 hash('sha256', ...不够;考虑bcrypt,scrypt或pbkdf2

$text = md5(uniqid(rand(), true)); Ever heard of openssl_random_pseudo_bytes() ? 有没有听说过openssl_random_pseudo_bytes()

(Also, you shouldn't seek to decrypt passwords, only verify them.) (另外,您不应该尝试解密密码,只能验证密码。)

If you're not familiar with these concepts, play it safe and use a tried and true library. 如果您不熟悉这些概念,请安全地使用并使用经过验证的真实库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM