PHP5.3 DES CBC多个版本实现方式@TOC
php DES CBC 多个版本实现
php7.1以后已经废弃mcrypt 更换为openssl,实现起来更加简洁
php 5.3 mcrypt
function decode($str, $key) {
$strBin = base64_decode($str);
$str = mcrypt_cbc(MCRYPT_DES, $key, $strBin, MCRYPT_DECRYPT, $key);
$str = pkcs5Unpad($str);
return $str;
}
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);
}
function encode($str, $key) {
$size = mcrypt_get_block_size(MCRYPT_DES, MCRYPT_MODE_CBC);
$str = pkcs5Pad($str, $size);
$aaa = mcrypt_cbc(MCRYPT_DES, $key, $str, MCRYPT_ENCRYPT, $key);
$ret = base64_encode($aaa);
return $ret;
}
function pkcs5Pad($text, $blocksize) {
$pad = $blocksize - (strlen($text) % $blocksize);
return $text . str_repeat(chr($pad), $pad);
}
php 5.6 mcrypt
function decode($str, $key) {
$strBin = base64_decode($str);
$str = mcrypt_decrypt( MCRYPT_DES, $key, $strBin, MCRYPT_MODE_CBC, $key );
$str = pkcs5Unpad($str);
return $str;
}
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);
}
function encode($str, $key) {
$size = mcrypt_get_block_size(MCRYPT_DES, MCRYPT_MODE_CBC);
$str = pkcs5Pad($str, $size);
$aaa = mcrypt_encrypt ( MCRYPT_DES, $key, $str, MCRYPT_MODE_CBC, $key );
$ret = base64_encode($aaa);
return $ret;
}
function pkcs5Pad($text, $blocksize) {
$pad = $blocksize - (strlen($text) % $blocksize);
return $text . str_repeat(chr($pad), $pad);
}
php openssl
function openssl_encode($str, $key){
$result = openssl_encrypt($str, 'DES-CBC', $key, OPENSSL_RAW_DATA, $key);
return base64_encode($result);
}
function openssl_decode($str, $key){
$data = base64_decode($str);
return openssl_decrypt($data, 'DES-CBC', $key, OPENSSL_RAW_DATA, $key);
}
例子
$data = '但愿风雨至,吾亦留如此';
$keyT="9781e7b5";
$encrypt_data = encode($data,$keyT);
$decrypt_data = decode($encrypt_data,$keyT);
$encrypt_data1 = openssl_encode($data,$keyT);
$decrypt_data2 = openssl_decode($encrypt_data1,$keyT);
echo "<pre>";
var_dump([$encrypt_data,$decrypt_data,$encrypt_data1,$decrypt_data2]);die;
array(4) {
[0]=>
string(44) "KZ/s6vMTVjhttBskejYsfkCpEtQJoEg4g8RROyb6cC8="
[1]=>
string(31) "但愿风雨至,吾亦留如此"
[2]=>
string(44) "KZ/s6vMTVjhttBskejYsfkCpEtQJoEg4g8RROyb6cC8="
[3]=>
string(31) "但愿风雨至,吾亦留如此"
}
|