本文介绍了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 给出指定的算法无效.异常
发布评论