PHP Encrypt/Decrypt with TripleDes, PKCS7, and ECB
- by Brandon Green
I've got my encryption function working properly however I cannot figure out how to get the decrypt function to give proper output.
Here is my encrypt function:
function Encrypt($data, $secret)
{
//Generate a key from a hash
$key = md5(utf8_encode($secret), true);
//Take first 8 bytes of $key and append them to the end of $key.
$key .= substr($key, 0, 8);
//Pad for PKCS7
$blockSize = mcrypt_get_block_size('tripledes', 'ecb');
$len = strlen($data);
$pad = $blockSize - ($len % $blockSize);
$data .= str_repeat(chr($pad), $pad);
//Encrypt data
$encData = mcrypt_encrypt('tripledes', $key, $data, 'ecb');
return base64_encode($encData);
}
Here is my decrypt function:
function Decrypt($data, $secret)
{
$text = base64_decode($data);
$data = mcrypt_decrypt('tripledes', $secret, $text, 'ecb');
$block = mcrypt_get_block_size('tripledes', 'ecb');
$pad = ord($data[($len = strlen($data)) - 1]);
return substr($data, 0, strlen($data) - $pad);
}
Right now I am using a key of test and I'm trying to encrypt 1234567. I get the base64 output from encryption I'm looking for, but when I go to decrypt I get a blank response.
I'm not very well versed in encryption/decryption so any help is much appreciated!!