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

时间:2015-08-05 09:23:44

标签: c# cryptography httprequest rsa digital-signature

我需要使用一个私钥使用算法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)和密钥。我应该将其引用到代码中吗?

1 个答案:

答案 0 :(得分:0)

您计算了@Component({ moduleId: module.id, selector: 'vx-alert', templateUrl: 'alert.html' }) export class AlertComponent extends I18N implements OnInit { @Input('class') initialClassList: string; @HostBinding('class') private classList:string; ngOnInit() { this.classList = this.initialClassList + ' au-ease-in-out au-20000ms'; } } 的SHA-1哈希,而不是RSA-SHA1签名。

如果您有X509Certificate2:

sPayload

如果您已有原始RSA密钥,则只需取消使用声明。

如果由于其他原因需要计算using (RSA rsa = cert.GetRSAPrivateKey()) { return rsa.SignData(sPayload, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); } 的哈希值,可以像

那样进行计算
sPayload

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