DefaultEncrypter.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * This file is part of the EasyWeChatComposer.
  5. *
  6. * (c) 张铭阳 <mingyoungcheung@gmail.com>
  7. *
  8. * This source file is subject to the MIT license that is bundled
  9. * with this source code in the file LICENSE.
  10. */
  11. namespace EasyWeChatComposer\Encryption;
  12. use EasyWeChatComposer\Contracts\Encrypter;
  13. use EasyWeChatComposer\Exceptions\DecryptException;
  14. use EasyWeChatComposer\Exceptions\EncryptException;
  15. class DefaultEncrypter implements Encrypter
  16. {
  17. /**
  18. * @var string
  19. */
  20. protected $key;
  21. /**
  22. * @var string
  23. */
  24. protected $cipher;
  25. /**
  26. * @param string $key
  27. * @param string $cipher
  28. */
  29. public function __construct($key, $cipher = 'AES-256-CBC')
  30. {
  31. $this->key = $key;
  32. $this->cipher = $cipher;
  33. }
  34. /**
  35. * Encrypt the given value.
  36. *
  37. * @param string $value
  38. *
  39. * @return string
  40. *
  41. * @throws \EasyWeChatComposer\Exceptions\EncryptException
  42. */
  43. public function encrypt($value)
  44. {
  45. $iv = random_bytes(openssl_cipher_iv_length($this->cipher));
  46. $value = openssl_encrypt($value, $this->cipher, $this->key, 0, $iv);
  47. if ($value === false) {
  48. throw new EncryptException('Could not encrypt the data.');
  49. }
  50. $iv = base64_encode($iv);
  51. return base64_encode(json_encode(compact('iv', 'value')));
  52. }
  53. /**
  54. * Decrypt the given value.
  55. *
  56. * @param string $payload
  57. *
  58. * @return string
  59. *
  60. * @throws \EasyWeChatComposer\Exceptions\DecryptException
  61. */
  62. public function decrypt($payload)
  63. {
  64. $payload = json_decode(base64_decode($payload), true);
  65. $iv = base64_decode($payload['iv']);
  66. $decrypted = openssl_decrypt($payload['value'], $this->cipher, $this->key, 0, $iv);
  67. if ($decrypted === false) {
  68. throw new DecryptException('Could not decrypt the data.');
  69. }
  70. return $decrypted;
  71. }
  72. }