AES.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /**
  3. * 重庆赤晓店信息科技有限公司
  4. * https://www.chixiaodian.com
  5. * Copyright (c) 2023 赤店商城 All rights reserved.
  6. */
  7. /*
  8. * This file is part of the overtrue/wechat.
  9. *
  10. * (c) overtrue <i@overtrue.me>
  11. *
  12. * This source file is subject to the MIT license that is bundled
  13. * with this source code in the file LICENSE.
  14. */
  15. namespace ByteDance\Kernel\Support;
  16. /**
  17. * Class AES.
  18. *
  19. * @author overtrue <i@overtrue.me>
  20. */
  21. class AES
  22. {
  23. /**
  24. * @param string $text
  25. * @param string $key
  26. * @param string $iv
  27. * @param int $option
  28. *
  29. * @return string
  30. */
  31. public static function encrypt(string $text, string $key, string $iv, int $option = OPENSSL_RAW_DATA): string
  32. {
  33. self::validateKey($key);
  34. self::validateIv($iv);
  35. return openssl_encrypt($text, self::getMode($key), $key, $option, $iv);
  36. }
  37. /**
  38. * @param string $cipherText
  39. * @param string $key
  40. * @param string $iv
  41. * @param int $option
  42. * @param string|null $method
  43. *
  44. * @return string
  45. */
  46. public static function decrypt(string $cipherText, string $key, string $iv, int $option = OPENSSL_RAW_DATA, $method = null): string
  47. {
  48. self::validateKey($key);
  49. self::validateIv($iv);
  50. return openssl_decrypt($cipherText, $method ?: self::getMode($key), $key, $option, $iv);
  51. }
  52. /**
  53. * @param string $key
  54. *
  55. * @return string
  56. */
  57. public static function getMode($key)
  58. {
  59. return 'aes-'.(8 * strlen($key)).'-cbc';
  60. }
  61. /**
  62. * @param string $key
  63. */
  64. public static function validateKey(string $key)
  65. {
  66. if (!in_array(strlen($key), [16, 24, 32], true)) {
  67. throw new \InvalidArgumentException(sprintf('Key length must be 16, 24, or 32 bytes; got key len (%s).', strlen($key)));
  68. }
  69. }
  70. /**
  71. * @param string $iv
  72. *
  73. * @throws \InvalidArgumentException
  74. */
  75. public static function validateIv(string $iv)
  76. {
  77. if (!empty($iv) && 16 !== strlen($iv)) {
  78. throw new \InvalidArgumentException('IV length must be 16 bytes.');
  79. }
  80. }
  81. }