Question

How to convert pkcs8 key file to DER format, to get Private and Public key in Xml format?

with openssl I can do it using: openssl pkcs8 -inform DER -in aaa010101aaa_FIEL.key -out aaa.txt

aaa010101aaa_FIEL.key is bynary file

I'm trying to do it with Bouncy Castle library but I have problems to create new EncryptedPrivateKeyInfo(...

there is a post to do that in java, but i need it in c# How to read a password encrypted key with java?

Was it helpful?

Solution 2

I found the Answer!

            byte[] dataKey = File.ReadAllBytes(fileName);

        Org.BouncyCastle.Crypto.AsymmetricKeyParameter asp =
            Org.BouncyCastle.Security.PrivateKeyFactory.DecryptKey(pass.ToCharArray(), dataKey);

        MemoryStream ms = new MemoryStream();
        TextWriter writer = new StreamWriter(ms);
        System.IO.StringWriter stWrite = new System.IO.StringWriter();
        Org.BouncyCastle.OpenSsl.PemWriter pmw = new PemWriter(stWrite);
        pmw.WriteObject(asp);
        stWrite.Close();
        return stWrite.ToString();

How to Load pkcs8 binary file format key

OTHER TIPS

BouncyCastle documentation is pretty sparse and I haven't done this exact thing, but you will want to use an Org.BouncyCastle.OpenSsl.PemReader to read the file into a (probably) Org.BouncyCastle.Asn1.Pkcs.EncryptedPrivateKeyInfo, like this:

using (FileStream FS = File.Open("whatever.key"))
{
 using (TextReader TR = new StreamReader(FS))
    {
  PR = new Org.BouncyCastle.OpenSsl.PemReader(TR);
  EPKI = (Org.BouncyCastle.Asn1.Pkcs.EncryptedPrivateKeyInfo)PR.ReadObject();
 }
}

and then EPKI.GetDerEncoded() would give you the DER formatted thing. No guarantees that this will work, but PemReader should at least put you on the right track.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top