Prpcrypt.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. namespace Modules\Common\Support\Wechat\Crypt;
  3. /**
  4. * Prpcrypt class
  5. *
  6. * 提供接收和推送给公众平台消息的加解密接口.
  7. */
  8. class Prpcrypt
  9. {
  10. public $key;
  11. public function __construct($k)
  12. {
  13. $this->key = base64_decode($k . "=");
  14. }
  15. /**
  16. * 对明文进行加密
  17. * @param string $text 需要加密的明文
  18. * @return string 加密后的密文
  19. */
  20. public function encrypt($text, $appid)
  21. {
  22. try {
  23. //获得16位随机字符串,填充到明文之前
  24. $random = $this->getRandomStr();
  25. $text = $random . pack("N", strlen($text)) . $text . $appid;
  26. //使用自定义的填充方式对明文进行补位填充
  27. $pkc_encoder = new PKCS7Encoder;
  28. $text = $pkc_encoder->encode($text);
  29. $encrypted = @openssl_encrypt($text, 'aes-128-cbc', $this->key, 0);
  30. //print(base64_encode($encrypted));
  31. //使用BASE64对加密后的字符串进行编码
  32. return array(ErrorCode::$OK, base64_encode($encrypted));
  33. } catch (Exception $e) {
  34. //print $e;
  35. return array(ErrorCode::$EncryptAESError, null);
  36. }
  37. }
  38. /**
  39. * 对密文进行解密
  40. * @param string $encrypted 需要解密的密文
  41. * @return string 解密得到的明文
  42. */
  43. public function decrypt($encrypted, $appid)
  44. {
  45. try {
  46. //使用BASE64对需要解密的字符串进行解码
  47. $ciphertext_dec = base64_decode($encrypted);
  48. $decrypted = openssl_decrypt($ciphertext_dec, 'aes-128-cbc', $this->key);
  49. } catch (Exception $e) {
  50. return array(ErrorCode::$DecryptAESError, null);
  51. }
  52. try {
  53. //去除补位字符
  54. $pkc_encoder = new PKCS7Encoder;
  55. $result = $pkc_encoder->decode($decrypted);
  56. //去除16位随机字符串,网络字节序和AppId
  57. if (strlen($result) < 16)
  58. return "";
  59. $content = substr($result, 16, strlen($result));
  60. $len_list = unpack("N", substr($content, 0, 4));
  61. $xml_len = $len_list[1];
  62. $xml_content = substr($content, 4, $xml_len);
  63. $from_appid = substr($content, $xml_len + 4);
  64. } catch (Exception $e) {
  65. //print $e;
  66. return array(ErrorCode::$IllegalBuffer, null);
  67. }
  68. if ($from_appid != $appid)
  69. return array(ErrorCode::$ValidateAppidError, null);
  70. return array(0, $xml_content);
  71. }
  72. /**
  73. * 随机生成16位字符串
  74. * @return string 生成的字符串
  75. */
  76. function getRandomStr()
  77. {
  78. $str = "";
  79. $str_pol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
  80. $max = strlen($str_pol) - 1;
  81. for ($i = 0; $i < 16; $i++) {
  82. $str .= $str_pol[mt_rand(0, $max)];
  83. }
  84. return $str;
  85. }
  86. }
  87. ?>