如果可以,您應該避免使用RSACryptoServiceProvider
。它只適用於Windows(並且它是Windows上不太好的RSA實現)。堅持以RSA
基類,並通過RSA.Create()
短暫按鍵(創建)
.NET核心
using (RSA rsa = RSA.Create())
{
rsa.KeySize = desiredKeySizeInBits;
// when the key next gets used it will be created at that keysize.
DoStuffWithThePrivateKey(rsa);
}
.NET框架
不幸的是,默認爲RSA創建新實例。 .NET Framework上的Create()是RSACryptoServiceProvider,它不尊重set_KeySize。所以,如果你需要短暫的鍵,你就需要在.NET框架使用不同的代碼VS .NET核心:
using (RSA rsa = new RSACng())
{
rsa.KeySize = desiredKeySizeInBits;
DoStuffWithThePrivateKey(rsa);
}
或者,如果你需要更早版本的支持比4.6(其中RSACng不存在)/ 4.6.2(其中大部分的.NET Framework與RSACng愉快合作對象,而不是對象的RSACryptoServiceProvider),您可以繼續使用老的實現:
using (RSA rsa = new RSACryptoServiceProvider(desiredKeySizeInBits))
{
// Since before net46 the Encrypt/Decrypt, SignData/VerifyData, SignHash/VerifyHash
// methods were not defined at the RSA base class, you might need to keep this strongly
// typed as RSACryptoServiceProvider.
DoStuffWithThePrivateKey(rsa);
}
短暫按鍵(進口)
即使RSACng,一般來說,比RSACr更容易使用yptoServiceProvider,應該的RSACryptoServiceProvider在這方面做工精細,所以RSA.Create()是所有平臺上的好:
using (RSA rsa = RSA.Create())
{
rsa.ImportParameters(rsaParameters);
DoStuffWithWhateverKindOfKeyYouImported(rsa);
}
從證書:
.NET核心1.0+,.NET框架4.6+
using (RSA rsa = cert.GetRSAPublicKey())
{
DoStuffWithThePublicKey(rsa);
}
或
using (RSA rsa = cert.GetRSAPrivateKey())
{
DoStuffWithThePrivateKey(rsa);
}
.NET框架< 4。6
// Do NOT put this in a using block, since the object is shared by all callers:
RSA rsaPrivate = (RSA)cert.PrivateKey;
DoStuffWithThePrivateKey(rsaPrivate);
// Do NOT put this in a using block, since the object is shared by all callers:
RSA rsaPublicOnly = (RSA)cert.PublicKey.Key;
DoStuffWithThePublicKey(rsaPublic);
使用名爲/持久化的按鍵(僅Windows)
我要包括有關的RSACryptoServiceProvider(操作系統+/CAPI)和RSACng(Win7的+/CNG)創建/打開一個名爲鍵一些樣品,但這在.NET中不是很常見的情況;並且它肯定不是可移植的(可移植到其他操作系統是.NET Core更有吸引力的參數之一)。
引用的東西。
對於.NET Core 1.0和1.1,您可以訪問System.Security.Cryptography.Algorithms
軟件包中的RSA基類。在.NET Core 2.0中,它將包含在netstandard
軟件包參考中。
如果需要做複雜的互操作與您可以參考OS System.Security.Cryptography.Cng
(視窗CNG),System.Security.Cryptography.Csp
(視窗CAPI/CryptoServiceProvider),或System.Security.Cryptography.OpenSsl
(Linux的OpenSSL的,MacOS的OpenSSL的),並獲得了能互操作的訪問類(RSACng,RSACryptoServiceProvider,RSAOpenSsl)。但是,真的,你不應該那樣做。
RSA.Create()返回什麼?
- .NET Framework:RSACryptoServiceProvider,除非被CryptoConfig更改。
- .NET Core(Windows):通過CNG實現RSA的私有類,您不能將其轉換爲更具體的類型。
- .NET Core(Linux):一個通過OpenSSL實現RSA的私有類,您不能將它轉換爲更具體的類型。
- .NET Core(macOS):一個通過OpenSSL實現RSA的私有類,您不能將它轉換爲更具體的類型。 (這應該通過.NET Core的下一個版本中的SecureTransforms)
嗨巴頓,你可以發佈一個在Linux中使用OpenSSL的工作示例代碼。我使用RSACryptoServiceProvider和CspParameters在iss中部署我的項目以生成jwt,並且它工作良好。 [Git Repo](https://github.com/lonemario/SHS.Authentication) –
@MarioRighi我不確定你在問什麼。可能你想要問一個不同的/更具體的新問題。 – bartonjs