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?