ApiV3Encrypt.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace app\common\services\wechatApiV3;
  3. class ApiV3Encrypt
  4. {
  5. const AUTH_TAG_LENGTH_BYTE = 16;
  6. /**
  7. * @var ApiV3Config
  8. */
  9. private $config;
  10. public function __construct(ApiV3Config $config)
  11. {
  12. $this->config = $config;
  13. }
  14. public function decrypt($associatedData, $nonceStr, $ciphertext)
  15. {
  16. $ciphertext = \base64_decode($ciphertext);
  17. if (strlen($ciphertext) <= self::AUTH_TAG_LENGTH_BYTE) {
  18. return false;
  19. }
  20. if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {
  21. return \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, $this->config->secretV3());
  22. }
  23. if (function_exists('\Sodium\crypto_aead_aes256gcm_is_available') && \Sodium\crypto_aead_aes256gcm_is_available()) {
  24. return \Sodium\crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, $this->config->secretV3());
  25. }
  26. // openssl (PHP >= 7.1 support AEAD)
  27. if (PHP_VERSION_ID >= 70100 && in_array('aes-256-gcm', \openssl_get_cipher_methods())) {
  28. $ctext = substr($ciphertext, 0, -self::AUTH_TAG_LENGTH_BYTE);
  29. $authTag = substr($ciphertext, -self::AUTH_TAG_LENGTH_BYTE);
  30. return \openssl_decrypt($ctext, 'aes-256-gcm', $this->config->secretV3(), \OPENSSL_RAW_DATA, $nonceStr,
  31. $authTag, $associatedData);
  32. }
  33. throw new \Exception('AEAD_AES_256_GCM需要PHP 7.1以上或者安装libsodium-php');
  34. }
  35. /**
  36. * 隐私数据提供加密方法
  37. * @param $str
  38. * @return string
  39. * @throws \Exception
  40. */
  41. public function encrypt($str)
  42. {
  43. $public_key_path = $this->config->platformCert();
  44. $public_key = file_get_contents($public_key_path);
  45. $encrypted = '';
  46. if (openssl_public_encrypt($str, $encrypted, $public_key, OPENSSL_PKCS1_OAEP_PADDING)) {
  47. //base64编码
  48. $sign = base64_encode($encrypted);
  49. } else {
  50. throw new \Exception('encrypt failed');
  51. }
  52. return $sign;
  53. }
  54. }