問題描述
我需要使用算法 SHA1RSA 用一個私鑰對一些數據進行簽名,Rsa 密鑰長度為 2048,基本編碼為 64.我的代碼是這樣的
I need to sign some data with one private key using Algorithm SHA1RSA ,Rsa Key length 2048 with 64 base encoding.My code is like this
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();
}
在標頭名稱簽名中,我需要使用私鑰傳遞簽名數據(sPayload).但是使用上面的代碼會出現無效簽名"錯誤.來自第三方,我不確定加密部分是否正確.
In the Header name Signature i need to pass the signed data(sPayload) using the private key.But using above code an error is getting as "invalid signature" from third party and i'am not sure whether the Encryption part is correct or not.
httpWebRequest.Headers.Add("SIGNATURE", Convert.ToBase64String(new System.Security.Cryptography.SHA1CryptoServiceProvider().ComputeHash(Encoding.ASCII.GetBytes(sPayload))));
第三方提供了一個證書(cert,sha1)和密鑰.我應該參考代碼嗎?
Third party had provide one certificate(cert,sha1) and key.should i refer that to the code?
推薦答案
您計算了 sPayload
的 SHA-1 哈希,而不是 RSA-SHA1 簽名.
You have computed the SHA-1 hash of sPayload
, not the RSA-SHA1 signature.
如果您有 X509Certificate2:
If you have an X509Certificate2:
using (RSA rsa = cert.GetRSAPrivateKey())
{
return rsa.SignData(sPayload, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
}
如果您已經擁有原始 RSA 密鑰,那么請不要使用 using 語句.
If you already have a raw RSA key then just leave off the using statement.
如果你必須計算 sPayload
的哈希值,你可以這樣做
If you have to compute the hash of sPayload
for some other reason you can do it like
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 值,因為算法標識符嵌入在簽名中.
SignHash still requires the HashAlgorithmName value because the algorithm identifier is embedded within the signature.
這篇關于在 C# 中使用私鑰對數據進行簽名的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!