簡體   English   中英

RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PublicKey.Key 在 .NET Core 中不起作用

[英]RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PublicKey.Key does not work in .NET Core

我有一個用 .NET Framework 2.0(是的,很舊的東西)編譯的程序集,它使用證書的公鑰執行加密。 代碼非常簡單:

X509Certificate2 objCert = new X509Certificate2(path);
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)objCert.PublicKey.Key;
byte [] EncrRes = rsa.Encrypt(data, false);

這繼續適用於所有最新版本的 .NET Framework,但拒絕在 .NET Core 下工作。 我收到兩條不同但相似的錯誤消息。

Windows 10:無法將“System.Security.Cryptography.RSACng”類型的對象轉換為“System.Security.Cryptography.RSACryptoServiceProvider”類型。

Linux:無法將“System.Security.Cryptography.RSAOpenSsl”類型的對象轉換為“System.Security.Cryptography.RSACryptoServiceProvider”類型。

有沒有辦法對這個簡單的操作進行編碼,以便它可以在 .NET Framework 2.0+ 和 .NET core 上運行?

提前致謝。

在 .NET Core 中, X509Certificate2.PublicKey.KeyX509Certificate2.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);

我自己想出來的。 代替

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 Core!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM