Skip to content

Instantly share code, notes, and snippets.

Created August 3, 2018 11:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sargue/2c1f8fca3482bcd0de0ea4182f44cf9d to your computer and use it in GitHub Desktop.
Save sargue/2c1f8fca3482bcd0de0ea4182f44cf9d to your computer and use it in GitHub Desktop.
Simple java cmd line util to check if a keystore contains a given certificate
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CheckCertificate {
public static void main(String[] args) throws Exception {
if (args.length < 1 || args.length > 3) {
"Usage: java CheckCertificate certificate [keystore [keystorePass]]");
System.err.println(" certificate: file containing the .crt certificate");
System.err.println(" [keystore]: optional keystore location, " +
"defaults to cacerts of current VM");
System.err.println(" [keystorePass]: optional keystore password, " +
"defaults to 'changeit'");
Path cacertsPath;
if (args.length > 1) {
cacertsPath = Paths.get(args[1]);
} else {
cacertsPath = Paths.get(System.getProperty("java.home"),
if (!Files.isReadable(cacertsPath)) {
System.err.println("Can't read keystore: " + cacertsPath);
Path certificatePath = Paths.get(args[0]);
if (!Files.isReadable(certificatePath)) {
System.err.println("Can't read certificate: " + certificatePath);
Certificate certificate = CertificateFactory
String keystorePass = args.length == 3 ? args[2] : "changeit";
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(Files.newInputStream(cacertsPath), keystorePass.toCharArray());
PKIXParameters params = new PKIXParameters(keystore);
boolean found = params.getTrustAnchors()
.anyMatch(trustedCert -> trustedCert.equals(certificate));
if (found) {
System.out.println("The certificate is present on the keystore.");
} else {
System.out.println("Can't found the certificate on the keystore.");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment