Read different certificate/key file formats with Java
Read a PEM or binary DER X509 certificate / public key
import java.io.FileInputStream;
import java.security.PublicKey;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
(...)
try {
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
FileInputStream is = new FileInputStream("THE_X509_CERTIFICATE_PEM_FILE_PATH");
X509Certificate cer = (X509Certificate) certFactory.generateCertificate(is);
PublicKey key = cer.getPublicKey();
} catch (Exception e) {
e.printStackTrace();
}
Read a PEM PKCS1 or PKCS8 private key
Use the PEM Parser from bouncy castle to easily read PEM in different formats.
import java.io.FileReader;
import java.io.IOException;
import java.security.PrivateKey;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
(...)
PEMParser reader = null;
try {
reader = new PEMParser(new FileReader("THE_PEM_ENCODED_FILE_PATH"));
PrivateKeyInfo info = null;
// the return type depends on whether the file contains a single key or a key pair
Object bouncyCastleResult = reader.readObject();
if (bouncyCastleResult instanceof PrivateKeyInfo) {
info = (PrivateKeyInfo) bouncyCastleResult;
} else if ( bouncyCastleResult instanceof PEMKeyPair ) {
PEMKeyPair keys = (PEMKeyPair) bouncyCastleResult;
info = keys.getPrivateKeyInfo();
} else {
throw new Exception("No private key found in the provided file");
}
JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
PrivateKey privateKeyJava = converter.getPrivateKey(info);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
Read a binary encoded (DER) PKCS1 private key
Reading PKCS1 encoded keys in Java is trickier as there is not direct support. Bouncy castle provides with tools to achieve this.
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.PrivateKey;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERNull;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.pkcs.RSAPrivateKey;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
(...)
try {
String privateKeyFileName = "THE_BINARY_ENCODED_FILE_PATH";
Path path = Paths.get(privateKeyFileName);
byte[] privKeyByteArray = Files.readAllBytes(path);
ASN1Sequence seq = ASN1Sequence.getInstance(privKeyByteArray);
RSAPrivateKey bcPrivateKey = RSAPrivateKey.getInstance(seq);
JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
AlgorithmIdentifier algId = new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE);
PrivateKey privateKeyJava = converter
.getPrivateKey(new PrivateKeyInfo(algId, bcPrivateKey));
} catch (Exception e) {
e.printStackTrace();
}
Read a binary encoded (DER) PKCS8 private key
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
(...)
try {
Path path = Paths.get(THE_BINARY_ENCODED_FILE_PATH);
byte[] privKeyByteArray = Files.readAllBytes(path);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privKeyByteArray);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey= keyFactory.generatePrivate(keySpec);
} catch (Exception e) {
e.printStackTrace();
}
Read a PKC12 / PFX file to extract a key / certificate
import java.io.FileInputStream;
import java.security.Key;
import java.security.KeyStore;
(...)
try {
KeyStore p12 = KeyStore.getInstance("pkcs12");
// getPassword returns the password of the key / file. The password should not be hard coded.
p12.load(new FileInputStream("THE_PFX_FILE_PATH"),
getPassword().toCharArray());
// the key is ready to be used !
Key key = p12.getKey("YOUR_KEY_ALIAS", getPassword().toCharArray());
} catch (Exception e) {
e.printStackTrace();
}