RsaSign.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace app\common\library;
  3. use function config;
  4. /**
  5. * rsa 签名
  6. */
  7. class RsaSign
  8. {
  9. protected $private_key = ''; // 私钥
  10. protected $public_key = ''; // 公钥
  11. public function __construct()
  12. {
  13. $config = config('rsa_sign');
  14. $this->private_key = file_get_contents($config['private_key']);
  15. $this->public_key = file_get_contents($config['public_key']);
  16. }
  17. /**
  18. * 公钥加密
  19. *
  20. * @param $data 加密数据
  21. *
  22. * @return void
  23. */
  24. public function openssl_public_encrypt($data){
  25. // 加密数据
  26. $public_key = openssl_get_publickey($this->public_key);
  27. openssl_public_encrypt($data, $encrypted_data, $public_key);
  28. // 输出加密后的数据
  29. return base64_encode($encrypted_data);
  30. }
  31. /**
  32. * 私钥解密
  33. *
  34. * @param $data 解密数据
  35. *
  36. * @return void
  37. */
  38. public function openssl_private_decrypt($data){
  39. // 解密数据
  40. openssl_private_decrypt(base64_decode($data), $decrypted_data, $this->private_key);
  41. // 输出解密后的数据
  42. return $decrypted_data;
  43. }
  44. /**
  45. * 私钥签名数据
  46. *
  47. * @param $data 签名数据
  48. *
  49. * @return void
  50. */
  51. public function openssl_sign($data){
  52. $private_key = openssl_get_privatekey($this->private_key);
  53. // 签名数据
  54. openssl_sign($data, $signature, $private_key);
  55. // 输出签名
  56. return base64_encode($signature);
  57. }
  58. /**
  59. * 公钥验证签名
  60. *
  61. * @param $data 验证数据
  62. * @param $sign 签名
  63. *
  64. * @return void
  65. */
  66. public function openssl_verify($data, $sign){
  67. $public_key = openssl_get_publickey($this->public_key);
  68. // 验证签名
  69. $result = openssl_verify($data, base64_decode($sign), $public_key);
  70. // 输出验证结果
  71. return $result === 1 ? true : false;
  72. }
  73. }