Check validity of SSL key certificates in client
@@ -40,6 +40,9 @@ import java.net.InetSocketAddress;
import java.net.Proxy;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateExpiredException;
+import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.List;
@@ -50,6 +53,7 @@ import static com.google.common.net.HttpHeaders.AUTHORIZATION;
import static com.google.common.net.HttpHeaders.USER_AGENT;
import static java.net.Proxy.Type.HTTP;
import static java.net.Proxy.Type.SOCKS;
+import static java.util.Collections.list;
import static java.util.Objects.requireNonNull;
public final class OkHttpUtil
@@ -153,6 +157,7 @@ public final class OkHttpUtil
keyStore.load(in, keyManagerPassword);
}
}
+ validateCertificates(keyStore);
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, keyManagerPassword);
keyManagers = keyManagerFactory.getKeyManagers();
@@ -186,6 +191,30 @@ public final class OkHttpUtil
}
}
+ private static void validateCertificates(KeyStore keyStore)
+ throws GeneralSecurityException
+ {
+ for (String alias : list(keyStore.aliases())) {
+ if (!keyStore.isKeyEntry(alias)) {
+ continue;
+ }
+ Certificate certificate = keyStore.getCertificate(alias);
+ if (!(certificate instanceof X509Certificate)) {
+ continue;
+ }
+
+ try {
+ ((X509Certificate) certificate).checkValidity();
+ }
+ catch (CertificateExpiredException e) {
+ throw new CertificateExpiredException("KeyStore certificate is expired: " + e.getMessage());
+ }
+ catch (CertificateNotYetValidException e) {
+ throw new CertificateNotYetValidException("KeyStore certificate is not yet valid: " + e.getMessage());
+ }
+ }
+ }
+
private static KeyStore loadTrustStore(File trustStorePath, Optional<String> trustStorePassword)
throws IOException, GeneralSecurityException
{
