RSACryptServiceProvider rsa=(RSACryptServiceProvider)cert.PublicKey.Key在.NET Core中不工作

RSACryptServiceProvider rsa=(RSACryptServiceProvider)cert.PublicKey.Key在.NET Core中不工作,.net,.net-core,x509certificate2,.net,.net Core,X509certificate2,我有一个用.NETFramework2.0编译的程序集(是的,非常旧的东西),它用证书的公钥执行加密。代码非常简单: X509Certificate2 objCert = new X509Certificate2(path); RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)objCert.PublicKey.Key; byte [] EncrRes = rsa.Encrypt(data, false); 这将继续适用于所有最新

我有一个用.NETFramework2.0编译的程序集(是的,非常旧的东西),它用证书的公钥执行加密。代码非常简单:

X509Certificate2 objCert = new X509Certificate2(path);
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)objCert.PublicKey.Key;
byte [] EncrRes = rsa.Encrypt(data, false);
这将继续适用于所有最新版本的.NETFramework,但拒绝在.NETCore下工作。我收到两条不同但相似的错误消息

Windows 10: 无法将类型为“System.Security.Cryptography.RSACng”的对象强制转换为类型为“System.Security.Cryptography.rsacCryptoServiceProvider”

Linux: 无法将“System.Security.Cryptography.RSAOpenSsl”类型的对象强制转换为“System.Security.Cryptography.RSACryptServiceProvider”类型

有没有一种方法可以对这个简单的操作进行编码,这样它就可以在.NETFramework2.0+和.NETCore上工作


提前谢谢。

我自己想出来的。而不是

RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)objCert.PublicKey.Key;


与.NET2.0+和.NETCore配合使用

是我自己想出来的。而不是

RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)objCert.PublicKey.Key;


与.NET2.0+和.NETCore配合使用

在.NET内核中,
X509Certificate2.PublicKey.Key
X509Certificate2.PrivateKey
使用特定于平台的密钥实现。在Windows上,有两种实现,传统的
rsaccryptoserviceprovider
和现代的
RSACng

您必须更改访问这些属性的方式。不要访问它们。相反,请使用扩展方法:。它们返回您应该使用的安全抽象类。不要尝试对任何内容使用显式强制转换。对于
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);

在.NET内核中,
X509Certificate2.PublicKey.Key
X509Certificate2.PrivateKey
使用特定于平台的密钥实现。在Windows上,有两种实现,传统的
rsaccryptoserviceprovider
和现代的
RSACng

您必须更改访问这些属性的方式。不要访问它们。相反,请使用扩展方法:。它们返回您应该使用的安全抽象类。不要尝试对任何内容使用显式强制转换。对于
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);

为什么您需要那个旧的
rsacyptoserviceprovider
?人们真的不鼓励使用它。在我的另一个响应中找到正确的方法。为了向后兼容,.NET Core与.NET 2.0不向后兼容。但是,为.NET 2.0编写的组件如果编码正确,可以与.NET Core一起使用。使用这种方法,您只能使用Windows,不能从.NET Core跨平台中获得任何好处。您的代码不会在Linux或Mac上运行,因为没有这样的
rsacyptoserviceprovider
类。为什么需要旧的
rsacyptoserviceprovider
?人们真的不鼓励使用它。在我的另一个响应中找到正确的方法。为了向后兼容,.NET Core与.NET 2.0不向后兼容。但是,为.NET 2.0编写的组件如果编码正确,可以与.NET Core一起使用。使用这种方法,您只能使用Windows,不能从.NET Core跨平台中获得任何好处。您的代码不会在Linux或Mac上运行,因为没有此类
rsacryptserviceprovider
类。感谢您的响应,但是.NET 2.0中没有GetRsaPublicKey。我已经在下面找到并发布了一个解决方案。感谢您的回复,但是GetRsaPublicKey在.NET2.0中不可用。我已经在下面找到并发布了一个解决方案。