Rsa.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. namespace app\api\middleware;
  3. class Rsa {
  4. /**
  5. * 获取私钥
  6. * @return bool|resource
  7. */
  8. private static function getPrivateKey()
  9. {
  10. $abs_path = dirname(__FILE__) . '/rsa_private_key.pem';
  11. $content = file_get_contents($abs_path);
  12. return openssl_pkey_get_private($content);
  13. }
  14. /**
  15. * 获取公钥
  16. * @return bool|resource
  17. */
  18. private static function getPublicKey()
  19. {
  20. $abs_path = dirname(__FILE__) . '/rsa_public_key.pem';
  21. $content = file_get_contents($abs_path);
  22. return openssl_pkey_get_public($content);
  23. }
  24. /**
  25. * 私钥加密
  26. * @param string $data
  27. * @return null|string
  28. */
  29. public static function privEncrypt($data = '')
  30. {
  31. if (!is_string($data)) {
  32. return null;
  33. }
  34. return openssl_private_encrypt($data,$encrypted,self::getPrivateKey()) ? base64_encode($encrypted) : null;
  35. }
  36. /**
  37. * 公钥加密
  38. * @param string $data
  39. * @return null|string
  40. */
  41. public static function publicEncrypt($data = '')
  42. {
  43. if (!is_string($data)) {
  44. return null;
  45. }
  46. return openssl_public_encrypt($data,$encrypted,self::getPublicKey()) ? base64_encode($encrypted) : null;
  47. }
  48. /**
  49. * 私钥解密
  50. * @param string $encrypted
  51. * @return null
  52. */
  53. public static function privDecrypt($encrypted = '')
  54. {
  55. if (!is_string($encrypted)) {
  56. return null;
  57. }
  58. return (openssl_private_decrypt(base64_decode($encrypted), $decrypted, self::getPrivateKey())) ? $decrypted : null;
  59. }
  60. /**
  61. * 公钥解密
  62. * @param string $encrypted
  63. * @return null
  64. */
  65. public static function publicDecrypt($encrypted = '')
  66. {
  67. if (!is_string($encrypted)) {
  68. return null;
  69. }
  70. return (openssl_public_decrypt(base64_decode($encrypted), $decrypted, self::getPublicKey())) ? $decrypted : null;
  71. }
  72. }