【问题标题】:SHA256 salt with PHP and MySQL - Insert error带有 PHP 和 MySQL 的 SHA256 salt - 插入错误
【发布时间】:2015-01-27 09:30:59
【问题描述】:

我正在使用以下代码对 MySQL 数据库中的密码进行加盐和哈希处理:

<?php
function make($string, $salt = '') {
    return hash('sha256', $string . $salt);
}
function salt($length) {
    return mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
}

$salt = salt(32);
$password = make('password', $salt);
?>

但是,当我尝试将生成的盐插入数据库时​​,在某些情况下会出现此错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ÜöOòƒ·¡]ŽÖ', 1)' at line 1

我认为这是因为生成了无法识别的字符。有什么办法可以解决这个问题?

【问题讨论】:

  • 显示插入的代码

标签: php mysql insert salt sha256


【解决方案1】:

您正在插入原始二进制垃圾。这将自然地(和半随机地)包含 SQL 元字符,例如 '。这意味着您的查询容易受到sql injection attacks 的攻击。

您没有显示任何实际的 PHP 代码,但您应该使用准备好的语句,或者进行手动转义,例如

$stmt = mysqli_prepare($conn, "INSERT .... (password_hash) VALUES (?)");
$stmt->execute(array($raw_hash));

$quoted = mysql_real_escape_string($raw_hash);
$sql = "INSERT ... (password_hash) VALUES ('$quoted')";

或者,您可以对该哈希字符串进行编码,例如使用base64,这样编码后的hash就变成了相对无害的字符串。但即便如此,您也应该使用正确的查询构造技术。

【讨论】:

    猜你喜欢
    • 2016-04-15
    • 1970-01-01
    • 1970-01-01
    • 2013-03-01
    • 1970-01-01
    • 2013-06-06
    • 2014-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多