CryptRsa.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. /**
  3. * Rsa加解密类
  4. * @author Len
  5. * @since 2018-01-09
  6. */
  7. namespace crypt;
  8. class CryptRsa extends CryptAbstract
  9. {
  10. public static $cryptName = 'Rsa';
  11. private $_privateKey;
  12. private $_publicKey;
  13. /**
  14. * RSA加密
  15. * @param string $input 明文
  16. * @return string|null
  17. */
  18. public function encrypt($input)
  19. {
  20. if (!is_string($input)) {
  21. return null;
  22. }
  23. $this->getPublicKey();
  24. $r = openssl_public_encrypt($input, $encrypted, $this->_publicKey);
  25. if ($r) {
  26. return base64_encode($encrypted);
  27. }
  28. return null;
  29. }
  30. /**
  31. * RSA解密
  32. * @param string $encrypted 密文
  33. * @param string $extend
  34. * @return string|null
  35. */
  36. public function decrypt($encrypted)
  37. {
  38. if (!is_string($encrypted)) {
  39. return null;
  40. }
  41. $this->getPrivateKey();
  42. $r = openssl_private_decrypt(base64_decode($encrypted), $decrypted, $this->_privateKey);
  43. if ($r) {
  44. return $decrypted;
  45. }
  46. return null;
  47. }
  48. /**
  49. * 获取私钥
  50. * @return bool
  51. */
  52. public function getPrivateKey()
  53. {
  54. if (is_resource($this->_privateKey)) {
  55. return true;
  56. }
  57. $privateKey = file_get_contents($this->_config['privateKey']);
  58. $this->_privateKey = openssl_pkey_get_private($privateKey);
  59. return true;
  60. }
  61. /**
  62. * 获取公钥
  63. * @return bool
  64. */
  65. public function getPublicKey()
  66. {
  67. if (is_resource($this->_publicKey)) {
  68. return true;
  69. }
  70. $publicKey = file_get_contents($this->_config['publicKey']);
  71. $this->_publicKey = openssl_pkey_get_public($publicKey);
  72. return true;
  73. }
  74. public function __destruct()
  75. {
  76. !empty($this->_privateKey) && @openssl_free_key($this->_privateKey);
  77. !empty($this->_publicKey) && @openssl_free_key($this->_publicKey);
  78. }
  79. }