其实只用过2次3des,也都是网上找的,查php的官方手册。以下是我整理的,比较清晰。
主要是看加密模式和填充模式比如 DESede/ECB/NoPadding
填充模式常用的有pkcs5和pkcs7
nopadding无填充模式:
function descrypt($data, $key)
{
$algorithm = MCRYPT_TRIPLEDES;
$mcryptMode = MCRYPT_MODE_ECB;
$source = MCRYPT_RAND;
$ivSize = mcrypt_get_iv_size($algorithm, $mcryptMode);
$iv = mcrypt_create_iv($ivSize, $source);
$data = pack("H*",$data);
$plainText = mcrypt_decrypt($algorithm, $key, $data, $mcryptMode, $iv);
return $plainText;
}
function encrypt($key, $data)
{
$algorithm = MCRYPT_TRIPLEDES;
$mcryptMode = MCRYPT_MODE_ECB;
$source = MCRYPT_RAND;
$ivSize = mcrypt_get_iv_size($algorithm, $mcryptMode);
$iv = mcrypt_create_iv($ivSize, $source);
$encryptedString = mcrypt_encrypt($algorithm, $key, $data, $mcryptMode, $iv);
$encryptedString = bin2hex($encryptedString);
return $encryptedString;
}
$result = bin2hex($str)的作用是将$str字符串变量的ASCII码值(即二进制形式)转换为十六进制形式
要将最终结果转换回来,方法是pack("H*",$result);
pkcs5模式填充:function descrypt($data, $key)
{
$algorithm = MCRYPT_TRIPLEDES;
$mcryptMode = MCRYPT_MODE_ECB;
$source = MCRYPT_RAND;
$ivSize = mcrypt_get_iv_size($algorithm, $mcryptMode);
$iv = mcrypt_create_iv($ivSize, $source);
$data = pack("H*",$data);
$plainText = mcrypt_decrypt($algorithm, $key, $data, $mcryptMode, $iv);
$plainText = pkcs5Unpad($plainText);
return $plainText;
}
function encrypt($key, $data)
{
$algorithm = MCRYPT_TRIPLEDES;
$mcryptMode = MCRYPT_MODE_ECB;
$source = MCRYPT_RAND;
$ivSize = mcrypt_get_iv_size($algorithm, $mcryptMode);
$iv = mcrypt_create_iv($ivSize, $source);
$data = pkcs5Pad($data, $ivSize);
$encryptedString = mcrypt_encrypt($algorithm, $key, $data, $mcryptMode, $iv);
$encryptedString = bin2hex($encryptedString);
return $encryptedString;
}
function pkcs5Pad ($text, $ivSize)
{
$pad = $ivSize - (strlen($text) % $ivSize);
return $text . str_repeat(chr($pad), $pad);
}
function pkcs5Unpad($text) {
$pad = ord($text{strlen($text)-1});
if ($pad > strlen($text)) return false;
if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return false;
return substr($text, 0, -1 * $pad);
}
pkcs7模式填充和5类似,关键的填充如下:
function pkcs7Pad($data, $ivSize)
{
$paddingChar = $ivSize - (strlen($data) % $ivSize);
$data .= str_repeat(chr($paddingChar), $paddingChar);
return $data;
}
function pkcs7Unpad($text)
{
$pad = ord($text{strlen($text) - 1});
if ($pad > strlen($text)) {
return false;
}
if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) {
return false;
}
return substr($text, 0, -1 * $pad);
}