Credit Card Encryption And Decryption Php Using Mcrypt Module


Below are the encryption and decryption functions. Pass your credit card number in string format to the encryptCard function and you will get the encrypted code which you can safely store in your database. The important thing here is the KEY. Define a secret string as the $key value which is needed to decrypt the data back to the original value.

function encryptCard($creditno){
$key = ‘YOURSECRETKEY’; //Change the key here
$td = mcrypt_module_open(‘tripledes’, ”, ‘cfb’, ”);
srand((double) microtime() * 1000000);
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
$okey = substr(md5($key.rand(0, 9)), 0, mcrypt_enc_get_key_size($td));
mcrypt_generic_init($td, $okey, $iv);
$encrypted = mcrypt_generic($td, $creditno.chr(194));
$code = $encrypted.$iv;
$code = eregi_replace(“‘”, “‘”, $code);
return $code;

function decryptCard($code){
$key = ‘YOURSECRETKEY’; // use the same key used for encrypting the data
$td = mcrypt_module_open(‘tripledes’, ”, ‘cfb’, ”);
$iv = substr($code, -8);
$encrypted = substr($code, 0, -8);
for ($i = 0; $i < 10; $i++) {
$okey = substr(md5($key.$i), 0, mcrypt_enc_get_key_size($td));
mcrypt_generic_init($td, $okey, $iv);
$decrypted = trim(mdecrypt_generic($td, $encrypted));
$txt = substr($decrypted, 0, -1);
if (ord(substr($decrypted, -1)) == 194 && is_numeric($txt)) break;
return $txt;

I suggest storing the encrypted data in a BLOB field in your MySQL database, which is similar to a TEXT but BLOB stores text string as a binary data. Sorting and comparison is performed in case-sensitive fashion for BLOB values and case-insensitive fashion for TEXT values. BLOB values have no character set, and sorting and comparison are based on the numeric values of the bytes in column values. Hence, a direct string match is not possible in a BLOB field.

Source by Anees Madathil