Java examples for Security:Certificate
verify Certificate
//package com.java2s; import java.io.FileInputStream; import java.security.KeyStore; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Date; public class Main { public static final String KEY_STORE = "JKS"; public static final String X509 = "X.509"; public static boolean verifyCertificate(Certificate certificate) { return verifyCertificate(new Date(), certificate); }// ww w . jav a 2 s.c o m public static boolean verifyCertificate(Date date, Certificate certificate) { boolean isValid = true; try { X509Certificate x509Certificate = (X509Certificate) certificate; x509Certificate.checkValidity(date); } catch (Exception e) { isValid = false; } return isValid; } public static boolean verifyCertificate(Date date, String certificatePath) { Certificate certificate; try { certificate = getCertificate(certificatePath); return verifyCertificate(certificate); } catch (Exception e) { e.printStackTrace(); return false; } } public static boolean verifyCertificate(Date date, String keyStorePath, String alias, String password) { Certificate certificate; try { certificate = getCertificate(keyStorePath, alias, password); return verifyCertificate(certificate); } catch (Exception e) { e.printStackTrace(); return false; } } public static boolean verifyCertificate(String keyStorePath, String alias, String password) { return verifyCertificate(new Date(), keyStorePath, alias, password); } public static boolean verifyCertificate(String certificatePath) { return verifyCertificate(new Date(), certificatePath); } private static Certificate getCertificate(String certificatePath) throws Exception { CertificateFactory certificateFactory = CertificateFactory .getInstance(X509); FileInputStream in = new FileInputStream(certificatePath); Certificate certificate = certificateFactory .generateCertificate(in); in.close(); return certificate; } private static Certificate getCertificate(String keyStorePath, String alias, String password) throws Exception { KeyStore keyStore = getKeyStore(keyStorePath, password); Certificate certificate = keyStore.getCertificate(alias); return certificate; } private static KeyStore getKeyStore(String keyStorePath, String password) throws Exception { FileInputStream in = new FileInputStream(keyStorePath); KeyStore keyStore = KeyStore.getInstance(KEY_STORE); keyStore.load(in, password.toCharArray()); in.close(); return keyStore; } }