X509AsymmetricSecurityKey.GetAsymmetricAlgorithm在.Net 4.7.2升



我在标准单元测试中运行X509AsymmetricSecurityKey.GetAsymmetricAlgorithm时遇到问题。该测试已经在.Net Framework 4.5.2版(C#(上运行了多年,但自从将项目升级到4.7.2版以来,由于GetAsymmetricAlgorithm返回null,该测试一直失败。完全相同的代码在测试之外运行完美。

X509Certificate2 cert = null;
var store = new X509Store(StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
// I'm actually using FindByThumbprint, just changing this here to protect keys
cert = store.Certificates[0];
// cert is valid X509, securityKey is valid
X509AsymmetricSecurityKey securityKey = new X509AsymmetricSecurityKey(cert);
// rsa is null
RSACryptoServiceProvider rsa = securityKey.GetAsymmetricAlgorithm(SecurityAlgorithms.RsaSha256Signature, true) as RSACryptoServiceProvider;

相同的代码,相同的证书,虽然运行测试GetAsymmetricAlgorithm返回null,但在"实时"代码(从WebAPI调用的类库(上运行它非常完美。

有什么想法吗?我在以前.Net版本更改的文档中看不到任何内容,在Microsoft文档中也看不到。

https://learn.microsoft.com/en-us/dotnet/api/system.identitymodel.tokens.x509asymmetricsecuritykey.getasymmetricalgorithm?view=netframework-4.7.2

谢谢你在这方面的帮助。

正如Crypt32在评论中所建议的那样,问题是在您从目标<=升级之后4.6.2到目标4.7(+(,您得到了一个"重定目标的更改",即允许GetAsymmetricAlgorithm返回RSACng的实例,这是.NET Framework中更好的RSA类。

代码中最好的操作是将行更改为

RSA rsa = securityKey.GetAsymmetricAlgorithm(SecurityAlgorithms.RsaSha256Signature, true) as RSA;

然后找到代码不再编译的地方,并从RSACryptoServiceProvider变体方法更改为新的RSA(基类(方法。(例如SignData(byte[], object)=>SignData(byte[], RSASignaturePadding)(。

如果可以的话,你真的想避免说RSACngRSACryptoServiceProvider,因为在理论上,RSACng不起作用,而RSACryptoServiceProvider会被退回(旧的智能卡/HSM有CAPI驱动程序,但没有CNG驱动程序(。

此特定的重定目标更改是的System.IdentityModel版本https://learn.microsoft.com/en-us/dotnet/framework/migration-guide/retargeting/4.5-4.7.2#wcf-传输安全性支持使用cng存储的证书,而cng似乎还没有被写下来。如果需要关闭此选项,则设置名称为Switch.System.IdentityModel.DisableCngCertificates

最新更新