AES.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. /**
  3. * AES.php UTF-8
  4. *
  5. *
  6. * @date : 2021-03-10 17:29
  7. *
  8. * @license 这不是一个自由软件,未经授权不许任何使用和传播。
  9. * @author : luowei <lw@huosdk.com>
  10. * @version : HUOSDK 9.0
  11. */
  12. namespace huoIdentify\controller;
  13. class AES {
  14. /**
  15. * key
  16. *
  17. * @var string
  18. */
  19. private $key;
  20. /**
  21. * method
  22. *
  23. * @var string
  24. */
  25. private $cipher;
  26. /**
  27. * iv length
  28. *
  29. * @var int
  30. */
  31. private $ivlen;
  32. /**
  33. * AES constructor.
  34. *
  35. * @param $key
  36. * @param string $cipher
  37. * @param int $ivlen
  38. */
  39. public function __construct($key, $cipher = 'aes-128-gcm', $ivlen = 12) {
  40. $this->cipher = $cipher;
  41. $this->ivlen = $ivlen;
  42. $this->key = hex2bin($key);
  43. }
  44. /**
  45. * AES GCM 128
  46. *
  47. * @param $cipherText
  48. * @param callable|null $callback
  49. *
  50. * @return string|false
  51. */
  52. public function decrypt($cipherText, callable $callback = null) {
  53. if (!is_null($callback)) {
  54. $cipherText = call_user_func($callback, $cipherText);
  55. } else {
  56. // method base64_encode as default return
  57. $cipherText = base64_decode($cipherText);
  58. }
  59. $iv = substr($cipherText, 0, $this->ivlen);
  60. $data = substr($cipherText, $this->ivlen, strlen($cipherText) - 16 - $this->ivlen);
  61. $tag = substr($cipherText, strlen($cipherText) - 16);
  62. return openssl_decrypt($data, $this->cipher, $this->key, OPENSSL_RAW_DATA, $iv, $tag);
  63. }
  64. /**
  65. * AES GCM 128
  66. *
  67. * @param string $plainText
  68. * @param callable|null $callback
  69. *
  70. * @return string
  71. */
  72. public function encrypt($plainText, callable $callback = null) {
  73. $iv = openssl_random_pseudo_bytes($this->ivlen, $result);
  74. if (!$result) {
  75. throw new \Exception('random bytes error');
  76. }
  77. $tag = null;
  78. $data = openssl_encrypt($plainText, $this->cipher, $this->key, OPENSSL_RAW_DATA, $iv, $tag);
  79. $data = $iv.$data.$tag;
  80. if (!is_null($callback)) {
  81. return call_user_func($callback, $data);
  82. }
  83. // use the base64_encode as default method to return
  84. return rtrim(base64_encode($data), "=");
  85. }
  86. }