Pkcs7Encoder.php 2.0 KB

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