Skip to content

Instantly share code, notes, and snippets.

@sargue
Created August 3, 2018 11:22
Show Gist options
  • 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;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.PKIXParameters;
import java.security.cert.TrustAnchor;
public class CheckCertificate {
public static void main(String[] args) throws Exception {
if (args.length < 1 || args.length > 3) {
System.err.println(
"Usage: java CheckCertificate certificate [keystore [keystorePass]]");
System.err.println();
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'");
System.exit(1);
}
Path cacertsPath;
if (args.length > 1) {
cacertsPath = Paths.get(args[1]);
} else {
cacertsPath = Paths.get(System.getProperty("java.home"),
"lib",
"security",
"cacerts");
}
if (!Files.isReadable(cacertsPath)) {
System.err.println("Can't read keystore: " + cacertsPath);
System.exit(-1);
}
Path certificatePath = Paths.get(args[0]);
if (!Files.isReadable(certificatePath)) {
System.err.println("Can't read certificate: " + certificatePath);
System.exit(-2);
}
Certificate certificate = CertificateFactory
.getInstance("X.509")
.generateCertificate(Files.newInputStream(certificatePath));
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()
.stream()
.map(TrustAnchor::getTrustedCert)
.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