Convert der to pem through bouncy castle library

2019-09-08 08:40发布

问题:

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