Import an ECDSA public key from CngKey to BouncyCastle

3

I am trying to generate an x509 certificate from a pair of keys generated with CngKey. I create the keys with:

        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); 

I get a BouncyCastle private key with:

        AsymmetricKeyParameter akPrivate = PrivateKeyFactory.CreateKey(ecPriKey); 

And I have no trouble in it, so that I can see the proper curve's parameters from the key.

However, when I try to get the public key with:

          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); 

I read I have to erase the 8 first digits from CngKey and add the uncompressed const value 0x04. When I execute "PublicKeyFactory.CreateKey(ecPublicKey)" I get the exception:

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  

Anyway, I get the same exception if I do this directly with the key as:

        AsymmetricKeyParameter akPublic = PublicKeyFactory.CreateKey(ecPubKey); 

Can someone, please, give me some ideas about why is this error with public key?

Thank you so much.

c#
bouncycastle
ecdsa
cng
asked on Stack Overflow Oct 7, 2016 by santiPipes

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0