AES.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. /*
  3. * This file is part of the overtrue/wechat.
  4. *
  5. * (c) overtrue <i@overtrue.me>
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. namespace EasyWeChat\Kernel\Support;
  11. /**
  12. * Class AES.
  13. *
  14. * @author overtrue <i@overtrue.me>
  15. */
  16. class AES
  17. {
  18. public static function encrypt(string $text, string $key, string $iv, int $option = OPENSSL_RAW_DATA): string
  19. {
  20. self::validateKey($key);
  21. self::validateIv($iv);
  22. return openssl_encrypt($text, self::getMode($key), $key, $option, $iv);
  23. }
  24. /**
  25. * @param string|null $method
  26. */
  27. public static function decrypt(string $cipherText, string $key, string $iv, int $option = OPENSSL_RAW_DATA, $method = null): string
  28. {
  29. self::validateKey($key);
  30. self::validateIv($iv);
  31. return openssl_decrypt($cipherText, $method ?: self::getMode($key), $key, $option, $iv);
  32. }
  33. /**
  34. * @param string $key
  35. *
  36. * @return string
  37. */
  38. public static function getMode($key)
  39. {
  40. return 'aes-'.(8 * strlen($key)).'-cbc';
  41. }
  42. public static function validateKey(string $key)
  43. {
  44. if (!in_array(strlen($key), [16, 24, 32], true)) {
  45. throw new \InvalidArgumentException(sprintf('Key length must be 16, 24, or 32 bytes; got key len (%s).', strlen($key)));
  46. }
  47. }
  48. /**
  49. * @throws \InvalidArgumentException
  50. */
  51. public static function validateIv(string $iv)
  52. {
  53. if (!empty($iv) && 16 !== strlen($iv)) {
  54. throw new \InvalidArgumentException('IV length must be 16 bytes.');
  55. }
  56. }
  57. }