PKCS7Encoder.php 1.4 KB

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