BouncyCastle undefined length ASN1
I found some bugreports on your problem with possible workarounds outlined. I don't have an appropriate environment to test this myself - sorry. But from the history it looks like it hasn't really been resolved:
- Bugreport:
This explicitly states problems with BouncyCastle just like you experience. Sebastian Pouliot posts a sample code in comment3 that he thinks can be used (or parts of it) to work around the problem using mono.security.dll. I don't know if your usecase allows to use it. It is shipped with MonoDroid.
He goes into details in this comment and has the example code linked on github: https://github.com/mono/mono/blob/master/mcs/tools/security/makecert.cs
- There is also someone else who posted a problem with this. BouncyCastle is not explicitly mentioned: http://lists.ximian.com/pipermail/mono-bugs/2010-October/104908.html
His workaround at the end of post:
[Once you have the correct PKCS#12] Quote:
Write the byte[] PKCS#12 into a temporary file and load it with string constructor.
Update on source provided in comments
Hope my system worked correctly as it took hours to get it running. But then I got the following working.
The solution is to change the StoreBuilder to UseDEREncoding to true
Small bugfix up front
Finding: You put in a string.empty as password but protected the cert with a password. I think this is not correct. If I put in the password I get the first error again CryptographicException Certificate cannot be coded to valid certificate.
So first I changed this:
certificate = new X509Certificate2(pkcsPath, string.Empty);
to
certificate = new X509Certificate2(pkcsPath, certPassword);
Fix
And now I don't know if this is what you want but after changing it I didn't get an exception but a certificate object.
The complete changes of the "using memory stream" block finally looked like this:
using (MemoryStream pfxData = new MemoryStream())
{
// **Change 1**: The DER Encoding is enabled on the
// store builder
Pkcs12StoreBuilder builder = new Pkcs12StoreBuilder();
builder.SetUseDerEncoding(true);
Pkcs12Store pkcsStore = builder.Build();
// change - end
X509CertificateEntry[] chain = new X509CertificateEntry[1];
string certPassword = Guid.NewGuid().ToString();
chain[0] = new X509CertificateEntry(x509);
pkcsStore.SetKeyEntry(applicationName, new AsymmetricKeyEntry(subjectKeyPair.Private), chain);
pkcsStore.Save(pfxData, certPassword.ToCharArray(), random);
var pkcsPath = pkcsStorePath + "/pkcs.p12";
File.WriteAllBytes(pkcsPath, pfxData.ToArray());
// **Change 2**: Use certificate password
certificate = new X509Certificate2(pkcsPath, certPassword);
// **Change 3**: Possible to use array instead of filename
// works as well. Just uncomment
//certificate = new X509Certificate2(pfxData.ToArray(), certPassword);
}