AES.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 App\Libs\TikTok\Kernel\Support;
  11. use App\Libs\TikTok\Kernel\Exceptions\InvalidArgumentException;
  12. /**
  13. * Class AES.
  14. *
  15. * @author overtrue <i@overtrue.me>
  16. */
  17. class AES {
  18. /**
  19. * @param string $text
  20. * @param string $key
  21. * @param string $iv
  22. * @param int $option
  23. *
  24. * @return string
  25. * @throws InvalidArgumentException
  26. */
  27. public static function encrypt(string $text, string $key, string $iv, int $option = OPENSSL_RAW_DATA): string {
  28. self::validateKey($key);
  29. self::validateIv($iv);
  30. return openssl_encrypt($text, self::getMode($key), $key, $option, $iv);
  31. }
  32. /**
  33. * @param string $cipherText
  34. * @param string $key
  35. * @param string $iv
  36. * @param int $option
  37. * @param string|null $method
  38. *
  39. * @return string
  40. * @throws InvalidArgumentException
  41. */
  42. public static function decrypt(string $cipherText, string $key, string $iv, int $option = OPENSSL_RAW_DATA, $method = null): string {
  43. self::validateKey($key);
  44. self::validateIv($iv);
  45. return openssl_decrypt($cipherText, $method ?: self::getMode($key), $key, $option, $iv);
  46. }
  47. /**
  48. * @param string $key
  49. *
  50. * @return string
  51. */
  52. public static function getMode(string $key): string {
  53. return 'aes-' . (8 * strlen($key)) . '-cbc';
  54. }
  55. /**
  56. *
  57. * @param string $key
  58. * @throws InvalidArgumentException
  59. * @author zhaoxiang <zhaoxiang051405@gmail.com>
  60. */
  61. public static function validateKey(string $key): void {
  62. if (!in_array(strlen($key), [16, 24, 32], true)) {
  63. throw new InvalidArgumentException(sprintf('Key length must be 16, 24, or 32 bytes; got key len (%s).', strlen($key)));
  64. }
  65. }
  66. /**
  67. *
  68. * @param string $iv
  69. * @throws InvalidArgumentException
  70. * @author zhaoxiang <zhaoxiang051405@gmail.com>
  71. */
  72. public static function validateIv(string $iv): void {
  73. if (!empty($iv) && 16 !== strlen($iv)) {
  74. throw new InvalidArgumentException('IV length must be 16 bytes.');
  75. }
  76. }
  77. }