Convert der to pem through bouncy castle library

烂漫一生 提交于 2019-12-25 14:44:23

问题


I found many answers towards convert from pem to der.

However, I cannot find ways to convert der to pem.

for example, the following codes generates der encoded file pkcs10.cer

public static void main(String[] args) throws Exception
{
    X509Certificate[] chain = buildChain();
    PEMWriter pemWrt = new PEMWriter(new OutputStreamWriter(System.out));
    pemWrt.writeObject(chain[0]);

    FileWriter fwO = new FileWriter("pkcs10.cer");
    fwO.write((chain[0]).toString());

    fwO.close();
    pemWrt.close();

}

Like, [0] Version: 3 SerialNumber: 1353995641265 IssuerDN: CN=Test Certificate Start Date: Mon Nov 26 21:54:01 PST 2012 Final Date: Mon Nov 26 21:54:51 PST 2012

However, I don't know how to make pem encoded Certification from der files.


回答1:


I'm not a Java developer, and therefore I cannot show you code or point to a class. PEM is just the Base64 encoding of the binary DER, with a standard header and trailer.




回答2:


Below is a method that will convert various BC objects to PEM string serialized format. Note this code is for the C# version of BC but should translate to the Java version without much effort.

// converts bouncy castle objects of type
// X509Certificate, X509Crl, AsymmetricCipherKeyPair, AsymmetricKeyParameter,
// IX509AttributeCertificate, Pkcs10CertificationRequest, Asn1.Cms.ContentInfo 
// to PEM format string
public string ToPem(object obj)
{
    using (MemoryStream mem = new MemoryStream())
    {
        StreamWriter writer = new StreamWriter(mem);
        Org.BouncyCastle.OpenSsl.PemWriter pem = new Org.BouncyCastle.OpenSsl.PemWriter(writer);
        pem.WriteObject(obj);
        // force the pem write to flush it's data - kind of abnoxious you have to do that
        pem.Writer.Flush();
        // create a stream reader to read the data.
        StreamReader reader = new StreamReader(mem);
        mem.Position = 0;
        string pemStr = reader.ReadToEnd();
        return pemStr;
    }
}


来源:https://stackoverflow.com/questions/13565532/convert-der-to-pem-through-bouncy-castle-library

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