最近项目和java对接,涉及到java的DESede加解密算法

google后找到这个作者的一篇博客,搬过来用

http://hersface.com/page/17.html

 

<?php 
class DESede{
/**
* 加密
* @param $data 待加密明文
* @param $key DES私钥
* @param $use3des 是否启用3DES加密,默认不启用
*/
function encrypt($data='', $key='', $use3des = False)
{
if (empty($data) || empty($key))
{
return False;
}
$cipher = $use3des ? MCRYPT_TRIPLEDES : MCRYPT_DES;
$modes = MCRYPT_MODE_ECB;
# Add PKCS7 padding.
$block = mcrypt_get_block_size($cipher, $modes);
$pad = $block - (strlen($data) % $block);
$data .= str_repeat(chr($pad), $pad);
$iv = mcrypt_create_iv(mcrypt_get_iv_size($cipher, $modes), MCRYPT_RAND);
$encrypted = @mcrypt_encrypt($cipher, $key, $data, $modes, $iv);
return $encrypted;
}
/**
* 解密
* @param $data 待解密密文
* @param $key DES私钥
* @param $use3des 是否启用3DES加密,默认不启用
*/
function decrypt($data='', $key='', $use3des = False)
{
if (empty($data) || empty($key))
{
return False;
}
$cipher = $use3des ? MCRYPT_TRIPLEDES : MCRYPT_DES;
$modes = MCRYPT_MODE_ECB;
$iv = mcrypt_create_iv(mcrypt_get_iv_size($cipher, $modes), MCRYPT_RAND);
$data = @mcrypt_decrypt($cipher, $key, $data, $modes, $iv);
# Strip padding out.
$block = mcrypt_get_block_size($cipher, $modes);
$pad = ord($data[($len = strlen($data)) - 1]);
$decrypted = substr($data, 0, strlen($data) - $pad);
return $decrypted;
}
}
$des=new DESede();

$rs=$des->encrypt('中国人','1',true);
echo '<meta http-equiv="Content-Type" content="text/html; charset=utf8">';
echo base64_encode($rs);

 

posted @ 2016-09-01 10:44  liugx  阅读(819)  评论(0编辑  收藏  举报