pkcs7Encoder.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. $decrypted = openssl_decrypt($aesCipher, 'AES-128-CBC', $this->key, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $aesIV);
  69. } catch (Exception $e) {
  70. return array(ErrorCode::$IllegalBuffer, null);
  71. }
  72. try {
  73. //去除补位字符
  74. $pkc_encoder = new PKCS7Encoder;
  75. $result = $pkc_encoder->decode($decrypted);
  76. } catch (Exception $e) {
  77. //print $e;
  78. return array(ErrorCode::$IllegalBuffer, null);
  79. }
  80. return array(0, $result);
  81. }
  82. }
  83. ?>