PHP openssl非对称加密
程序员文章站
2024-03-16 20:24:34
...
关于秘钥的生成方式请查看:https://blog.csdn.net/liujihaozhy/article/details/79781468
非对称加密,将生成的公钥提供给外部开发人员,生成的私钥不要泄露
代码如下:
<?php
/**
* @uses openssl非对称加密
* @author jhl
*
*/
class OpensslAuthcode {
//公钥文件地址
private $certPublicUrl;
//私钥文件地址
private $certPrivateUrl;
public function __construct()
{
$this->certPublicUrl = __DIR__ . "/opensslkey/cert_public.pem";
$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) {
$encrypt_data = '';
$pp = self::getPublicKey();
$pubkey = openssl_pkey_get_public($pp);
openssl_public_encrypt($string, $encrypt_data, $pubkey);
$encrypt_data = base64_encode($encrypt_data);
return $encrypt_data;
}
/**
*
* @uses 解密
* @author jhl
* @param string $string
* @return string
*/
public function decrypt($string) {
// 私钥解密
$encrypt_data = base64_decode($string);
$prikey = openssl_pkey_get_private(self::getPrivateKey());
openssl_private_decrypt($encrypt_data, $decrypt_data, $prikey);
return $decrypt_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;
}
}
上一篇: 点在三角形中的测试
下一篇: JDBC与Oracle存储过程