RSAUtil.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace clue;
  3. class RSAUtil
  4. {
  5. public $privateKey;
  6. public $publicKey;
  7. /**
  8. * 构造方法
  9. * @access public
  10. */
  11. public function __construct($private_key,$public_key)
  12. {
  13. $this->privateKey = openssl_pkey_get_private($private_key);
  14. $this->publicKey = openssl_pkey_get_public($public_key);
  15. }
  16. public function __call($method, $args)
  17. {
  18. return json(['status' => '1', 'msg' => '方法不存在']);
  19. }
  20. public function privateEncrypt($data)
  21. {
  22. $crypto = '';
  23. foreach (str_split($data, 117) as $chunk) {
  24. openssl_private_encrypt($chunk, $encryptData, $this->privateKey);
  25. $crypto .= $encryptData;
  26. }
  27. //加密后的内容通常含有特殊字符,需要编码转换下,在网络间通过url传输时要注意base64编码是否是url安全的
  28. $encrypted = $this->urlsafeB64encode($crypto);
  29. return $encrypted;
  30. }
  31. //加密码时把特殊符号替换成URL可以带的内容
  32. function urlsafeB64encode($string)
  33. {
  34. $data = base64_encode($string);
  35. $data = str_replace(array('+', '/', '='), array('-', '_', ''), $data);
  36. return $data;
  37. }
  38. //解密码时把转换后的符号替换特殊符号
  39. function urlsafeB64decode($string)
  40. {
  41. $data = str_replace(array('-', '_'), array('+', '/'), $string);
  42. $mod4 = strlen($data) % 4;
  43. if ($mod4) {
  44. $data .= substr('====', $mod4);
  45. }
  46. return base64_decode($data);
  47. }
  48. //公钥加密
  49. public function publicEncrypt($data)
  50. {
  51. $crypto = '';
  52. foreach (str_split($data, 117) as $chunk) {
  53. openssl_public_encrypt($chunk, $encryptData, $this->publicKey);
  54. $crypto .= $encryptData;
  55. }
  56. $encrypted = $this->urlsafeB64encode($crypto);
  57. return $encrypted;
  58. }
  59. //私钥解密
  60. public function privateDecrypt($encrypted)
  61. {
  62. $crypto = '';
  63. foreach (str_split($this->urlsafeB64decode($encrypted), 128) as $chunk) {
  64. openssl_private_decrypt($chunk, $decryptData, $this->privateKey);
  65. $crypto .= $decryptData;
  66. }
  67. return $crypto;
  68. }
  69. }