如何在#C中将pkcs8密钥文件转换为DER格式?

时间:2010-11-13 08:33:56

标签: c# openssl pkcs#8

如何将pkcs8密钥文件转换为DER格式,以Xml格式获取私钥和​​公钥?

使用openssl我可以使用: openssl pkcs8 -inform DER -in aaa010101aaa_FIEL.key -out aaa.txt

aaa010101aaa_FIEL.key是bynary file

我正在尝试使用Bouncy Castle库,但我有问题要创建新的EncryptedPrivateKeyInfo(...

在java中有一个帖子要做,但我需要在c#中 How to read a password encrypted key with java?

2 个答案:

答案 0 :(得分:1)

BouncyCastle文档相当稀疏,我还没有做到这一点,但你会想要使用Org.BouncyCastle.OpenSsl.PemReader将文件读入(可能)Org.BouncyCastle.Asn1.Pkcs.EncryptedPrivateKeyInfo ,像这样:

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

然后EPKI.GetDerEncoded()会给你DER格式的东西。不能保证这会有效,但PemReader至少应该让你走上正轨。

答案 1 :(得分:1)

我找到了答案!

            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