如何使用MySQL查询解密openssl_encrypt()加密值?

时间:2019-01-15 10:12:33

标签: php mysql encryption pdo aes

如果我使用以下PHP脚本加密数据库中的字段:

<?php
require_once('../api.php');

$newApi = new api();
$conn = $newApi->connection();

//$key previously generated safely, ie: openssl_random_pseudo_bytes
$plaintext = "Test";
$key="testKey";
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext_raw = openssl_encrypt($plaintext, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
$ciphertext = base64_encode( $iv.$hmac.$ciphertext_raw );

echo $ciphertext;
$sql = 'INSERT INTO test(encName) VALUES(:enc)';
$exec=$conn->prepare($sql);
$exec->bindValue(':enc', $ciphertext);
$exec->execute();

echo "\n";
$c = base64_decode($ciphertext);
$hmac = substr($c, $ivlen, $sha2len=32);
$ciphertext_raw = substr($c, $ivlen+$sha2len);
$original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
$calcmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
if (hash_equals($hmac, $calcmac))//PHP 5.6+ timing attack safe comparison
{
    echo $original_plaintext."\n";
}

$sql = "SELECT aes_decrypt(encName, 'testKey') FROM test";
$exec = $conn->prepare($sql);
$exec->execute();
$res=$exec->fetchAll();
foreach($res as $result)
{
    print_r($result);
    echo "\n";
}

如您所见,我曾经使用过:

SELECT aes_decrypt(encName, 'testKey') FROM test

检索原始名称。但这没有用。显然,openssl_encrypt()在MySQL中没有任何等效项。

我试图理解这个example

  

在mysql中,全长密钥由AES_ENCRYPT()和   AES_DECRYPT()

SELECT 
HEX(AES_ENCRYPT('testvalue',UNHEX(SHA2('mysecretphrase',512)))) AS l_full,
HEX(AES_ENCRYPT('testvalue',SUBSTR(UNHEX(SHA2('mysecretphrase',512)),1,16)))

AS l_16,
HEX(AES_ENCRYPT('testvalue',SUBSTR(UNHEX(SHA2('mysecretphrase',512)),1,15)))

AS l_15;

但是关键是要使用PHP进行加密,然后使用PHP或MYSQL进行解密。

如何使用MySQL查询检索字段encName的原始值?我是否在MySQL查询中使用aes_encrypt()和crypto()的第二种方法?

0 个答案:

没有答案