RSA加密
1. 生成私钥和公钥
# 私钥
openssl genrsa -out rsa_private_key.pem 1024
# 公钥
openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
function createOpenSSLKeys($cnf)
{
$private_key = '';
$public_key = '';
$config = [
"digest_alg" => "sha512",
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
'config' => $cnf
];
$res = openssl_pkey_new($config);
openssl_pkey_export($res, $private_key, null, $config);
$public_key = openssl_pkey_get_details($res)['key'];
return [
'public_key' => $public_key,
'private_key' => $private_key
];
}
2. 使用
$data = 'wogaslfgnladfghlanflgnaldnglanfhlnlabh';
$public_key = file_get_contents('rsa_public_key.pem');
$public = openssl_pkey_get_public($public_key);
$encode = '';
// 公钥加密
openssl_public_encrypt($data, $encode, $public);
$private_key = file_get_contents('rsa_private_key.pem');
$private = openssl_pkey_get_private($private_key);
$decode = '';
// 私钥解密
openssl_private_decrypt($encode, $decode, $private);
echo $decode;