refactor(tenpayv3): 优化加解密及哈希算法工具类

This commit is contained in:
Fu Diwei
2024-02-05 10:53:59 +08:00
committed by RHQYZ
parent 70315cd128
commit 70611189cc
25 changed files with 788 additions and 671 deletions

View File

@@ -1,8 +1,9 @@
using System;
using System.Text;
namespace SKIT.FlurlHttpClient.Wechat.TenpayV3
{
using SKIT.FlurlHttpClient.Primitives;
public static class WechatTenpayClientEventDecryptionExtensions
{
/// <summary>
@@ -14,7 +15,7 @@ namespace SKIT.FlurlHttpClient.Wechat.TenpayV3
public static WechatTenpayEvent DeserializeEvent(this WechatTenpayClient client, string webhookJson)
{
if (client is null) throw new ArgumentNullException(nameof(client));
if (string.IsNullOrEmpty(webhookJson)) throw new ArgumentNullException(webhookJson);
if (webhookJson is null) throw new ArgumentNullException(webhookJson);
return client.JsonSerializer.Deserialize<WechatTenpayEvent>(webhookJson);
}
@@ -56,11 +57,11 @@ namespace SKIT.FlurlHttpClient.Wechat.TenpayV3
try
{
plainJson = Utilities.AESUtility.DecryptWithGCM(
key: client.Credentials.MerchantV3Secret,
nonce: webhookEventResource.Nonce,
aad: webhookEventResource.AssociatedData,
cipherText: webhookEventResource.CipherText
);
encodingKey: new EncodedString(client.Credentials.MerchantV3Secret, EncodingKinds.Literal),
encodingNonce: new EncodedString(webhookEventResource.Nonce, EncodingKinds.Literal),
encodingAssociatedData: new EncodedString(webhookEventResource.AssociatedData, EncodingKinds.Literal),
encodingCipher: new EncodedString(webhookEventResource.CipherText, EncodingKinds.Base64)
)!;
}
catch (Exception ex)
{
@@ -75,17 +76,17 @@ namespace SKIT.FlurlHttpClient.Wechat.TenpayV3
{
// REF: https://pay.weixin.qq.com/docs/merchant/development/shangmi/guide.html
// 由于 SM4 密钥长度的限制,密钥由 APIv3 密钥通过国密 SM3 Hash 计算生成。SM4 密钥取其摘要256bit的前 128bit。
byte[] secretBytes = Utilities.SM3Utility.Hash(Encoding.UTF8.GetBytes(client.Credentials.MerchantV3Secret));
byte[] secretBytes = Utilities.SM3Utility.Hash(EncodedString.FromLiteralString(client.Credentials.MerchantV3Secret));
byte[] keyBytes = new byte[16];
Array.Copy(secretBytes, keyBytes, keyBytes.Length);
byte[] plainBytes = Utilities.SM4Utility.DecryptWithGCM(
keyBytes: keyBytes,
nonceBytes: Encoding.UTF8.GetBytes(webhookEventResource.Nonce),
aadBytes: webhookEventResource.AssociatedData is null ? null : Encoding.UTF8.GetBytes(webhookEventResource.AssociatedData),
cipherBytes: Convert.FromBase64String(webhookEventResource.CipherText)
nonceBytes: EncodedString.FromLiteralString(webhookEventResource.Nonce),
associatedDataBytes: EncodedString.FromLiteralString(webhookEventResource.AssociatedData),
cipherBytes: EncodedString.FromBase64String(webhookEventResource.CipherText)
);
plainJson = Encoding.UTF8.GetString(plainBytes);
plainJson = EncodedString.ToLiteralString(plainBytes).Value!;
}
catch (Exception ex)
{