【发布时间】:2021-03-09 08:22:23
【问题描述】:
我有一个需要为证书私钥设置权限的要求,我使用了以下方法 (SetCertificatePrivateKeyPermissions),该方法在 .Net framework 4.7.2上运行良好> 但是现在我不得不将项目框架迁移到 .Net 5,由于这个项目框架升级,这个现有的代码被破坏了。
RSACryptoServiceProvider 和 CspParameters 类是指 System.Security.Cryptography.Csp.dll (C:\Program Files\dotnet\packs\Microsoft.NETCore.App.Ref\5.0.0\ref\net5.0\System.Security .Cryptography.Csp.dll),通过这个 dll 参考,我面临现有代码的 2 个问题
-
在将 certificate.PrivateKey 转换为 RSACryptoServiceProvider 期间,它返回 NULL。
-
在创建 CspParameters 的实例时,我无法从 rsa 分配 CryptoKeySecurity 值,因为 .NET 5 的 RSACryptoServiceProvider 和 CspParameters 类都不可用/支持此属性,而 .NET 4.7.2 版本支持它。
请告诉我如何处理这个问题?或者是否有任何替代解决方案可以让我在 .NET 5 中设置证书私钥的权限?
代码sn-p:
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
public static void SetCertificatePrivateKeyPermissions(X509Certificate2 certificate, IdentityReference account, Operation operation)
{
var rsa = certificate.PrivateKey as RSACryptoServiceProvider;
if (rsa != null)//ISSUE 1: rsa is NULL
{
var cspParams = new CspParameters(rsa.CspKeyContainerInfo.ProviderType, rsa.CspKeyContainerInfo.ProviderName, rsa.CspKeyContainerInfo.KeyContainerName)
{
Flags = CspProviderFlags.UseExistingKey | CspProviderFlags.UseMachineKeyStore,
CryptoKeySecurity = rsa.CspKeyContainerInfo.CryptoKeySecurity//ISSUE 2: There is no CryptoKeySecurity property present
};
switch (operation)
{
case Operation.Add:
cspParams.CryptoKeySecurity.AddAccessRule(new CryptoKeyAccessRule(account, CryptoKeyRights.GenericRead, AccessControlType.Allow));
break;
case Operation.Remove:
cspParams.CryptoKeySecurity.RemoveAccessRule(new CryptoKeyAccessRule(account, CryptoKeyRights.GenericAll, AccessControlType.Allow));
break;
default:
throw new ArgumentException("Unhandled operation type");
}
using (var rsa2 = new RSACryptoServiceProvider(cspParams))
{
}
}
}
【问题讨论】:
-
没有“.NET 5 框架”。只有 .NET 5。
标签: c# .net-core .net-5 x509certificate2 rsacryptoserviceprovider