gpt4 book ai didi

c# - 在 C# 中使用私钥对数据进行签名

转载 作者:太空宇宙 更新时间:2023-11-03 13:02:54 24 4
gpt4 key购买 nike

我需要使用 SHA1RSA 算法用一个私钥对一些数据进行签名,Rsa key 长度为 2048,基本编码为 64。我的代码是这样的

string sPayload = "";
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("URI");
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = WebRequestMethods.Http.Post;

using (StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
sPayload = "{\"id\":\"14123213213\"," +
"\"uid\":\"teller\"," +
"\"pwd\":\"abc123\"," +
"\"apiKey\":\"2343243\"," +
"\"agentRefNo\":\"234324324\"}";

httpWebRequest.Headers.Add("SIGNATURE", Convert.ToBase64String(new System.Security.Cryptography.SHA1CryptoServiceProvider().ComputeHash(Encoding.ASCII.GetBytes(sPayload))));

streamWriter.Write(sPayload);
streamWriter.Flush();
streamWriter.Close();
}

System.Net.ServicePointManager.Expect100Continue = false;

HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
}

在 header 名称签名中,我需要使用私钥传递签名数据(sPayload)。但是使用上面的代码,错误是来自第三方的“无效签名”,我不确定加密部分是否是正确与否。

httpWebRequest.Headers.Add("SIGNATURE", Convert.ToBase64String(new System.Security.Cryptography.SHA1CryptoServiceProvider().ComputeHash(Encoding.ASCII.GetBytes(sPayload))));

第三方提供了一个证书(cert,sha1)和 key 。我应该引用代码吗?

最佳答案

您已经计算了 sPayload 的 SHA-1 哈希,而不是 RSA-SHA1 签名。

如果您有 X509Certificate2:

using (RSA rsa = cert.GetRSAPrivateKey())
{
return rsa.SignData(sPayload, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
}

如果您已经有了原始 RSA key ,那么就不要使用 using 语句。

如果出于某些其他原因必须计算 sPayload 的哈希值,您可以这样做

byte[] hash;
byte[] signature;

using (HashAlgorithm hasher = SHA1.Create())
using (RSA rsa = cert.GetRSAPrivateKey())
{
hash = hasher.ComputeHash(sPayload);
signature = rsa.SignHash(hash, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
}

SignHash 仍然需要 HashAlgorithmName 值,因为算法标识符嵌入在签名中。

关于c# - 在 C# 中使用私钥对数据进行签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31828420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com