转:PHP的DES加解密函数 与JAVA兼容


PHP可以使用mcrypt_encrypt进行DES加密与解密,但实际上操作,你会发现它与JAVA的DES加密出来的字符串,有些不同。基本上是前半段一样,后半段不一样。找到PHP官方网站上对这个函数的文档,有人回复了,并给出了代码。经测,这样加密解密就跟JAVA中的兼容了。

If you want to be interoperable with other PKCS #7 padding implementations, like the Legion of the Bouncy Castle Java cryptography APIs, you should always pad, that is a 8-byte (block size) padding should be added, even if not necessary

function encrypt($str, $key) {
    $block = mcrypt_get_block_size(MCRYPT_DES, MCRYPT_MODE_ECB);
    $pad = $block - (strlen($str) % $block);
    $str .= str_repeat(chr($pad), $pad);
    return mcrypt_encrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB);
}

/**
 * 解密
 * @param $str
 * @param $key
 * @return string
 */
function decrypt($str, $key) {
    $str = mcrypt_decrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB);
    //$block = mcrypt_get_block_size('des', 'ecb');
    $pad = ord($str[($len = strlen($str)) - 1]);
    return substr($str, 0, strlen($str) - $pad);
}

$key = '12345678';
$data = 'hello world!!!Hello China!!!';

$en_str = encrypt($data,$key);
echo base64_encode($en_str)."\n";

echo decrypt($en_str,$key)."\n";

http://it.oyksoft.com/post/4831/

普人特福的博客cnzz&51la for wordpress,cnzz for wordpress,51la for wordpress