Prpcrypt.php 2.5 KB

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