PrpCrypt.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. namespace WeWork\Crypt;
  3. /**
  4. * 提供接收和推送给公众平台消息的加解密接口
  5. */
  6. class PrpCrypt
  7. {
  8. /**
  9. * @var string
  10. */
  11. public $key = null;
  12. /**
  13. * @var string
  14. */
  15. public $iv = null;
  16. /**
  17. * @param $k
  18. */
  19. public function __construct($k)
  20. {
  21. $this->key = base64_decode($k . '=');
  22. $this->iv = substr($this->key, 0, 16);
  23. }
  24. /**
  25. * 加密
  26. *
  27. * @param string $text
  28. * @param string $corpid
  29. * @return array
  30. */
  31. public function encrypt($text, $corpid)
  32. {
  33. try {
  34. //拼接
  35. $text = $this->getRandomStr() . pack('N', strlen($text)) . $text . $corpid;
  36. //添加PKCS#7填充
  37. $pkc_encoder = new PKCS7Encoder;
  38. $text = $pkc_encoder->encode($text);
  39. //加密
  40. $encrypted = openssl_encrypt($text, 'AES-256-CBC', $this->key, OPENSSL_ZERO_PADDING, $this->iv);
  41. return [ErrorCode::$OK, $encrypted];
  42. } catch (\Exception $e) {
  43. return [ErrorCode::$EncryptAESError, null];
  44. }
  45. }
  46. /**
  47. * 解密
  48. *
  49. * @param $encrypted
  50. * @param $corpid
  51. * @return array
  52. */
  53. public function decrypt($encrypted, $corpid)
  54. {
  55. try {
  56. //解密
  57. $decrypted = openssl_decrypt($encrypted, 'AES-256-CBC', $this->key, OPENSSL_ZERO_PADDING, $this->iv);
  58. } catch (\Exception $e) {
  59. return [ErrorCode::$DecryptAESError, null];
  60. }
  61. try {
  62. //删除PKCS#7填充
  63. $pkc_encoder = new PKCS7Encoder;
  64. $result = $pkc_encoder->decode($decrypted);
  65. if (strlen($result) < 16) {
  66. return [];
  67. }
  68. //拆分
  69. $content = substr($result, 16, strlen($result));
  70. $len_list = unpack('N', substr($content, 0, 4));
  71. $xml_len = $len_list[1];
  72. $xml_content = substr($content, 4, $xml_len);
  73. $from_corpid = substr($content, $xml_len + 4);
  74. } catch (\Exception $e) {
  75. return [ErrorCode::$IllegalBuffer, null];
  76. }
  77. if ($from_corpid != $corpid) {
  78. return [ErrorCode::$ValidateCorpidError, null];
  79. }
  80. return [0, $xml_content];
  81. }
  82. /**
  83. * 生成随机字符串
  84. *
  85. * @return string
  86. */
  87. public function getRandomStr()
  88. {
  89. $str = '';
  90. $str_pol = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyl';
  91. $max = strlen($str_pol) - 1;
  92. for ($i = 0; $i < 16; $i++) {
  93. $str .= $str_pol[mt_rand(0, $max)];
  94. }
  95. return $str;
  96. }
  97. }