您好,欢迎访问一九零五行业门户网

PHP实现非对称加密

非对称加密
至于什么是非对称加密,这里就不说啦,大家谷歌去吧。这里说明的是,最近在做一个对外的充值加密服务,那么涉及到这个加密的处理,中间遇到几个小问题,所以记录下,方便自己下次查阅。
详细代码 _keypath = $path; } /** * 创建公钥和私钥 * */ public function createkey() { $config = [ config => 'd:\wamp\bin\apache\apache2.4.9\conf\openssl.cnf', digest_alg => sha512, private_key_bits => 4096, private_key_type => openssl_keytype_rsa, ]; // 生成私钥 $rsa = openssl_pkey_new($config); openssl_pkey_export($rsa, $privkey, null, $config); file_put_contents($this->_keypath . directory_separator . 'priv.key', $privkey); $this->_privkey = openssl_pkey_get_public($privkey); // 生成公钥 $rsapri = openssl_pkey_get_details($r); $pubkey = $rsapri['key']; file_put_contents($this->_keypath . directory_separator . 'pub.key', $pubkey); $this->_pubkey = openssl_pkey_get_public($pubkey); } /** * 设置私钥 * */ public function setupprivkey() { if (is_resource($this->_privkey)) { return true; } $file = $this->_keypath . directory_separator . 'priv.key'; $privkey = file_get_contents($file); $this->_privkey = openssl_pkey_get_private($privkey); return true; } /** * 设置公钥 * */ public function setuppubkey() { if (is_resource($this->_pubkey)) { return true; } $file = $this->_keypath . directory_separator . 'pub.key'; $pubkey = file_get_contents($file); $this->_pubkey = openssl_pkey_get_public($pubkey); return true; } /** * 用私钥加密 * */ public function privencrypt($data) { if (!is_string($data)) { return null; } $this->setupprivkey(); $result = openssl_private_encrypt($data, $encrypted, $this->_privkey); if ($result) { return base64_encode($encrypted); } return null; } /** * 私钥解密 * */ public function privdecrypt($encrypted) { if (!is_string($encrypted)) { return null; } $this->setupprivkey(); $encrypted = base64_decode($encrypted); $result = openssl_private_decrypt($encrypted, $decrypted, $this->_privkey); if ($result) { return $decrypted; } return null; } /** * 公钥加密 * */ public function pubencrypt($data) { if (!is_string($data)) { return null; } $this->setuppubkey(); $result = openssl_public_encrypt($data, $encrypted, $this->_pubkey); if ($result) { return base64_encode($encrypted); } return null; } /** * 公钥解密 * */ public function pubdecrypt($crypted) { if (!is_string($crypted)) { return null; } $this->setuppubkey(); $crypted = base64_decode($crypted); $result = openssl_public_decrypt($crypted, $decrypted, $this->_pubkey); if ($result) { return $decrypted; } return null; } /** * __destruct * */ public function __destruct() { @fclose($this->_privkey); @fclose($this->_pubkey); }}?>
测试 $rsa = new rsa('ssl-key');//私钥加密,公钥解密echo 待加密数据:segmentfault.com\n;$pre = $rsa->privencrypt(segmentfault.com);echo 加密后的密文:\n . $pre . \n;$pud = $rsa->pubdecrypt($pre);echo 解密后数据: . $pud . \n;//公钥加密,私钥解密echo 待加密数据:segmentfault.com\n;$pue = $rsa->pubencrypt(segmentfault.com);echo 加密后的密文:\n . $pue . \n;$prd = $rsa->privdecrypt($pue);echo 解密后数据: . $prd;
重要问题 这里特别要注意的是在配置中要指定openssl.cnf的文件地址,或者设置个openssl_conf全局变量就可以了。
其它类似信息

推荐信息