fix: 改为优先从文件读取微信支付私钥,提高可靠性
This commit is contained in:
parent
83fd02c4c0
commit
dfc352a64a
|
|
@ -430,9 +430,34 @@ public class WeChatService : IWeChatService
|
|||
private string SignWithPrivateKey(string message)
|
||||
{
|
||||
using var rsa = RSA.Create();
|
||||
// 处理 JSON 中转义的换行符
|
||||
var privateKey = _options.Pay.PrivateKey.Replace("\\n", "\n");
|
||||
rsa.ImportFromPem(privateKey);
|
||||
|
||||
// 优先从文件读取,如果文件不存在则从配置读取
|
||||
string privateKeyPem;
|
||||
if (!string.IsNullOrEmpty(_options.Pay.PrivateKey) && _options.Pay.PrivateKey.StartsWith("-----BEGIN"))
|
||||
{
|
||||
// 从配置中读取,处理转义的换行符
|
||||
privateKeyPem = _options.Pay.PrivateKey.Replace("\\n", "\n");
|
||||
}
|
||||
else
|
||||
{
|
||||
// 从文件读取
|
||||
var keyPath = Path.Combine(AppContext.BaseDirectory, "apiclient_key.pem");
|
||||
if (!File.Exists(keyPath))
|
||||
{
|
||||
throw new FileNotFoundException($"私钥文件不存在: {keyPath}");
|
||||
}
|
||||
privateKeyPem = File.ReadAllText(keyPath);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
rsa.ImportFromPem(privateKeyPem.AsSpan());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "导入私钥失败,私钥内容长度: {Length}", privateKeyPem.Length);
|
||||
throw;
|
||||
}
|
||||
|
||||
var data = Encoding.UTF8.GetBytes(message);
|
||||
var signature = rsa.SignData(data, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user