我一直致力于学校的侧面项目,用户可以登录并记录他们拥有的志愿者小时数。我已完成注册页面,它连接到数据库并存储用户信息,包括加密密码。 我遇到的问题是用户尝试登录时。输入密码后,程序进入数据库并检索散列函数,但是当我尝试解密时,解密的行是空白的。我不确定为什么会发生这种情况,但是我想一些帮助解决这个问题。谢谢。
以下是我的登录页面和encrypt_decrypt()函数的代码:
login.php页面:
<?php
include("encrypt_decrypt.php");
$username="root";
$password="";
$server="localhost";
$db_name="userauthentication";
$uname="";
$pword="";
$error_msg = "";
if(isset($_POST["submit"])){
$db_handle = mysqli_connect($server, $username, $password);
$db_found = mysqli_select_db($db_handle, $db_name);
$uname = $_POST["uname"];
$uname = htmlspecialchars($uname);
$uname = mysqli_real_escape_string($db_handle, $uname);
$pword = $_POST["pword"];
$pword = htmlspecialchars($pword);
$pword = mysqli_real_escape_string($db_handle, $pword);
if($db_found){
if($uname == "admin"){
$SQL = "SELECT * FROM WHERE username = '$uname' AND pword = '$pword'";
$result = mysqli_query($db_handle, $SQL);
$num_rows = mysqli_num_rows($result);
if(isset($num_rows) && $num_rows > 0){
session_start();
$_SESSION['login'] = "2";
header("Location: adminpage.html");
}else{
print("error");
}
}else{
$SQL = "SELECT * FROM login WHERE username = '$uname'";
$result = mysqli_query($db_handle, $SQL);
$num_rows = mysqli_num_rows($result);
if($num_rows > 0){
$db_field = mysqli_fetch_assoc($result);
$pword_match = $db_field['password'];
$pword_match = encrypt_decrypt('decrypt', $pword_match);
print ($pword . "<br>");
print $pword_match;
if($pword == $pword_match){
session_start();
$_SESSION['login'] = "1";
header("Location: mainpage.html");
}else{
$error_msg = "<span class='error_msg'>Wrong password!</span>";
print $error_msg;
}
}else if($num_rows == 0){
$error_msg = "<span class='error_msg'>Wrong username!</span>";
print $error_msg;
}
}
}else{
$error_msg = "<span class='register'>Could not connect to database!</span>";
print $error_msg;
}
}
?>
这些是在login.php文件中给我带来麻烦的行:
$db_field = mysqli_fetch_assoc($result);
$pword_match = $db_field['password'];
$pword_match = encrypt_decrypt('decrypt', $pword_match);
print ($pword . "<br>");
print $pword_match;
我刚刚打印出两条线,所以我可以看到发生了什么。 打印$ pword行很好,但打印$ pword_match给我一个空白。
encrypt_decrypt()函数:
<?php
function encrypt_decrypt($action, $string) {
$output = false;
$encrypt_method = "AES-256-CBC";
$secret_key = $string;
$secret_iv = "password";
// hash
$key = hash('sha256', $secret_key);
// iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
$iv = substr(hash('sha256', $secret_iv), 0, 16);
if( $action == 'encrypt' ) {
$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
$output = base64_encode($output);
}
else if( $action == 'decrypt' ){
$output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
}
return $output;
}
?>
答案 0 :(得分:1)
关于如何在服务器上处理密码,搜索示例代码,有数百个答案。
基本上,当第一次对密码进行哈希处理并将哈希值存储在服务器上时,会收到密码。当用户想要登录时,检索密码哈希,密码被哈希,然后比较哈希值。
注意:加密密码意味着密钥位于服务器上,如果攻击者获得密码,则攻击者可以使用所有密码。如果您认为服务器是安全的,您就不必费心加密密码了。人们不能依赖服务器的安全性,但至少应该对服务器使用双因素身份验证。