1
0

PKCS7Encoder.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. namespace weworkapi\receive;
  3. use weworkapi\receive\ErrorCode;
  4. /**
  5. * PKCS7Encoder class
  6. *
  7. * 提供基于PKCS7算法的加解密接口.
  8. */
  9. class PKCS7Encoder
  10. {
  11. public static $block_size = 32;
  12. /**
  13. * 对需要加密的明文进行填充补位
  14. * @param $text 需要进行填充补位操作的明文
  15. * @return 补齐明文字符串
  16. */
  17. function encode($text)
  18. {
  19. $block_size = PKCS7Encoder::$block_size;
  20. $text_length = strlen($text);
  21. //计算需要填充的位数
  22. $amount_to_pad = PKCS7Encoder::$block_size - ($text_length % PKCS7Encoder::$block_size);
  23. if ($amount_to_pad == 0) {
  24. $amount_to_pad = PKCS7Encoder::block_size;
  25. }
  26. //获得补位所用的字符
  27. $pad_chr = chr($amount_to_pad);
  28. $tmp = "";
  29. for ($index = 0; $index < $amount_to_pad; $index++) {
  30. $tmp .= $pad_chr;
  31. }
  32. return $text . $tmp;
  33. }
  34. /**
  35. * 对解密后的明文进行补位删除
  36. * @param decrypted 解密后的明文
  37. * @return 删除填充补位后的明文
  38. */
  39. function decode($text)
  40. {
  41. $pad = ord(substr($text, -1));
  42. if ($pad < 1 || $pad > PKCS7Encoder::$block_size) {
  43. $pad = 0;
  44. }
  45. return substr($text, 0, (strlen($text) - $pad));
  46. }
  47. }