123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
- <?php
- namespace JinDouYun\Controller;
- class Prpcrypt
- {
- public $key;
- function __construct($k)
- {
- $this->key = base64_decode($k . "=");
- }
- function Prpcrypt($k)
- {
- $this->key = base64_decode($k . "=");
- }
- public function encrypt($text, $corpid)
- {
- try {
-
- $random = $this->getRandomStr();
- $text = $random . pack("N", strlen($text)) . $text . $corpid;
- $iv = substr($this->key, 0, 16);
-
-
-
-
- $pkc_encoder = new PKCS7Encoder;
- $text = $pkc_encoder->encode($text);
-
-
-
-
-
- $encrypted = openssl_encrypt($text, 'AES-256-CBC', $this->key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv );
-
-
- return array(ErrorCode::$OK, base64_encode($encrypted));
- } catch (\Exception $e) {
- print $e;
- return array(ErrorCode::$EncryptAESError, null);
- }
- }
- public function decrypt($encrypted, $corpid)
- {
- try {
- $ciphertext_dec = base64_decode($encrypted);
-
- $iv = substr($this->key, 0, 16);
-
-
-
-
- $decrypted = openssl_decrypt ( $ciphertext_dec, 'AES-256-CBC', $this->key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv );
-
- } catch (\Exception $e) {
- return array(ErrorCode::$DecryptAESError, null);
- }
- try {
-
- $pkc_encoder = new PKCS7Encoder;
- $result = $pkc_encoder->decode($decrypted);
-
- if (strlen($result) < 16)
- return "";
- $content = substr($result, 16, strlen($result));
- $len_list = unpack("N", substr($content, 0, 4));
- $xml_len = $len_list[1];
- $xml_content = substr($content, 4, $xml_len);
- $from_corpid = substr($content, $xml_len + 4);
- } catch (\Exception $e) {
- print $e;
- return array(ErrorCode::$DecryptAESError, null);
- }
- if ($from_corpid != $corpid)
- return array(ErrorCode::$ValidateSuiteKeyError, null);
- return array(0, $xml_content);
- }
- function getRandomStr()
- {
- $str = "";
- $str_pol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
- $max = strlen($str_pol) - 1;
- for ($i = 0; $i < 16; $i++) {
- $str .= $str_pol[mt_rand(0, $max)];
- }
- return $str;
- }
- }
- ?>
|