pkcs7Encoder.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. include_once "errorCode.php";
  3. /**
  4. * PKCS7Encoder class
  5. *
  6. * 提供基于PKCS7算法的加解密接口.
  7. */
  8. class PKCS7Encoder {
  9. public static $block_size = 16;
  10. /**
  11. * 对需要加密的明文进行填充补位
  12. * @param $text 需要进行填充补位操作的明文
  13. * @return 补齐明文字符串
  14. */
  15. public function encode($text) {
  16. $block_size = PKCS7Encoder::$block_size;
  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. * @param decrypted 解密后的明文
  34. * @return 删除填充补位后的明文
  35. */
  36. public function decode($text) {
  37. $pad = ord(substr($text, -1));
  38. if ($pad < 1 || $pad > 32) {
  39. $pad = 0;
  40. }
  41. return substr($text, 0, (strlen($text) - $pad));
  42. }
  43. }
  44. /**
  45. * Prpcrypt class
  46. *
  47. *
  48. */
  49. class Prpcrypt {
  50. public $key;
  51. public function __construct($k) {
  52. $this->key = $k;
  53. }
  54. /**
  55. * 对密文进行解密
  56. * @param string $aesCipher 需要解密的密文
  57. * @param string $aesIV 解密的初始向量
  58. * @return string 解密得到的明文
  59. */
  60. public function decrypt($aesCipher, $aesIV = '') {
  61. try {
  62. $decrypted = openssl_decrypt($aesCipher, 'AES-128-CBC', $this->key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $aesIV);
  63. } catch (Exception $e) {
  64. return array(ErrorCode::$IllegalBuffer, null);
  65. }
  66. try {
  67. //去除补位字符
  68. $pkc_encoder = new PKCS7Encoder;
  69. $result = $pkc_encoder->decode($decrypted);
  70. } catch (Exception $e) {
  71. //print $e;
  72. return array(ErrorCode::$IllegalBuffer, null);
  73. }
  74. return array(0, $result);
  75. }
  76. }