Rsa.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. declare (strict_types=1);
  3. namespace utils;
  4. use think\facade\Config;
  5. class Rsa
  6. {
  7. /**
  8. * 配置参数
  9. * @var array
  10. */
  11. protected $config = [];
  12. /**
  13. * 构造方法
  14. * @access public
  15. */
  16. public function __construct(Config $config)
  17. {
  18. $this->config = $config::get('cipher');
  19. }
  20. /**
  21. * 私钥加密
  22. * @param string $data 要加密的数据
  23. * @return false|string
  24. */
  25. public function privateEncrypt(string $data): string
  26. {
  27. $private_key = openssl_pkey_get_private($this->config['private_key']);
  28. openssl_private_encrypt($data, $encrypted, $private_key);
  29. return base64_encode($encrypted);
  30. }
  31. /**
  32. * 私钥解密
  33. * @param string $data
  34. * @return false|string
  35. */
  36. public function privateDecrypt(string $data): ?string
  37. {
  38. $private_key = openssl_pkey_get_private($this->config['private_key']);
  39. openssl_private_decrypt(base64_decode($data), $decrypted, $private_key);
  40. return $decrypted;
  41. }
  42. /**
  43. * 公钥加密
  44. * @param string $data
  45. * @return false|string
  46. */
  47. public function publicEncrypt(string $data): string
  48. {
  49. $public_key = openssl_pkey_get_public($this->config['public_key']);
  50. openssl_public_encrypt($data, $encrypted, $public_key);
  51. return base64_encode($encrypted);
  52. }
  53. /**
  54. * 公钥解密
  55. * @param string $data
  56. * @return false|string
  57. */
  58. public function publicDecrypt(string $data): ?string
  59. {
  60. $public_key = openssl_pkey_get_public($this->config['public_key']);
  61. openssl_public_decrypt(base64_decode($data), $decrypted, $public_key);
  62. return $decrypted;
  63. }
  64. }