人人商城

pkcs7Encoder.php 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <?php
  2. include_once "errorCode.php";
  3. /**
  4. * PKCS7Encoder class
  5. *
  6. * 提供基于PKCS7算法的加解密接口.
  7. */
  8. class PKCS7Encoder
  9. {
  10. public static $block_size = 16;
  11. /**
  12. * 对需要加密的明文进行填充补位
  13. * @param $text 需要进行填充补位操作的明文
  14. * @return 补齐明文字符串
  15. */
  16. function encode( $text )
  17. {
  18. $block_size = PKCS7Encoder::$block_size;
  19. $text_length = strlen( $text );
  20. //计算需要填充的位数
  21. $amount_to_pad = PKCS7Encoder::$block_size - ( $text_length % PKCS7Encoder::$block_size );
  22. if ( $amount_to_pad == 0 ) {
  23. $amount_to_pad = PKCS7Encoder::block_size;
  24. }
  25. //获得补位所用的字符
  26. $pad_chr = chr( $amount_to_pad );
  27. $tmp = "";
  28. for ( $index = 0; $index < $amount_to_pad; $index++ ) {
  29. $tmp .= $pad_chr;
  30. }
  31. return $text . $tmp;
  32. }
  33. /**
  34. * 对解密后的明文进行补位删除
  35. * @param decrypted 解密后的明文
  36. * @return 删除填充补位后的明文
  37. */
  38. function decode($text)
  39. {
  40. $pad = ord(substr($text, -1));
  41. if ($pad < 1 || $pad > 32) {
  42. $pad = 0;
  43. }
  44. return substr($text, 0, (strlen($text) - $pad));
  45. }
  46. }
  47. /**
  48. * Prpcrypt class
  49. *
  50. *
  51. */
  52. class Prpcrypt
  53. {
  54. public $key;
  55. function __construct( $k )
  56. {
  57. $this->key = $k;
  58. }
  59. /**
  60. * 对密文进行解密
  61. * @param string $aesCipher 需要解密的密文
  62. * @param string $aesIV 解密的初始向量
  63. * @return string 解密得到的明文
  64. */
  65. public function decrypt( $aesCipher, $aesIV = '' )
  66. {
  67. try {
  68. if (empty($aesIV)) {
  69. $mcrypt_mode = MCRYPT_MODE_ECB;
  70. } else {
  71. $mcrypt_mode = MCRYPT_MODE_CBC;
  72. }
  73. $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', $mcrypt_mode, '');
  74. @mcrypt_generic_init($module, $this->key, $aesIV);
  75. //解密
  76. $decrypted = mdecrypt_generic($module, $aesCipher);
  77. mcrypt_generic_deinit($module);
  78. mcrypt_module_close($module);
  79. } catch (Exception $e) {
  80. return array(ErrorCode::$IllegalBuffer, null);
  81. }
  82. try {
  83. //去除补位字符
  84. $pkc_encoder = new PKCS7Encoder;
  85. $result = $pkc_encoder->decode($decrypted);
  86. } catch (Exception $e) {
  87. //print $e;
  88. return array(ErrorCode::$IllegalBuffer, null);
  89. }
  90. return array(0, $result);
  91. }
  92. }
  93. ?>