PKCS7Encoder.php 1.2 KB

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