MySQL AES Decrypt返回值

时间:2012-07-10 16:52:00

标签: php mysql aes

尝试使用PHP / MySQL为客户端开发AES加密数据库。插入加密值是有效的,但无法返回可用的解密值。

public static function auth($username="", $password="") {
    global $database;
    $fields = self::$db_fields;
    array_shift($fields);
    $username = $database->escape_value($username);
    $password = $database->escape_value($password);
    $hashed_pwd = sha1($password);
    $join_str = ", '" . AUTH_KEY . "'), AES_DECRYPT(";

    $sql  = "SELECT id, AES_DECRYPT(";
    $sql .=  join($join_str, $fields) . ", '" . AUTH_KEY . "') FROM " . self::$table_name. " ";
    $sql .= "WHERE u_name = AES_ENCRYPT('{$username}', '" . AUTH_KEY . "') ";
    $sql .= "AND u_pwd = AES_ENCRYPT('{$hashed_pwd}', '" . AUTH_KEY . "') ";
    $sql .= "LIMIT 1";

使用以下查询:

    $query_result = $database->query($sql);
    $result_array = $database->fetch_array($query_result);

}

返回:

    Array ( 
        [0] => 5 
        [id] => 5 
        [1] => a_user_name 
        [AES_DECRYPT(user_name, '[PRINTS FULL AUTH KEY]')] => a_user_name 
        [2] => 0000hashedpasswordstring00000 
        [AES_DECRYPT(user_pwd, '[PRINTS FULL AUTH KEY]')] => 0000hashedpasswordstring00000  
        [3] => sample@email.com 
        [AES_DECRYPT(user_email, '[PRINTS FULL AUTH KEY]')] => sample@email.com 
    )

这是次要解决方案。理想情况下,查询将是面向对象的,但该方法返回的是一个包含字段但没有值的数组。

显然,在结果中传输完整的auth密钥完全违背了加密的目的。困惑于为什么它返回一个组合的关联/索引数组,而不仅仅是一个索引数组,或只是一个关联数组。是否会返回[user_email] => sample@email.com的SQL语法更改 代替 [AES_DECRYPT(user_email, '[PRINTS FULL AUTH KEY]')] => sample@email.com

1 个答案:

答案 0 :(得分:1)

您需要为包含该函数的列使用别名:

$sql  = "SELECT id, AES_DECRYPT(";
$sql .=  join($join_str, $fields) . ", '" . AUTH_KEY . "') AS user_email FROM " . self::$table_name. " ";
$sql .= "WHERE u_name = AES_ENCRYPT('{$username}', '" . AUTH_KEY . "') ";
$sql .= "AND u_pwd = AES_ENCRYPT('{$hashed_pwd}', '" . AUTH_KEY . "') ";
$sql .= "LIMIT 1";

来自SELECT上的MySQL文档:

  

可以使用AS alias_name为select_expr指定别名。别名是   用作表达式的列名,可以在GROUP BY中使用,   ORDER BY或HAVING子句。例如:

     

SELECT CONCAT(last_name,',',first_name)AS full_name FROM mytable   ORDER BY full_name;

这样的加密通常在应用程序中完成,而不是在MySQL中完成。在MySQL中完成时,密钥最终会出现在MySQL日志中。