SignedData giving Invalid algorithm specified.exception

自作多情 提交于 2019-12-11 08:04:23

问题


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 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");
}

回答1:


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);
}

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).




回答2:


While @Crypt32 gave the best answer (upgrade to .NET Framework 4.6 or better and use GetRSAPrivateKey() and the better version of SignData -- it's been out over 4 years at this point), if you really need to stay on net45, your easiest answer is to open the PFX with X509KeyStorageFlags.Exportable and copy the key into a better provider.

return new X509Certificate2(@"d:\Keys\myCert.pfx", "Pass#@123", X509KeyStorageFlags.Exportable);

...

RSA legacyProv = (RSA)certificate.PrivateKey;
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
provider.ImportParameters(legacyProv.ExportParameters(true));
return provider.SignHash(data, "SHA256");


来源:https://stackoverflow.com/questions/57873061/signeddata-giving-invalid-algorithm-specified-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!