PKCS7Encoder.php 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. namespace WeChat\Prpcrypt;
  3. /**
  4. * PKCS7算法 - 加解密
  5. * Class PKCS7Encoder
  6. */
  7. class PKCS7Encoder
  8. {
  9. public static $blockSize = 32;
  10. /**
  11. * 对需要加密的明文进行填充补位
  12. * @param string $text 需要进行填充补位操作的明文
  13. * @return string 补齐明文字符串
  14. */
  15. function encode($text)
  16. {
  17. $amount_to_pad = PKCS7Encoder::$blockSize - (strlen($text) % PKCS7Encoder::$blockSize);
  18. if ($amount_to_pad == 0) {
  19. $amount_to_pad = PKCS7Encoder::$blockSize;
  20. }
  21. list($pad_chr, $tmp) = [chr($amount_to_pad), ''];
  22. for ($index = 0; $index < $amount_to_pad; $index++) {
  23. $tmp .= $pad_chr;
  24. }
  25. return $text . $tmp;
  26. }
  27. /**
  28. * 对解密后的明文进行补位删除
  29. * @param string $text 解密后的明文
  30. * @return string 删除填充补位后的明文
  31. */
  32. function decode($text)
  33. {
  34. $pad = ord(substr($text, -1));
  35. if ($pad < 1 || $pad > PKCS7Encoder::$blockSize) {
  36. $pad = 0;
  37. }
  38. return substr($text, 0, strlen($text) - $pad);
  39. }
  40. }