Pkcs7Encoder.php 1.4 KB

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