Twi*_*ter 0 php encryption passwords
可能重复:
PHP密码的安全散列和盐
为了加密php文件中的密码,我想更改为sha256或md5,而不是使用sha1作为iIwent进行在线研究,他们说sha1不是那么安全.
如何更改php文件?
<?php
class DB_Functions {
private $db;
//put your code here
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$this->db = new DB_Connect();
$this->db->connect();
}
// destructor
function __destruct() {
}
/**
* Storing new user
* returns user details
*/
public function storeUser($name, $nric, $email, $license, $address, $postal_code, $password) {
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"]; // salt
$result = mysql_query("INSERT INTO users(name, nric, email, license, address, postal_code, encrypted_password, salt, created_at) VALUES('$name', '$nric', '$email', '$license', '$address', '$postal_code', '$encrypted_password', '$salt', NOW())");
// check for successful store
if ($result) {
// get user details
$uid = mysql_insert_id(); // last inserted id
$result = mysql_query("SELECT * FROM users WHERE uid = $uid");
// return user details
return mysql_fetch_array($result);
} else {
return false;
}
}
/**
* Get user by nric and password
*/
public function getUserByNricAndPassword($nric, $password) {
$result = mysql_query("SELECT * FROM users WHERE nric = '$nric'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
$salt = $result['salt'];
$encrypted_password = $result['encrypted_password'];
$hash = $this->checkhashSSHA($salt, $password);
// check for password equality
if ($encrypted_password == $hash) {
// user authentication details are correct
return $result;
}
} else {
// user not found
return false;
}
}
/**
* Check user is existed or not
*/
public function isUserExisted($nric) {
$result = mysql_query("SELECT nric from users WHERE nric = '$nric'");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
// user existed
return true;
} else {
// user not existed
return false;
}
}
/**
* Encrypting password
* @param password
* returns salt and encrypted password
*/
public function hashSSHA($password) {
$salt = sha1(rand()); //algorithm hash
$salt = substr($salt, 0, 10);
$encrypted = base64_encode(sha1($password . $salt, true) . $salt);
$hash = array("salt" => $salt, "encrypted" => $encrypted);
return $hash;
}
/**
* Decrypting password
* @param salt, password
* returns hash string
*/
public function checkhashSSHA($salt, $password) {
$hash = base64_encode(sha1($password . $salt, true) . $salt);
return $hash;
}
}
?>
Run Code Online (Sandbox Code Playgroud)
最安全的散列密码方式,就是使用BCrpyt
MD5,SHA1,SHA256被认为是不安全的.
有关此问题的更多信息,请参阅此安全性帖子:https: //security.stackexchange.com/questions/211/how-to-securely-hash-passwords
要实现BCrpyt密码散列,请参阅:如何在PHP中使用bcrypt进行散列密码?