我们有一个自签名 CA 证书,其私钥存储在 HSM 解决方案中。我们需要创建一个由 CA 证书通过 .NET 代码签名的短期 X.509 证书。短期 X.509 证书将用于通过 TLS/HTTPS 对基于 REST 的服务进行客户端证书身份验证。
HSM 解决方案使用密钥存储提供程序 (KSP) 与 Microsoft 证书存储的集成,因此必须使用下一代加密 (CNG) 库来获取私钥。
通过 X509CertificateExtensions.GetCngPrivateKey() 我们能够访问代表私钥的 CngKey 对象。
但是,我们不能将 CngKey 与 BouncyCastle 一起使用
AsymmetricCipherKeyPair issuerKeyPair=null;
if (issuerCertificate.HasCngKey())
{
var cngPrivateKey = issuerCertificate.GetCngPrivateKey();
var rsa = new RSACng(cngPrivateKey);
issuerKeyPair = DotNetUtilities.GetRsaKeyPair(privateKey);
}
失败并引发以下异常
System.Security.Cryptography.CryptographicException: Invalid type specified.
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)
编辑:认为失败的原因是 DotNetUtilities.GetRsaKeyPair 尝试通过 rsa.ExportParameters(true) 导出私钥。HSM 不允许这样做,它会引发异常。似乎需要一种不同的方式来引用私钥
编辑#2:向 Bouncy Castle 提出了功能请求,并且有关于如何将其作为框架的一部分实现的响应。