如何对加密列数据进行排序?

How to sort encrypted column data?

我已经完成了对加密和非加密列的搜索,但对于排序,非加密字段排序成功,但加密字段未排序。

加密列:名字、姓氏、电子邮件

加密函数

// Encrypt Data
function encrypted_data($decrypted){
    if($decrypted != NULL){
        $method = 'aes-256-cbc';
        // Must be exact 32 chars (256 bit)
        $salt = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
        $password = substr(hash('sha256', $salt, true), 0, 32);
        // IV must be exact 16 chars (128 bit)
        $iv = chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0);
        $encrypted = base64_encode(openssl_encrypt($decrypted, $method, $password, OPENSSL_RAW_DATA, $iv));
        return $encrypted;
    } else {
        return "";
    }
}

搜索代码

if(isset($_POST['search']) && isset($_POST['search']['value']) && !empty($_POST['search']['value']))
{
    $search_keyword = trim($_POST['search']['value']);
    $encrypted = encrypted_data($search_keyword);
    
    $search_query = "AND id like '%$search_keyword%' OR pin_local_id like '%$search_keyword%' OR firstname like '%$encrypted%' OR lastname like '%$encrypted%' OR email like '%$encrypted%'";

    $sql .= $search_query;
    $count_sql .= $search_query;
}

订购代码

if(isset($_POST['order'][0]['dir']))
{
    $db_orderby = $_POST['order'][0]['dir'];

    if( isset($_POST['order'][0]['column']) && $_POST['order'][0]['column'] == 1 ) {
        $db_field_name = 'ID';
        $sql .= " order by $db_field_name $db_orderby ";
    } else if( isset($_POST['order'][0]['column']) && $_POST['order'][0]['column'] == 2 ) {
        $db_field_name = 'pin_local_id';
        $sql .= " order by $db_field_name $db_orderby ";
    } else if( isset($_POST['order'][0]['column']) && $_POST['order'][0]['column'] == 3 ) {
        $db_field_data = $_REQUEST['columns'][3]['data'];
        $db_field_name = 'firstname';
        $sql .= " order by $db_field_name $db_orderby ";
    } else if( isset($_POST['order'][0]['column']) && $_POST['order'][0]['column'] == 4 ) {
        $db_field_name = 'lastname';
        $sql .= " order by $db_field_name $db_orderby ";
    } else if( isset($_POST['order'][0]['column']) && $_POST['order'][0]['column'] == 5 ) {
        $db_field_name = 'email';
        $sql .= " order by $db_field_name $db_orderby ";
    }
} else {
    $sql .= " ORDER BY ID ASC ";
}

如果数据在PHP中被加密你不能使用MYSQL排序,因为MYSQL会按加密后的数据排序base64而不是原始数据价值。 MYSQL 永远不会暴露原始的解密值,因此永远无法根据它进行排序。

您需要从 Mysql 中检索加密数据,在 PHP 中对其进行解密,然后根据解密数据的值使用 usort 手动对数组进行排序。