Java Requires Chilkat v11.0.0+
Chilkat2 Java
Iterate Keys and Certs in PEM
See more PEM Examples
Demonstrates how to access each of the private keys and certs contained within a PEM.Chilkat Java Downloads
import com.chilkatsoft.chilkat2.Cert;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Pem;
import com.chilkatsoft.chilkat2.PrivateKey;
public class ChilkatExample {
public static void main(String[] args) {
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
Pem pem = new Pem();
// Load the PEM from a file.
// If the PEM is encrypted, provide a password. Otherwise pass an empty string for the password.
String password = "myPassword";
try {
pem.loadPemFile("../myPemFiles/myPem.pem", password);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// Note: If the app already has the PEM pre-loaded in a string variable, then load it
// by calling LoadPem instead.
String pemContent = "... the PEM contents ...";
pem.loadPem(pemContent, password);
// Check for success as before..
// Iterate over the private keys.
int numPrivateKeys = pem.getNumPrivateKeys();
int i = 0;
PrivateKey privKey = new PrivateKey();
while (i < numPrivateKeys) {
pem.privateKeyAt(i, privKey);
System.out.println("Private Key " + i + " is " + privKey.getBitLength() + " in length");
i = i + 1;
}
// Iterate over the certificates.
Cert cert = new Cert();
int numCerts = pem.getNumCerts();
i = 0;
while (i < numCerts) {
pem.certAt(i, cert);
System.out.println("Certificate " + i + " : " + cert.getSubjectDN());
i = i + 1;
}
}
}