AesHelper.php 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. <?php
  2. namespace addons\QiDingDong\common\helper;
  3. class AesHelper
  4. {
  5. public static $aesMethod = "AES-128-CBC";
  6. public static $aesOptions = OPENSSL_RAW_DATA;
  7. public static $aesIv = "106d46f29f9ea389";
  8. /**
  9. * 对字符串进行加密
  10. *
  11. * @param mixed $plaintext
  12. * @return array [密文,加密key]
  13. */
  14. public static function encrypt($plaintext)
  15. {
  16. $key = time() . mt_rand(100000, 999999);
  17. $ciphertext = openssl_encrypt(json_encode($plaintext), self::$aesMethod, $key, self::$aesOptions, self::$aesIv);
  18. return [base64_encode($ciphertext), $key];
  19. }
  20. /**
  21. * 对密文进行解密
  22. *
  23. * @param string $ciphertext 密文
  24. * @param string $key 加密密钥
  25. * @return string|array|int 解密后数据
  26. */
  27. public static function decrypt(string $ciphertext, string $key)
  28. {
  29. $original_plaintext = openssl_decrypt(base64_decode($ciphertext), self::$aesMethod, $key, self::$aesOptions, self::$aesIv);
  30. return json_decode($original_plaintext, true);
  31. }
  32. }