PHP的DES加密和RSA签名
时间:2015-06-17 阅读:次 QQ群:182913345
主要用于php对接java的接口
rsa签名用SHA1WithRSA算法
<?php /** * DES加密/解密,RSA加密/验签 */ class Crypt{ // DES加密 public function encrypt($str,$key){ $block = mcrypt_get_block_size('des', 'ecb'); $pad = $block - (strlen($str) % $block); $str .= str_repeat(chr($pad), $pad); $str = mcrypt_encrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB); return base64_encode($str); } // DES解密 public function decrypt($str,$key){ $str = base64_decode($str); $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); } // RSA签名(SHA1WithRSA算法) public function sign($content,$rsaPrivateKeyPem){ $priKey = file_get_contents($rsaPrivateKeyPem); $res = openssl_get_privatekey($priKey); openssl_sign($content, $sign, $res); openssl_free_key($res); $sign = base64_encode($sign); return $sign; } // RSA验签 public function verify($data,$sign,$publicRsaPath){ //读取公钥文件 $pubKey = file_get_contents($publicRsaPath); //转换为openssl格式密钥 $res = openssl_get_publickey($pubKey); //调用openssl内置方法验签,返回bool值 $result = (bool)openssl_verify($data, base64_decode($sign), $res); //释放资源 openssl_free_key($res); //返回资源是否成功 return $result; } } |
上一篇:php常用的header头
下一篇:ThinkPHP分页实例