| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- <?php
- namespace app\common\library;
- use function config;
- /**
- * rsa 签名
- */
- class RsaSign
- {
- protected $private_key = ''; // 私钥
- protected $public_key = ''; // 公钥
- public function __construct()
- {
- $config = config('rsa_sign');
- $this->private_key = file_get_contents($config['private_key']);
- $this->public_key = file_get_contents($config['public_key']);
- }
- /**
- * 公钥加密
- *
- * @param $data 加密数据
- *
- * @return void
- */
- public function openssl_public_encrypt($data){
- // 加密数据
- $public_key = openssl_get_publickey($this->public_key);
- openssl_public_encrypt($data, $encrypted_data, $public_key);
- // 输出加密后的数据
- return base64_encode($encrypted_data);
- }
- /**
- * 私钥解密
- *
- * @param $data 解密数据
- *
- * @return void
- */
- public function openssl_private_decrypt($data){
- // 解密数据
- openssl_private_decrypt(base64_decode($data), $decrypted_data, $this->private_key);
- // 输出解密后的数据
- return $decrypted_data;
- }
- /**
- * 私钥签名数据
- *
- * @param $data 签名数据
- *
- * @return void
- */
- public function openssl_sign($data){
- $private_key = openssl_get_privatekey($this->private_key);
- // 签名数据
- openssl_sign($data, $signature, $private_key);
- // 输出签名
- return base64_encode($signature);
- }
- /**
- * 公钥验证签名
- *
- * @param $data 验证数据
- * @param $sign 签名
- *
- * @return void
- */
- public function openssl_verify($data, $sign){
- $public_key = openssl_get_publickey($this->public_key);
- // 验证签名
- $result = openssl_verify($data, base64_decode($sign), $public_key);
- // 输出验证结果
- return $result === 1 ? true : false;
- }
- }
|