How to convert pkcs8 key file to DER format in #C?

旧巷老猫 提交于 2019-12-10 12:15:05

问题


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?


回答1:


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.




回答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



来源:https://stackoverflow.com/questions/4171658/how-to-convert-pkcs8-key-file-to-der-format-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!