无法导出RSA私钥参数,不支持请求的操作



我有一个由另一方提供的证书文件,我正在应用程序中加载该文件,无法导出其私钥参数。看起来证书使用的是CNG而不是CryptoAPI,所以我不能直接访问私钥,只能使用GetRSAPrivateKey()方法。该方法返回RSACngKey而不是RSACryptoServiceProvider,后者是RSA的不同实现。问题是,返回的密钥在其导出策略中似乎缺少CngExportPolicies.AllowPlaintextExport,因此我无法从此证书导出RSA参数。我可以通过生成一个错过必要出口政策的新证书来重现这个问题:

using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace TestRsaCngConsole
{
class Program
{
static void Main(string[] args)
{
var oldCertificate = CreateCertificate();
var oldCertificateBytes = oldCertificate.Export(X509ContentType.Pfx, "");
var newCertificate = new X509Certificate2(oldCertificateBytes, "",
X509KeyStorageFlags.Exportable | 
X509KeyStorageFlags.MachineKeySet | 
X509KeyStorageFlags.PersistKeySet);
LogCertificate(oldCertificate, "old certificate"); // this fails
LogCertificate(newCertificate, "new certificate"); // works only on Win10
Console.ReadKey();
}
private static X509Certificate2 CreateCertificate()
{
var keyParams = new CngKeyCreationParameters();
keyParams.KeyUsage = CngKeyUsages.Signing;
keyParams.Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider;
keyParams.ExportPolicy = CngExportPolicies.AllowExport; // here I don't have AllowPlaintextExport
keyParams.Parameters.Add(new CngProperty("Length", BitConverter.GetBytes(2048), CngPropertyOptions.None));
var cngKey = CngKey.Create(CngAlgorithm.Rsa, Guid.NewGuid().ToString(), keyParams);
var rsaKey = new RSACng(cngKey);
var req = new CertificateRequest("cn=mah_cert", rsaKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pss); // requires .net 4.7.2
var cert = req.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(5));
return cert;
}
private static void LogCertificate(X509Certificate2 certificate, string name)
{
Console.WriteLine("----- Testing " + name + " ------");
try
{
var rsaPrivateKey = certificate.GetRSAPrivateKey();
var parameters = rsaPrivateKey.ExportParameters(true);
Console.WriteLine("Certificate private key RSA parameters were successfully exported.");
var privateKey = certificate.PrivateKey;
Console.WriteLine("Certificate private key is accessible.");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}

该程序在Windows 10上运行时显示以下输出:

----- Testing old certificate ------
System.Security.Cryptography.CryptographicException: The requested operation is not supported.
at System.Security.Cryptography.NCryptNative.ExportKey(SafeNCryptKeyHandle key, String format)
at System.Security.Cryptography.CngKey.Export(CngKeyBlobFormat format)
at System.Security.Cryptography.RSACng.ExportParameters(Boolean includePrivateParameters)
at TestRsaCngConsole.Program.LogCertificate(X509Certificate2 certificate, String name) in D:ProjectsTestRsaCngConsoleTestRsaCngConsoleProgram.cs:line 44
----- Testing new certificate ------
Certificate private key RSA parameters were successfully exported.
Certificate private key is accessible.

因此,第一个证书无法导出私钥,因为它的导出策略中缺少AllowPlaintextExport标志。但是在重新加载带有可导出标志的旧证书后,我可以很好地导出新证书参数。然而,它在Windows Server 2012或Windows Server 2016上不起作用,并为这两个证书抛出异常:

----- Testing old certificate ------
System.Security.Cryptography.CryptographicException: The requested operation is not supported.
at System.Security.Cryptography.NCryptNative.ExportKey(SafeNCryptKeyHandle key, String format)
at System.Security.Cryptography.CngKey.Export(CngKeyBlobFormat format)
at System.Security.Cryptography.RSACng.ExportParameters(Boolean includePrivateParameters)
at TestRsaCngConsole.Program.LogCertificate(X509Certificate2 certificate, String name) in D:ProjectsTestRsaCngConsoleTestRsaCngConsoleProgram.cs:line 44
----- Testing new certificate ------
System.Security.Cryptography.CryptographicException: The requested operation is not supported.
at System.Security.Cryptography.NCryptNative.ExportKey(SafeNCryptKeyHandle key, String format)
at System.Security.Cryptography.CngKey.Export(CngKeyBlobFormat format)
at System.Security.Cryptography.RSACng.ExportParameters(Boolean includePrivateParameters)
at TestRsaCngConsole.Program.LogCertificate(X509Certificate2 certificate, String name) in D:ProjectsTestRsaCngConsoleTestRsaCngConsoleProgram.cs:line 44

我需要能够修复证书并使其能够导出RSA参数,即使证书最初缺少AllowPlaintextExport。Windows Server上有什么不同?有办法修复证书吗?

这是.NET Framework的解决方案:

X509Certificate2 cert = new X509Certificate2("certificate.pfx", "password", X509KeyStorageFlags.Exportable);

来源:https://github.com/dotnet/runtime/issues/26031

不幸的是,导出处于该状态的密钥的唯一方法是p/Invoke到NCryptExportKey中以设置加密导出;然后通过NCryptImportKey将其导入到新密钥中,然后将导出策略设置为AllowPlaintextExport。

从.NET Core 3.0开始,这将更容易:

using (RSA exportRewriter = RSA.Create())
{
// Only one KDF iteration is being used here since it's immediately being
// imported again.  Use more if you're actually exporting encrypted keys.
exportRewriter.ImportEncryptedPkcs8PrivateKey(
"password",
rsa.ExportEncryptedPkcs8PrivateKey(
"password",
new PbeParameters(
PbeEncryptionAlgorithm.Aes128Cbc,
HashAlgorithmName.SHA256,
1)),
out _);
return exportRewriter.ExportParameters(true);
}

用于导出加密的.NET核心代码位于https://github.com/dotnet/corefx/blob/64477348da1ff57a43deb65a4b12d32986ed00bd/src/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Export.cs#L126-L237,这不是一个很好的API必须从C#调用。

我测试了整个建议,但它们对我不起作用。最后我找到了一个不同的解决方案,如下所示。

static byte[] DecryptUsingBouncyCastle(byte[] encryptedData)
{
var builder = new Pkcs12StoreBuilder();
var store = builder.Build();
store.Load(File.OpenRead("file path"), "password".ToCharArray());
var alias = store.Aliases.Cast<string>();
var _key = store.GetKey(alias.First());

var cipher = new OaepEncoding(new RsaEngine(), new Sha256Digest(), new Sha1Digest(), null);
cipher.Init(false, _key.Key);

var decrypted = cipher.ProcessBlock(encryptedData, 0, encryptedData.Length);
return decrypted;
}

最新更新