I want to use openssl_public_encrypt
to encrypt data and store it in a MySQL database. Then, when I need the data, I want to SELECT
it from the MySQL database and use openssl_private_decrypt
to decrypt it. After it is encrypted I am using base64
to encode the data for MySQL and again to decode the data before decrypting it.
Here is the code I am using to encrypt the data and INSERT
it in the database:
<?php
require_once('default.inc.php');
mysql_connect_selectdb($host,$username,$password,$database);
function encrypt($string) {
$publickey = '-----BEGIN PUBLIC KEY-----
PUBLIC KEY HERE
-----END PUBLIC KEY-----';
openssl_public_encrypt($string,$encryptedstring,$publickey);
return $encryptedstring;
}
$number = base64_encode(encrypt('1234567890123456'));
$qry = "UPDATE table SET number='$number' WHERE id='120006'";
$result = mysql_query($qry);
if (!$result) {
die(mysql_error());
}
?>
The default.inc.php
file sets error reporting to E_ALL and also defines the mysql connect variables and the mysql_connect_selectdb()
function. It inserts into the database fine and there is no output to the screen.
Here is the code I am using to SELECT
it from the database and decrypt it:
<?php
require_once('default.inc.php');
mysql_connect_selectdb($host,$username,$password,$database);
$key = '-----BEGIN RSA PRIVATE KEY-----
PRIVATE KEY HERE
-----END RSA PRIVATE KEY-----';
function decrypt($string,$privatekey) {
openssl_private_decrypt($string,$decryptedstring,$privatekey);
return $decryptedstring;
}
$qry = "SELECT * FROM table WHERE id='120006'";
$result = mysql_query($qry);
if ($result) {
if (mysql_numrows($result) == '1') {
$data = mysql_fetch_assoc($result);
$number = decrypt(base64_decode($data['number']),$key);
echo 'Number: '.$number;
}
else {
echo 'no rows';
}
}
else {
die(mysql_error());
}
?>
There is no output to the screen other than Number:
. I can't figure out why it doesn't decrypt. I can echo the $data['number']
straight from the database and it shows up fine as base 64 encoded data and also I can echo the data after it has been base 64 decoded and it shows up fine as binary on my screen, however when I try to decrypt it there is no output.
The MySQL field number is VARCHAR(128)
(have tried VARBINARY
, BINARY
and BLOB
), VARCHAR
should be fine for base64
, and it is a latin1_swedish_ci
collation.
Any help would be greatly appreciated! Thanks!
mysql_*
functions. They're being deprecated. Instead use PDO (supported as of PHP 5.1) or mysqli (supported as of PHP 4.1). If you're not sure which one to use, read this article.