我需要在C#中将ECC证书导入到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。
谢谢!
using SystemX509 = System.Security.Cryptography.X509Certificates;
作为VS/.Net新手,我一定做错了什么?谢谢! - hyongsopusing
指令中使用了别名,即using SystemX509 = System.Security.Cryptography.X509Certificates
。如果不使用别名,VS就能找到该方法。回到最初的目标,根据您对上述问题的回答,P/Invoking是否仍然是将私钥与msCert2
关联的唯一方法?谢谢。 - hyongsop