Skip to content

Instantly share code, notes, and snippets.

@joeolaoye
Created May 23, 2016 14:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joeolaoye/9dcaf3ef041624df26b0a0385548f923 to your computer and use it in GitHub Desktop.
Save joeolaoye/9dcaf3ef041624df26b0a0385548f923 to your computer and use it in GitHub Desktop.
An encryption/decryption code in PHP
public function encrypt3Des($data, $key)
{
//Generate a key from a hash
$key = md5(utf8_encode($key), 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 = $data.str_repeat(chr($pad), $pad);
//Encrypt data
$encData = mcrypt_encrypt('tripledes', $key, $data, 'ecb');
//return $this->strToHex($encData);
return base64_encode($encData);
}
public function decrypt3Des($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);
$data = base64_decode($data);
$data = mcrypt_decrypt('tripledes', $key, $data, 'ecb');
$block = mcrypt_get_block_size('tripledes', 'ecb');
$len = strlen($data);
$pad = ord($data[$len-1]);
return substr($data, 0, strlen($data) - $pad);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment