Csharp/C#教程:使用c#中的私钥对数据进行签名分享


使用c#中的私钥对数据进行签名

我需要使用一个私钥使用算法SHA1RSA,Rsa密钥长度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(); } 

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

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

第三方提供了一个证书(证书,sha1)和密钥。我应该将其引用到代码中吗?

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

如果您有X509Certificate2:

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

如果您已经有一个原始RSA密钥,那么就不要使用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#中的私钥对数据进行签名分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/988266.html

(0)
上一篇 2021年12月23日
下一篇 2021年12月23日

精彩推荐