首页 > 解决方案 > php-encrypt 比较两个数据

问题描述

我仍然是一个新手和一个新的编码器在加密 php 中的数据,我在数据库中有一个用 iv 加密的数据现在问题是当用户尝试搜索该数据时,我将比较他输入到数据库的数据sql 中的数据类似于WHERE tbl_column = "user_input". 有没有更好的方法来比较两个数据(普通数据检查到加密数据)这是我的代码。

<?php
$input = 'sample';

$key = "secretkey";
$secretMethod = 'AES-256-CBC';
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

echo $database_data = openssl_encrypt('sample', $secretMethod, $key, 0, $iv);

echo $data = $iv.$emessage;

$iv = substr($data, 0, $iv_size);

echo '<br/>Decrypted: '.openssl_decrypt(substr($data, $iv_size), $umethod, $key, 0, $iv);

if($data == $input) {
    echo 'equal';
} else {
    echo 'not-equal';
}

?>

标签: phpencryption

解决方案


我正在使用此解决方案进行加密/解密 1- 加密:

function crypt_val($val){
      $token = $val;
      $enc_method = 'AES-128-CTR';
      $enc_key = openssl_digest(gethostname() . "|" . $key, 'SHA256', true);
      $enc_iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($enc_method));
      $crypted_token = openssl_encrypt($token, $enc_method, $enc_key, 0, $enc_iv) . "::" . bin2hex($enc_iv);
      return $crypted_token;
    } 

2-解密:

function decrypt_val($val){
      $crypted_token = $val;
      if(preg_match("/^(.*)::(.*)$/", $crypted_token, $regs)) {
      list(, $crypted_token, $enc_iv) = $regs;
      $enc_method = 'AES-128-CTR';
      $enc_key = openssl_digest(gethostname() . "|" . $key, 'SHA256', true);
      $decrypted_token = openssl_decrypt($crypted_token, $enc_method, $enc_key, 0, hex2bin($enc_iv));
      return $decrypted_token;
    }
  }

第一个函数将加密输入的字符串,第二个函数将解密它
注意$key是您的密钥,它将用于加密/解密过程


推荐阅读