2014-02-24 341 views
0

我正在尝试注册并登录带有盐加密的表单,但我并不十分熟悉它。所以一切正常,除了登录无法识别密码,所以我很确定这是加密问题。这些线寄存器:PHP盐加密/解密密码

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

,这些都是对登录:

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

任何人都可以点的问题。谢谢!

回答

0

这有很多不对的地方。 对于初学者:您是否用密码存储盐?如果不是,则密码变得无法验证。

安全考虑:

hash('sha256', ...不足;考虑bcrypt,scrypt,或PBKDF2

$text = md5(uniqid(rand(), true));听说过的openssl_random_pseudo_bytes()

(同样,你不应该试图解密密码,只有验证。)

如果你不熟悉这些概念,发挥它的安全,并使用一个尝试和真正的图书馆。

2

其实你的代码应该尽我所能地工作,虽然它是非常不安全的!

  1. 问题:SHA256不适合哈希密码,因为它太快了。使用像BCrypt这样的慢键推导函数。
  2. 问题:三字母盐只有字母几乎没有保护。

也许您的数据库字段小于64个字符,或者您正在比较不同的密码。在任何情况下,都有一种更简单更安全的哈希密码方式,只需使用新功能password_hash()password_verify()即可。早期的PHP版本也存在compatibility pack

// 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);