2017-07-14 65 views
2

我需要將ECC證書導入C#中的Windows Key Stores。作爲第一步,我使用BouncyCastle的生成EC密鑰對,創建具有公共密鑰X509證書,並與ECDSA和私有密鑰,即簽署,:從ECC創建X509Certificate2 X509Certificate在C#中拋出'System.NotSupportedException'

  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.ToX509Certific ate()導致相同的異常。

我知道在Windows/.NET上對ECC證書的支持可能不完整,但我在網上的搜索似乎表明這應該是可能的?任何想法我做錯了什麼?我想使用VS社區2017,我的項目的目標是.NET Framework 4.6.2。

謝謝!

回答

1

PublicKey.Key非正式棄用(與PrivateKey一起)。它不支持ECC,並且不會生成能夠執行OAEP-SHA-2加密或能夠執行FIPS 186-3 DSA的DSA密鑰的RSA密鑰。

相反,你要使用的擴展方法不需要鑄造:

// 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 
} 
+0

最後,我想創建PKCS12並將其導入密鑰庫,類似於目標的HTTPS:/ /stackoverflow.com/questions/36624105/generate-certificate-using-ecdsa-in-c-sharp在那裏你也提供了非常有用的答案。目前,我發現雖然我使用SystemX509 = System.Security.Cryptography導入System.Security.Cryptography.X509Certificates命名空間,即' ',''GetECDsaPublicKey()擴展方法在'msCert2'上不可用。 X509Certificates;'作爲VS/.Net新手,我一定是做錯了什麼?謝謝! – hyongsop

+0

@hyongsop在4.6.1中增加了擴展方法。如果你得到一個編譯時錯誤,檢查你確實引用了4.6.2,而不是隻安裝它(VS似乎喜歡將舊版本的框架定位)。 – bartonjs

+0

該項目具有「.NET Framework 4.6.2」作爲其目標框架,並具有對System.Security.dll在C:\ Program Files(x86)\ Reference Assemblies \ Microsoft \ Framework \ .NETFramework \ v4.6.2 \ System.Security.dll。是否有我缺少的VS範圍配置? – hyongsop

相關問題