SignedData 给出指定的算法无效.异常

编程入门 行业动态 更新时间:2024-10-28 05:20:06
本文介绍了SignedData 给出指定的算法无效.异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我尝试使用 myCert.pfx 文件私钥和公钥对我的签名数据进行签名和验证.但是在签署数据时,我得到指定的算法无效".异常

I tried to sign and valid my signed data using myCert.pfx file private and public key. But while signing the data I am getting " Invalid algorithm specified." exception

我们使用的.Net框架是4.5,代码如下

.Net framework we are using is 4.5 and the code is as below

public static void CallMainMethod() { string str = "Sign and verify the data"; X509Certificate2 certificate = LoadPrivateKey(); byte[] hashBytes = GetDataHash(str); byte[] signature = GetDigitalSignature(hashBytes); } private static X509Certificate2 LoadPrivateKey() { return new X509Certificate2(@"d:\Keys\myCert.pfx", "Pass#@123"); } private static byte[] GetDataHash(string sampleData) { //choose any hash algorithm SHA256Managed managedHash = new SHA256Managed(); return managedHash.ComputeHash(Encoding.Unicode.GetBytes(sampleData)); } private static byte[] GetDigitalSignature(byte[] data) { X509Certificate2 certificate = LoadPrivateKey(); RSACryptoServiceProvider provider = (RSACryptoServiceProvider)certificate.PrivateKey; return provider.SignHash(data, "SHA256"); }

推荐答案

我相信旧的 RSACryptoServiceProvider 不支持 SHA2 算法.将最后一个方法改写如下:

I believe that legacy RSACryptoServiceProvider doesn't support SHA2 algorithms. Rewrite last method as follows:

private static byte[] GetDigitalSignature(byte[] data) { X509Certificate2 certificate = LoadPrivateKey(); RSA provider = certificate.GetRSAPrivateKey(); return provider.SignHash(data, "SHA256", RSASignaturePadding.Pkcs1); }

从 .NET Framework 4.6 及更高版本开始,这种风格是首选(@bartonjs,如果我对 .NET 版本有错误,请纠正我).

This style is preferred as of .NET Framework 4.6 and above (@bartonjs, please correct me if I'm wrong in regards to .NET version).

更多推荐

SignedData 给出指定的算法无效.异常

本文发布于:2023-11-09 19:24:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1573216.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:算法   异常   SignedData

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!