1

If I am using the following PHP script to encrypt a field in my database:

<?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";
}

As you see, I used:

SELECT aes_decrypt(encName, 'testKey') FROM test

to retrieve the original name. But it didn't work. Apparently, openssl_encrypt() doesn't have any equivalent in MySQL.

I tried to understand this example:

In mysql the full length key is used by AES_ENCRYPT() and 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;

But the point is to encrypt using PHP and decrypt using PHP or MYSQL.

How to retrieve the original value of the field encName using a MySQL query? And do I use the second method where I used aes_encrypt() and decrypt() inside the MySQL query?

Sayed Mohd Ali
  • 2,156
  • 3
  • 12
  • 28
am909090
  • 83
  • 1
  • 7
  • Hash the contents or use another key before encryption if you need to have a id field for querying, then decrypt using php rather than mysql. – David Lemon Jan 15 '19 at 11:07
  • No. Sometimes I need to search by name. – am909090 Jan 15 '19 at 11:08
  • 1
    Encrypting or output format are different between openssl and mysq, so you cannot just interchange them. https://www.smashingmagazine.com/2012/05/replicating-mysql-aes-encryption-methods-with-php/ – gusto2 Jan 16 '19 at 10:53

0 Answers0