AES.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace App\Common\Library;
  3. /**
  4. * Class AES.
  5. *
  6. * @author overtrue <i@overtrue.me>
  7. */
  8. class AES
  9. {
  10. /**
  11. * @param string $text
  12. * @param string $key
  13. * @param string $iv
  14. * @param int $option
  15. *
  16. * @return string
  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 $cipherText
  26. * @param string $key
  27. * @param string $iv
  28. * @param int $option
  29. * @param string|null $method
  30. *
  31. * @return string
  32. */
  33. public static function decrypt(string $cipherText, string $key, string $iv, int $option = OPENSSL_RAW_DATA, $method = null): string
  34. {
  35. self::validateKey($key);
  36. self::validateIv($iv);
  37. return openssl_decrypt($cipherText, $method ?: self::getMode($key), $key, $option, $iv);
  38. }
  39. /**
  40. * @param string $key
  41. *
  42. * @return string
  43. */
  44. public static function getMode($key)
  45. {
  46. return 'aes-'.(8 * strlen($key)).'-cbc';
  47. }
  48. /**
  49. * @param string $key
  50. */
  51. public static function validateKey(string $key)
  52. {
  53. if (!in_array(strlen($key), [16, 24, 32], true)) {
  54. throw new \InvalidArgumentException(sprintf('Key length must be 16, 24, or 32 bytes; got key len (%s).', strlen($key)));
  55. }
  56. }
  57. /**
  58. * @param string $iv
  59. *
  60. * @throws \InvalidArgumentException
  61. */
  62. public static function validateIv(string $iv)
  63. {
  64. if (!empty($iv) && 16 !== strlen($iv)) {
  65. throw new \InvalidArgumentException('IV length must be 16 bytes.');
  66. }
  67. }
  68. }