May 30, 2018

How to Read PEM or DER Encoded Certificate In Java

import java.io.InputStream;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

import org.junit.Test;

public class PEMTest {

    /**
     * 

* In the case of a certificate factory for X.509 certificates, the certificate provided in {@code inStream} must be * DER-encoded and may be supplied in binary or printable (Base64) encoding. If the certificate is provided in * Base64 encoding, it must be bounded at the beginning by -----BEGIN CERTIFICATE-----, and must be bounded at the * end by -----END CERTIFICATE-----. * * @throws Exception */ @Test public void readX509Certificate() throws Exception { CertificateFactory factory = CertificateFactory.getInstance("X.509"); InputStream input = ClassLoader.getSystemResourceAsStream("server.cert.pem"); X509Certificate cert = (X509Certificate) factory.generateCertificate(input); System.out.println(cert); } }

No comments: