php 3DES|DES 加密解密(通用)
程序员文章站
2024-03-14 10:40:28
...
phpseclib
<?php
//set_include_path(get_include_path().PATH_SEPARATOR.'phpseclib');
include('Crypt/DES.php');
$des = new Crypt_DES();
$des->setKey('abcdefgh');
$plaintext = 'a';
$jiami = base64_encode($des->encrypt($plaintext));
echo "Encode:".$jiami."<br/>";
echo "Decode:".$des->decrypt(base64_decode($jiami));
?>
由于PHP使用mcrypt扩展进行3DES加密,填充模式是跟JAVA以及.NET是不一样的,JAVA和.NET填充模式使用的是PKCS7。
所以PHP端必须自定义一个函数对加密字符串进行PKCS7模式补位填充 。
另外一点就是双方的KEY注意进行base64编码,最后PHP端经过3DES加密后得到的结果也需要进行base64编码。
以上几点都做好之后,加密结果就一致了。
再谷歌一番发现这么一段代码(原作者“幻想曲.NET”),实现了上述规则,这个3DES加密类兼容.net 和java :
<?php
class STD3Des
{
private $key = "";
private $iv = "";
/**
* 构造,传递二个已经进行base64_encode的KEY与IV
*
* @param string $key
* @param string $iv
*/
function __construct($key, $iv)
{
if (empty($key) || empty($iv)) {
echo 'key and iv is not valid';
exit();
}
$this->key = $key;
$this->iv = $iv;
}
/**
*加密
* @param <type> $value
* @return <type>
*/
public function encrypt($value)
{
$td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');
$iv = base64_decode($this->iv);
$value = $this->PaddingPKCS7($value);
$key = base64_decode($this->key);
mcrypt_generic_init($td, $key, $iv);
$ret = base64_encode(mcrypt_generic($td, $value));
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $ret;
}
/**
*解密
* @param <type> $value
* @return <type>
*/
public function decrypt($value)
{
$td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');
$iv = base64_decode($this->iv);
$key = base64_decode($this->key);
mcrypt_generic_init($td, $key, $iv);
$ret = trim(mdecrypt_generic($td, base64_decode($value)));
$ret = $this->UnPaddingPKCS7($ret);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $ret;
}
private function PaddingPKCS7($data)
{
$block_size = mcrypt_get_block_size('tripledes', 'cbc');
$padding_char = $block_size - (strlen($data) % $block_size);
$data .= str_repeat(chr($padding_char), $padding_char);
return $data;
}
private function UnPaddingPKCS7($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);
}
}
//使用
include('STD3Des.class.php');
$key = 'abcdefgh';
$iv = 'abcdefgh';
$msg = 'test string';
$des = new STD3Des(base64_encode($key), base64_encode($iv));
$rs1 = $des->encrypt($msg);
echo $rs1 . '<br />';
$rs2 = $des->decrypt($rs1);
echo $rs2;
?>