我有一个用.NET Framework2.0(是的,非常旧的东西)编译的程序集,它使用证书的公钥执行加密。代码非常简单:
X509Certificate2 objCert = new X509Certificate2(path);
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)objCert.PublicKey.Key;
byte [] EncrRes = rsa.Encrypt(data, false);这继续适用于所有最新版本的.NET框架,但拒绝在.NET核心下工作。我得到了两个不同但相似的错误消息。
'System.Security.Cryptography.RSACryptoServiceProvider'. 10:无法将类型为System.Security.Cryptography.RSACng的对象强制转换为Windows类型
Linux:无法将'System.Security.Cryptography.RSAOpenSsl‘类型的对象强制转换为'System.Security.Cryptography.RSACryptoServiceProvider'.类型
有没有办法对这个简单的操作进行编码,这样它就可以同时在.NET框架2.0+和.NET核心上工作?
提前谢谢。
发布于 2020-02-07 04:46:57
在.NET核心中,X509Certificate2.PublicKey.Key和X509Certificate2.PrivateKey使用特定于平台的密钥实现。在Windows上,有两种实现,传统的RSACryptoServiceProvider和现代的RSACng。
您必须更改访问这些属性的方式。并且不能访问它们。相反,使用扩展方法:X509Certificate2 Extension Methods。它们返回您应该使用的安全抽象类。不要试图对任何内容使用显式强制转换。对于RSA密钥,使用RSA类,依此类推。
X509Certificate2 objCert = new X509Certificate2(path);
// well, it is reasonable to check the algorithm of public key. If it is ECC,
// then call objCert.GetECDsaPublicKey()
RSA rsa = objCert.GetRsaPublicKey();
byte [] EncrRes = rsa.Encrypt(data, RSAEncryptionPadding.Pkcs1);发布于 2020-02-07 04:46:10
我自己想出来的。而不是
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)objCert.PublicKey.Key;做
RSA rsa_helper = (RSA)objCert.PublicKey.Key;
RSAParameters certparams = rsa_helper.ExportParameters(false);
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
RSAParameters paramcopy = new RSAParameters();
paramcopy.Exponent = certparams.Exponent;
paramcopy.Modulus = certparams.Modulus;
rsa.ImportParameters(paramcopy);可与.NET 2.0+和.NET核心配合使用!
https://stackoverflow.com/questions/60102646
复制相似问题