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:

  1. User inserts credit card number.

  2. 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 ----------------------------------------------------

  1. 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 ----------------------------------------------------

  1. Run an select SQL statement to retrieve the data from the MySQL field.

//Start Select ----------------------------------------------------
"SELECT * FROM tblCustomersdata";
//End Select ----------------------------------------------------

  1. 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.

    15 days later

    I am having the exact same problem.

    I can not decrypt, what I've just encrypted.

    Can someone please help?

    Thanks,

      didn't look too close at your code, but what function are you using to encrypt and decrypt into mysql, you could always use the

      ENCODE(str,pass_str)
      Encrypt str using pass_str as the password. To decrypt the result, use DECODE(). The results is a binary string of the same length as string. If you want to save it in a column, use a BLOB column type.

      and

      DECODE(crypt_str,pass_str)
      Descrypts the encrypted string crypt_str using pass_str as the password. crypt_str should be a string returned from ENCODE().

      functions i suppose, there more options here

        13 days later

        Hello,

        Here are some functions I use to encrypt and decrypt data I store
        in a database. Hopefully yhey will be able to give you a bit of help.

        I have also included an example of using it.

        function encrypt($key,$data,$iv) {
        // This function is for encrypting data. You must
        // pass the key, data and iv in order to encrypt
        	// Open the cipher
        	$td = mcrypt_module_open ('rijndael-256', '', 'ofb', '');
        
        // Intialize encryption
        mcrypt_generic_init ($td, $key, $iv);
        
        // Encrypt data and return the results
        return mcrypt_generic ($td, $data);
        
        // Terminate encryption handler and close module
        mcrypt_generic_deinit ($td);
        mcrypt_module_close ($td);
        }
        
        function decrypt($key,$data,$iv) {
        // This function will decrypt the data. You must
        // pass the key, data and iv
        	//Open the cipher 
            $td = mcrypt_module_open ('rijndael-256', '', 'ofb', '');
        
        // Initialize encryption module for decryption
        mcrypt_generic_init ($td, $key, $iv);
        
        // Decrypt encrypted string and return results
        return mdecrypt_generic ($td, $data);
        
        // Terminate decryption handle and close module
        mcrypt_generic_deinit ($td);
        mcrypt_module_close ($td);
        }
        
        function encodekey($newkey) {
            // Open the cipher
            $td = mcrypt_module_open ('rijndael-256', '', 'ofb', '');
        
        // Detrmine key size
        $ks = mcrypt_enc_get_key_size ($td);
        
        // Create key in hash and return
        return $encodekey = substr (md5 ($newkey), 0, $ks);
        
        // Close module
        mcrypt_module_close ($td);
        }
        
        function getiv() {
            $td = mcrypt_module_open ('rijndael-256', '', 'ofb', '');
        
        // Create the IV and return results
        return $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_DEV_RANDOM);
        
        // Close module
        mcrypt_module_close ($td);
        }
        

        To use the above to encrypt this would work:

         
         	// We do need to make an iv and make an encrypted
        	// Key here first
        $mykey = "this is the long key";
        	$iv = getiv();
        	$myenkey = encodekey($mykey);
         	// Lets do some encrypting
        	$encrypted = encrypt($myenkey,$mydata,$iv);
        
        // Lets connect to the database
        $connect = mysql_connect($host,$username,$password) or die("Unable to connect");
        mysql_select_db($database);
        $query = "INSERT INTO $tbl(pass, data, iv) VALUES('$myenkey', '$encrypted', '$iv')";
        
        // Lets add the stuff to the database
        mysql_query($query) or die("Could not insert");
        

        Here is how you can decrypt the data:

        		// Lets encode the password to test it
        		$passchk = encodekey($enkey);
        
        	// Lets connect to the database
        	$connect = mysql_connect($host,$username,$password) or die("Unable to connect");
        	mysql_select_db($database);
        	$query = "SELECT * FROM $tbl WHERE id = '$endata' and pass = '$passchk'";
        
        	// Lets add the stuff to the database
        	$result = mysql_query($query) or die("Could not insert");
        	$getit = mysql_fetch_array($result);
        	if(!$getit) {
        		echo "You entered the wrong information please try again";
        	}else{
        		// Now lets decode this information
        		$decoded = decrypt($getit['pass'],$getit['data'],$getit['iv']);
        		echo $decoded;
        	}
        

        In the above example you the var $enkey would be supplied as the
        original key used to encrypt the data. You could change the
        $query string to find the record anyway you want.

        I hope this helps you in your search. If someone sees how this can
        be used better please let me know. I edited the above due to an error I found.

        Regards,
        Ray

          Write a Reply...