Summary
How can I insert an encrypted credit card number into a MySQL database, then retrieve the encrypted credit card number from the MySQL field and decrypt it for display?
Details
In pesudo code, this is what I have wrote:
User inserts credit card number.
Initialize "mycrypt" with mcrypt_module_open to encrypt the data, then save value to a variable.
//Start Crypt ----------------------------------------------------
$vardecryptPayment = $_POST['cardnumber'];
$key = 'this is a very long key';
$plain_text = trim($vardecryptPayment);
$td = mcrypt_module_open ('des', '', 'ecb', '');
$key = substr ($key, 0, mcrypt_enc_get_key_size ($td));
$iv_size = mcrypt_enc_get_iv_size ($td);
$iv = mcrypt_create_iv ($iv_size, MCRYPT_RAND);
if (mcrypt_generic_init ($td, $key, $iv) != -1) {
$mcrypted_cc_number = mcrypt_generic ($td, $plain_text);
mcrypt_generic_deinit ($td);
mcrypt_module_close ($td);
}
//End Crypt ----------------------------------------------------
- Run an insert SQL statement to insert the data into the MySQL field, noting that the field must be "tinyblob or tinytext" type, since encrypted data can end in a space.
//Start Insert ----------------------------------------------------
"INSERT INTO tblCustomersdata(cardnumber) VALUES ('$vardecryptPayment')";
//End Insert ----------------------------------------------------
- Run an select SQL statement to retrieve the data from the MySQL field.
//Start Select ----------------------------------------------------
"SELECT * FROM tblCustomersdata";
//End Select ----------------------------------------------------
- Initialize "mycrypt" with mcrypt_module_open again to decrypt the data, then save value to a variable to be displayed on a different page.
//Start DeCrypt ----------------------------------------------------
$key = 'this is a very long key';
$plain_text = $row_rsGet_tblCustomersdata['payment'];
$td = mcrypt_module_open ('des', '', 'ecb', '');
$key = substr ($key, 0, mcrypt_enc_get_key_size ($td));
$iv_size = mcrypt_enc_get_iv_size ($td);
$iv = mcrypt_create_iv ($iv_size, MCRYPT_RAND);
if (mcrypt_generic_init ($td, $key, $iv) != -1) {
mcrypt_generic_init ($td, $key, $iv);
$demcrypted_cc_number = mdecrypt_generic($td, $plain_text);
mcrypt_generic_deinit ($td);
mcrypt_module_close ($td);
}
//End DeCrypt ----------------------------------------------------
Issues
I am able to successfully encrypt the data and insert it into the MySQL field, view the data encrypted in the MySQL field, then retrieve the data from the database.
However I am unable to decrypt the data, when I run the decrypt script, I get a short string value of garbage characters that do not relate in any possible way.
Any suggests would be recommended or any direction on what I need to do different would be appreciated.
(Please, note I have thought about using the MySQL encode function, however I would like to accomplish this with PHP.)
Thank you.