Write x509 certificate into PEM formatted string in java?

后端 未结 10 2316
天涯浪人
天涯浪人 2020-12-07 15:48

Is there some high level way to write an X509Certificate into a PEM formatted string? Currently I\'m doing x509cert.encode() to write it into a DER formatted string, then ba

10条回答
  •  臣服心动
    2020-12-07 16:11

    If you have PEMWriter from bouncy castle, then you can do the following :

    Imports :

    import org.bouncycastle.openssl.PEMWriter;
    

    Code :

    /**
     * Converts a {@link X509Certificate} instance into a Base-64 encoded string (PEM format).
     *
     * @param x509Cert A X509 Certificate instance
     * @return PEM formatted String
     * @throws CertificateEncodingException
     */
    public String convertToBase64PEMString(Certificate x509Cert) throws IOException {
        StringWriter sw = new StringWriter();
        try (PEMWriter pw = new PEMWriter(sw)) {
            pw.writeObject(x509Cert);
        }
        return sw.toString();
    }
    

提交回复
热议问题