将ECDSA公钥从CngKey导入BouncyCastle

时间:2016-10-07 11:51:23

标签: c# bouncycastle ecdsa cng

我正在尝试从使用CngKey生成的一对密钥生成x509证书。 我创建了键:

        var parameters = new CngKeyCreationParameters 
        { 
            Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider, 
            ExportPolicy = CngExportPolicies.AllowPlaintextExport, 
            KeyCreationOptions = CngKeyCreationOptions.OverwriteExistingKey, 
            KeyUsage = CngKeyUsages.AllUsages, 
            UIPolicy = new CngUIPolicy(CngUIProtectionLevels.None) 
        }; 
        var key = CngKey.Create(CngAlgorithm.ECDsaP384, container, parameters); 
        byte[] ecPriKey = key.Export(CngKeyBlobFormat.Pkcs8PrivateBlob); 
        byte[] ecPubKey = key.Export(CngKeyBlobFormat.EccPublicBlob); 

我获得了一个BouncyCastle私钥:

        AsymmetricKeyParameter akPrivate = PrivateKeyFactory.CreateKey(ecPriKey); 

我没有遇到任何麻烦,因此我可以从键中看到正确的曲线参数。

但是,当我尝试使用以下公式获取公钥时

          string publicKeyBase64 = Convert.ToBase64String(ecPubKey); 
          byte[] ecPubKey2 = Base64.Decode(publicKeyBase64); 
          byte[] ecPublicKey = new byte[ecPubKey.Length -7]; 
          ecPublicKey[0] = 0x04; 
          Array.Copy(ecPubKey, 8, ecPublicKey, 7, ecPublicKey.Length); 
          AsymmetricKeyParameter akPublic = PublicKeyFactory.CreateKey(ecPublicKey - 1); 

我读过我必须从CngKey中删除8位数字并添加未压缩的const值0x04。 当我执行" PublicKeyFactory.CreateKey(ecPublicKey)"我得到了例外:

ex  {"extra data found after object"}   System.Exception {System.IO.IOException} 
Data    {System.Collections.ListDictionaryInternal} System.Collections.IDictionary {System.Collections.ListDictionaryInternal} 
            HResult 0x80131620  int 
            HelpLink    null    string 
InnerException  null    System.Exception 
            Message "extra data found after object" string 
            Source  "BouncyCastle.Crypto"   string 
            StackTrace  "   at Org.BouncyCastle.Asn1.Asn1Object.FromByteArray(Byte[] data)\r\n   at Org.BouncyCastle.Security.PublicKeyFactory.CreateKey(Byte[] keyInfoData)\r\n   at Plpm.Csp.Security.KeyTool.SecurityKeyTool.OpGenEc(String[] args) in ..."  string 
TargetSite  {Org.BouncyCastle.Asn1.Asn1Object FromByteArray(Byte[])}    System.Reflection.MethodBase {System.Reflection.RuntimeMethodInfo} 
Static members  
Non-Public members  

无论如何,如果我直接用密钥执行此操作,我会得到相同的异常:

        AsymmetricKeyParameter akPublic = PublicKeyFactory.CreateKey(ecPubKey); 

请有人,请给我一些关于为什么这个错误与公钥有关的想法?

非常感谢你。

0 个答案:

没有答案