Exception with CreateKey of PublicKeyFactory of BouncyCastle

4.9k views Asked by At

I'm trying to create an AsymmetricKeyParameter public key obj from an xml string like this:

public static AsymmetricKeyParameter xmlStringToPubKey(string xmlStr)
{
    if (String.IsNullOrEmpty(xmlStr))
    {
        return null;
    }
    else
    {
        XDocument xdoc = XDocument.Parse(xmlStr);
        return PublicKeyFactory.CreateKey(Streamify(xdoc.Descendants("Modulus").First().Value));
    }
}

I get the following stack trace:

at Org.BouncyCastle.Asn1.DefiniteLengthInputStream.ToArray() at Org.BouncyCastle.Asn1.Asn1InputStream.BuildObject(Int32 tag, Int32 tagNo, Int32 length) at Org.BouncyCastle.Asn1.Asn1InputStream.ReadObject() at Org.BouncyCastle.Asn1.Asn1Object.FromByteArray(Byte[] data) at Org.BouncyCastle.Security.PublicKeyFactory.CreateKey(Byte[] keyInfoData) at TestConsole.PGP.xmlStringToPubKey(String xmlString) in PGP.cs:line 141 at TestConsole.Test.Main(String[] args) in Test.cs:line 22 at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart()

While there's very little to no documentation for c#, the method (CreateKey) description accepts a byte array or a Stream as parameters. I've tried numerous ways to convert the string into a byte, but still couldn't get it work. Any hints/help appreciated.

1

There are 1 answers

2
Jcs On BEST ANSWER

The PublicKeyFactory.CreateKey method is expecting a stream containing an ASN.1 encoded SubjectPublicKeyInfo structure. The error you get indicates that the stream does not deliver a correctly encoded ASN.1 object.

If you know the type of key you want to create you can directly create the AsymmetricKeyParameter subtype instance from the key parameters.

For example for a RSA key:

BigInteger modulus = new BigInteger(xdoc.Descendants("Modulus").First().Value);
BigInteger exponent = new BigInteger(xdoc.Descendants("Exponenet").First().Value);
AsymmetricKeyParameter param = new RsaKeyParameters(false, modulus, exponent);