生成授权信息
// 要加密的数据
$data = array(
'site'=> 'www.2xyun.cn',
'user'=> 1436386488,
'version'=> '1.1.0'
);
// 将数据转换成json格式
$data = json_encode($data);
// 读取RSA私钥
$privateKey = openssl_pkey_get_private(file_get_contents('private_key.pem'));
// 使用私钥加密数据
openssl_private_encrypt($data, $encryptedData, $privateKey);
// 释放私钥资源
openssl_free_key($privateKey);
// 将二进制数据转换成base64编码后输出
echo base64_encode($encryptedData);
验证授权信息
// 加密后的授权信息
$encryptedData = 'ijfVYtnFxHhp/m9J4SMAWVQuvkH3HCK8Gdx5FA63+fVgzzFttXGcrpdg8YP/g8O+DvHp9RISJVTRfUVMeayO8uJWD6ZBOPtlg0z9PWUP1ZOwuRUwqerbkXHCzhA55xgu/qz0jXyR3KJCQxhHC4KlMueKRq/lrtk1O15LGrrQjhBcA7wukpxlm+oDF/ELJ9fEEgl2HeUNBGcq7gYCIWjBvviU6TJvro7rvxWwrItKyb6ck9jIUh7xzcDkDitfTekFYuW+W6WFkUo7DRKR41mjbkH0aNEIs0zEJd9bauipsy2LXAs5hbg4vBzIF4ZgSPPkIWp1t6/lTCcAeyQk5exVvA==';
// 获取公钥
$publicKey = openssl_pkey_get_public(file_get_contents('public_key.pem'));
// 使用公钥解密授权信息
openssl_public_decrypt(base64_decode($encryptedData), $decryptedData, $publicKey);
// 释放公钥资源
openssl_free_key($publicKey);
// 将授权信息转换成数组
$decryptedData = json_decode($decryptedData, true);
// 验证域名
if($decryptedData['site'] !== $_SERVER['HTTP_HOST']){
exit(json_encode(['code' => -1, 'msg' => '程序未授权!']));
}
评论