我需要将ECC证书导入C#中的Windows密钥库。作为第一步,我使用BouncyCastle生成EC密钥对,使用公钥创建X509证书,并使用ECDSA和私钥对其进行签名,即:
var ecKeyPairGenerator = new ECKeyPairGenerator("ECDSA");
ECKeyGenerationParameters ecKeyGenParams =
new ECKeyGenerationParameters(SecObjectIdentifiers.SecP384r1, new SecureRandom());
ecKeyPairGenerator.Init(ecKeyGenParams);
AsymmetricCipherKeyPair pair = ecKeyPairGenerator.GenerateKeyPair();
PrivateKeyInfo privKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(pair.Private);
SubjectPublicKeyInfo pubKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pair.Public);
X509V3CertificateGenerator bcX509Gen = new X509V3CertificateGenerator();
// set cert fields
...
bcX509Gen.SetPublicKey(pair.Public);
Asn1SignatureFactory bcSigFactory =
new Asn1SignatureFactory(X9ObjectIdentifiers.ECDsaWithSha384.Id, pair.Private);
X509Certificate bcCert = bcX509Gen.Generate(bcSigFactory);
然后,我使用上面创建的证书创建一个X509Certificate2,即:
SystemX509.X509Certificate2 msCert2 =
new SystemX509.X509Certificate2(bcCert.GetEncoded(), (string)null);
但是,在创建X509Certificate2:
时会出现异常'msCert2.PublicKey.Key' threw an exception of type 'System.NotSupportedException'
"The certificate key algorithm is not supported."
使用BC的DotNetUtilities.ToX509Certificate()会导致相同的异常。
我知道在Windows / .NET上对ECC证书的支持可能不完整,但我在网上搜索似乎表明这应该是可能的?我有什么想法吗?
仅供参考,我正在使用VS Community 2017,我的项目的目标是.NET Framework 4.6.2。
谢谢!
答案 0 :(得分:2)
PublicKey.Key
已被非正式弃用(以及PrivateKey
)。它不支持ECC,也不会生成能够执行OAEP-SHA-2加密的RSA密钥或能够执行FIPS 186-3 DSA的DSA密钥。
相反,您希望使用不需要强制转换的扩展方法:
// GetECDsaPublicKey returns a unique object every call,
// so you're responsible for Disposing it (lest it end up on the Finalizer queue)
using (ECDsa ecdsa = msCert2.GetECDsaPublicKey())
{
// do stuff with the public key object
}