PKCS7Encoder.php 1.3 KB

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