公钥,私钥文件需要在Linux下生成!
相关命令:
私钥:
openssl genrsa -out rsa_private_key.pem 1024
公钥:
openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
代码如下:
<?php
/**
* @uses openssl加密解密
* @author jhl
*
*/
class OpensslAuthcode {
//公钥文件地址
private $certPublicUrl;
//私钥文件地址
private $certPrivateUrl;
public function __construct()
{
$this->certPublicUrl = __DIR__ . "/opensslkey/cert_public.key";
$this->certPrivateUrl = __DIR__ . "/opensslkey/cert_private.pem";
}
/**
*
* @uses 生成证书文件
* @author jhl
* @return file
*/
public function exportOpenSSLFile() {
$config = [
'digest_alg' => 'sha512',
'private_key_bits' => 4096,
'private_key_type' => OPENSSL_KEYTYPE_RSA
];
$res = openssl_pkey_new ( $config );
if ($res == false) {
return false;
}
openssl_pkey_export ( $res, $private_key );
$public_key = openssl_pkey_get_details ( $res );
$public_key = $public_key ['key'];
file_put_contents ( $this->certPublicUrl, $public_key );
file_put_contents ( $this->certPrivateUrl, $private_key );
openssl_free_key ( $res );
}
/**
*
* @uses 加密
* @author jhl
* @param string $string
* @return string
*/
public function encrypt($string) {
$sslPublic = self::getPublicKey();
$sslPrivate = self::getPrivateKey();
$privateKey = openssl_pkey_get_private ( $sslPrivate );
$publicKey = openssl_pkey_get_public ( $sslPublic );
if (false == ($privateKey || $publicKey)) {
return 'certificate error!!';
}
openssl_public_encrypt ( $string, $data, $publicKey );
$data = base64_encode ( $data );
return $data;
}
/**
*
* @uses 解密
* @author jhl
* @param string $string
* @return string
*/
public function decrypt($string) {
$sslPublic = self::getPublicKey();
$sslPrivate = self::getPrivateKey();
$privateKey = openssl_pkey_get_private ( $sslPrivate );
$publicKey = openssl_pkey_get_public ( $sslPublic );
if (false == ($privateKey || $publicKey)) {
return 'certificate error!!';
}
openssl_private_decrypt ( base64_decode ( $string ), $data, $privateKey );
return $data;
}
/**
*
* @uses 获取公钥
* @author jhl
* @param string $string
* @return string
*/
private function getPublicKey()
{
static $sslPublicKey;
if (!$sslPublicKey) {
$sslPublicKey = file_get_contents ( $this->certPublicUrl );
}
return $sslPublicKey;
}
/**
*
* @uses 获取私钥
* @author jhl
* @param string $string
* @return string
*/
private function getPrivateKey()
{
static $sslPrivateKey;
if (!$sslPrivateKey) {
$sslPrivateKey = file_get_contents ( $this->certPrivateUrl );
}
return $sslPrivateKey;
}
}