基本使用
代码
"sha512",
"private_key_bits" => 2048, //字节数 512 1024 2048 4096 等 ,不能加引号,此处长度与加密的字符串长度有关系,可以自己测试一下
"private_key_type" => OPENSSL_KEYTYPE_RSA, //加密类型
);
$resource = openssl_pkey_new($config);
//提取私钥
openssl_pkey_export($resource, $privateKey);
//生成公钥
$publicKey = openssl_pkey_get_details($resource)['key'];
echo '------------------创建私钥---------------------' . PHP_EOL;
echo $privateKey.PHP_EOL;
echo '------------------创建公钥---------------------' . PHP_EOL;
echo $publicKey.PHP_EOL;
// 加密后内容含有特殊字符,需编码转换
//从证书中提取公钥
$publicKey = openssl_pkey_get_public($publicKey);
//从证书中提取私钥
$privateKey = openssl_pkey_get_private($privateKey); // 提取成功返回资源标识,错误返回false is_resource($publicKey)
//原始数据
$data = '{"name":"xiaoming","age":"23","address":"beijing"}';
//加密
$encrypted = "";
//解密
$decrypted = "";
echo '原始数据:' . PHP_EOL . $data . PHP_EOL;
//私钥加密,公钥解密
echo '------------------私钥加密,公钥解密---------------------' . PHP_EOL;
//私钥加密
openssl_private_encrypt($data, $encrypted, $privateKey);
//加密后内容含有特殊字符,需编码转换
$encrypted = base64_encode($encrypted);
echo '私钥加密:' . PHP_EOL, $encrypted . PHP_EOL;
//公钥解密
openssl_public_decrypt(base64_decode($encrypted), $decrypted, $publicKey);
echo '公钥解密:' . PHP_EOL, $decrypted . PHP_EOL;
//公钥加密,私钥解密
echo '------------------公钥加密,私钥解密---------------------' . PHP_EOL;
//加密后内容含有特殊字符,需编码转换
openssl_public_encrypt($data, $encrypted, $publicKey);
$encrypted = base64_encode($encrypted);
echo '公钥加密:' . PHP_EOL, $encrypted . PHP_EOL;
openssl_private_decrypt(base64_decode($encrypted), $decrypted, $privateKey);//私钥解密
echo '私钥解密:' . PHP_EOL, $decrypted . PHP_EOL;
//释放key关联秘钥
openssl_free_key($publicKey);
openssl_free_key($privateKey);
打印结果
------------------创建私钥---------------------
-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhk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EkKeT+cP17t4S7k3
C5OVY4m2XnMCgYA5RfAM2A2tc3EW0DGg7hRVgnkUpXyReLykeBny2WZCVDgyoja5
ySDESmJ8fDoGV8fFWaufBPMip0Qy6p4JgdMLMJJNeTyEhM2t8me6PDF1IVPWPRpf
eMx/IBJBEZSN87HHCWAyqBlOV0aH+86zgMWCYYaZ49Xwq/xYFMF+ey+7iQKBgAgR
YgVW1FIg4KQplFsTckHwmJzZDyUuoTZ6jSKiPKYUrJNb43bBjNXcQ+wnU7FY+OQu
TwRAP25NtjgnSaAXDbzeaBh+T36jrKoPhJWRdHyD6pHE7Qg/O+CPfqM8EMjPo5Tn
Wbnwj8Dc/l63kaYweph5l1/OsDmQZjNc2ijlg+arAoGBAK7Re38ZEYtnC7MSLHIx
I7nJefrPw9SAkzkQ6CgH05hjwTXegM6f/c9pdg/qmA7cudNW1r9i6gRb+cp3ek18
tEuI9NjNzlkS7HT1CeV51rSc6QfOLfz2a7i0Co9nmzaP5JKXIgnUDh8mBLMjTRfU
NcQ17ebXueTF9MsgamrBt18S
-----END PRIVATE KEY-----
------------------创建公钥---------------------
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3XvjGXNxk3sn7jzwQwa2
Qb/aojB5KZdmiztuVZlYpa4yL3RaBpSzteY6n1oc5j7SKJO2GOmjVewk1Ik1v0A/
CkW7BUANAJ4zfIiEqLEzEOyNnEOwzlHLkPWSYQrB+yXZnWfbeiQOnqZdD0i/Oyyc
FD/xeskrRTqQ2RJ6oSXuyjiJqf3io6vd+8qywkz9YjxeIlBYT8GpDfXDpyxOOCQV
T0/7J46cg5RWT7YvrLly7HHdE3eikLxpgjNzKTmw5hLE3R6UknNO8jIhD4ocdw1a
InCUYzh3YAcLDXMYDwl0U5tymfQdW7emiBKBzFWllAH+uADMRKOVpOrblTylGNEI
5QIDAQAB
-----END PUBLIC KEY-----
原始数据:
{"name":"xiaoming","age":"23","address":"beijing"}
------------------私钥加密,公钥解密---------------------
私钥加密:
JKxCYGsGshnTF9o4HaX7KfcMPGnCcNnnZrWk9lQaSJ17cJbkOO8b/n2s4S2TBLdTy7oqmyqF5+MqR0/Pn08dZNy2oJc9fScjoEzovDsXWLqFXRDrxnoy8RtqYC70B9b6WfQGFesWL6qVhVfvH0xbqhbMQ19z7vyztYd5jy22Vw1jAIgl+3P9VdH5zJJ6eTpnkW0I82c9/vY4nIeMv49dTOjTN8vEcInqBse1pUb2UcnrOsiTzhh+D+0RiGVeWJ6Vx7RYkV6s9D7C+25Zf128MiPsCcEnI6ocfoBMEX/GzaXnT+vxj6b3vqJu738n7bF+dxNJnrr2iPzLF5JzpoFaEQ==
公钥解密:
{"name":"xiaoming","age":"23","address":"beijing"}
------------------公钥加密,私钥解密---------------------
公钥加密:
kEhne7tYqjmhBJqTq5GXop9OE5FBbDVBtcCKpBONrfTjbcZa0WPqyi2meCg/gNWzk8hI6KF5V5H9UIZBE74DJMQk2s/DcYQY/0zHuxaV4zgrD7TDVhTwM/YfnpR9xlf4JBnoY27M5eULaxf0Rj70nxwW/QGldZ/lhHpN/kZBlTmonSjfiEpm1WnWvZGSZVTib75/70kGDhl8ykpTZLRt9/CFIIgpf+U0WiSoOa3FRnFx/BTiAtWWYWSiIwMs7pzxM+UWPGy9m4FPPJgAhy8/AO9GKBWfpk3WFzz38OQTCsS/X+QkuUbDO7mSSalkTsYWTXTWv4GbPdcUaUYSkB97/g==
私钥解密:
{"name":"xiaoming","age":"23","address":"beijing"}
封装类
class
publicKey = $publicKey;
$this->privateKey = $privateKey;
}
/**
* 加密解密
* @param $string
* @param string $operation
* @return string
*/
public function authcode($string, $operation = 'encrypt')
{
if (!(file_exists($this->publicKey) || file_exists($this->privateKey))) {
echo '秘钥文件不存在';
return false;
}
$publicKey = openssl_pkey_get_public(file_get_contents($this->publicKey));
$privateKey = openssl_pkey_get_private(file_get_contents($this->privateKey));
if (!($privateKey || $publicKey)) {
echo '证书错误';
return false;
}
$data = "";
if ($operation == 'decrypt') {
openssl_private_decrypt(base64_decode($string), $data, $privateKey);
} else {
openssl_public_encrypt($string, $data, $publicKey);
$data = base64_encode($data);
}
return $data;
}
/**
* 生成证书
* @return bool
*/
public function exportOpenSSLFile()
{
$publicKey = $privateKey = '';
$dir = './conf';
$conf = 'openssl.cnf';
if (!is_dir($dir)) {
mkdir($dir,0700);
}
if (!file_exists($conf)) {
touch($dir . '/' . $conf);
}
//参数设置
$config = [
"digest_alg" => "sha512",
//字节数 512 1024 2048 4096 等
"private_key_bits" => 2048,
"config" => "./conf/openssl.cnf",
//加密类型
"private_key_type" => OPENSSL_KEYTYPE_RSA,
];
//创建私钥和公钥
$res = openssl_pkey_new($config);
if ($res == false) {
//创建失败,请检查openssl.cnf文件是否存在
echo '生成秘钥失败';
return false;
}
//将密钥导出为PEM编码的字符串,并输出(通过引用传递)。
openssl_pkey_export($res, $privateKey, null, $config);
$publicKey = openssl_pkey_get_details($res);
$publicKey = $publicKey["key"];
//生成证书
$createPublicFileRet = file_put_contents($this->publicKey, $publicKey);
$createPrivateFileRet = file_put_contents($this->privateKey, $privateKey);
if (!($createPublicFileRet || $createPrivateFileRet)) {
echo '创建秘钥文件失败';
return false;
}
openssl_free_key($res);
return true;
}
}
$certPublic = "./conf/cert_public.key";
$certPrivate = "./conf/cert_private.key";
$rsaObj = new Rsa($certPublic, $certPrivate);
//生成证书
$rsaObj->exportOpenSSLFile();
//原始数据
$sourceDat = '{"name":"jack","age":"22","address":"beijing"}';
echo 'source data:' . PHP_EOL, $sourceDat . PHP_EOL;
//加密
$encryptStr = $rsaObj->authcode($sourceDat);
echo 'string encrypt:' . PHP_EOL, $encryptStr . PHP_EOL;
//解密
$decryptStr = $rsaObj->authcode($encryptStr, 'decrypt');
echo 'string decrypt:' . PHP_EOL, $decryptStr . PHP_EOL;
输出
source data:
{"name":"jack","age":"22","address":"beijing"}
string encrypt:
hikoQAKwt9jztThG4SoepMnRsd/VqkpgUubnP6tFHqvsAEka9mPm5QLNFSW07p2l+5KJYOkNOX8IDQ+YXid2kivLnDc3RWHOsACw3nFnb28SbTsqv/QRLteRqXrj/zt/s02V9qQ/s/WZOHPRrKMqkVIbo1yrncT1YhdPWPeeY/6BBUWB7YS2a2IzN1Yo/MmGUtxqPTzXwUhdTztu7kVJnwF6sJK8Dus+2PsAdvbNSNrZGHIEKfKueaThn0QN55vzsK88wnuMpyJcpfK8O2WtwdIFVvBboZH9sNNCU80nUM3ma/Xpewash/Zac1ZX1jgxdfsNxmh73aV8eaOQyXzjCw==
string decrypt:
{"name":"jack","age":"22","address":"beijing"}
生成文件
$ tree conf/
conf/
├── cert_private.key
├── cert_public.key
└── openssl.cnf
0 directories, 3 files