MySQL SHA()不起作用 [英] MySQL SHA() doesn't work
问题描述
基本上,我像这样在注册表格中加密了密码:
So basically I encrypted password in my registration form like so:
$query = "INSERT INTO users(first_name, last_name, email, password,
username) VALUES ('$fn', '$ln', '$em', SHA('$pw1'), '$un')";
现在密码已被散列,但是当我尝试在我的登录脚本中使用它时,它不想工作,并且函数mysql_num_rows返回0.
Now the password is hashed, but when I try to use it in my login script it doesn't want to work and function mysql_num_rows returns 0.
<?php
ob_start();
//If login button is pressed
if(isset($_POST['submitted'])){
//Username clean up
if(preg_match('%^[a-zA-Z0-9_-]{6,20}$%', stripslashes(trim($_POST['username'])))){
$u = escape_data($_POST['username']);
} else {
$u = FALSE;
echo '<p><font color="red" size="+1">Please enter valid username</font></p>';
}
//Password clean up
if(preg_match('%^[a-zA-Z0-9_-]{6,20}$%', stripslashes(trim($_POST['password'])))){
$p = escape_data($_POST['password']);
} else {
$p = FALSE;
echo '<p><font color="red" size="+1">Please enter valid password</font></p>';
}
//Check if both matched
if($u && $p){
$query = "SELECT * FROM users WHERE username='$u' AND password=SHA('$p')";
$result = mysql_query($query);
$count = mysql_num_rows($result);
$row = mysql_fetch_array($result, MYSQL_NUM);
if($count != 0){
$_SESSION['username'] = $row[1];
$_SESSION['password'] = $row[3];
header("Location: login_confirmed.php");
} else {
echo "Wrong username or password!";
}
}
}
ob_end_flush();
?>
推荐答案
可能是因为您的密码字段类型.您的密码字段是VARCHAR
吗?多久了?在我看来,SHA
生成的字符串长于字段允许的长度,因此它在存储时会被截断,并且在重新生成它进行检查时会匹配.
It's probably because of your password field type. Is your password field VARCHAR
? How long is it? It seems to me that SHA
is generating a string longer than it is allowed by the field so it gets cutoff when it is stored and it does match when you regenerate it to check.
MySQL文档说,您需要40个字符存储SHA
的输出.
MySQL documentation says that you need 40 characters to store the output of SHA
.
计算字符串的SHA-1 160位校验和,如 RFC 3174(安全哈希算法).该值以字符串形式返回 40个十六进制数字,如果参数为NULL,则为NULL.可能之一 此功能的用途是用作哈希键.
Calculates an SHA-1 160-bit checksum for the string, as described in RFC 3174 (Secure Hash Algorithm). The value is returned as a string of 40 hex digits, or NULL if the argument was NULL. One of the possible uses for this function is as a hash key.
这篇关于MySQL SHA()不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!