Example usage for java.security.cert X509Certificate checkValidity

List of usage examples for java.security.cert X509Certificate checkValidity

Introduction

In this page you can find the example usage for java.security.cert X509Certificate checkValidity.

Prototype

public abstract void checkValidity() throws CertificateExpiredException, CertificateNotYetValidException;

Source Link

Document

Checks that the certificate is currently valid.

Usage

From source file:com.vmware.identity.idm.ValidateUtil.java

/**
 * Checks validity of the given certificate.
 * @throws IllegalArgumentException//from   ww w.  j a  v  a 2 s . co  m
 *            on validation failure
 */
public static void validateCertificate(X509Certificate cert) {
    try {
        cert.checkValidity();
    } catch (Exception e) {
        logAndThrow(String.format("Certificate is not valid: %s", e.getMessage()));
    }
}

From source file:org.wso2.carbon.identity.relyingparty.saml.IssuerCertificateUtil.java

private static boolean isInKeyStore(X509Certificate signedCert, KeyStore keyStore) throws Exception {

    if (signedCert == null || keyStore == null) {
        throw new RelyingPartyException("invalidInputParams");
    }/* w w w  . j av a 2s.c  om*/

    // validity period
    signedCert.checkValidity();

    try {
        if (keyStore.getCertificateAlias(signedCert) != null) {
            return true;
        } else {
            return false;
        }
    } catch (KeyStoreException e) {
        log.error("The keystore has not been initialized", e);
        throw new RelyingPartyException("errorLoadingTrustedKeystore", e);
    }
}

From source file:org.wso2.carbon.identity.relyingparty.saml.IssuerCertificateUtil.java

/**
 * This method checks whether the certificate is present in the certificate store
 *//* w w  w.ja  v  a 2s .c o m*/
public static boolean checkSystemStore(X509Certificate signedCert, KeyStore systemStore) throws Exception {
    if (signedCert == null || systemStore == null) {
        throw new RelyingPartyException("invalidInputParams");
    }

    // validity period
    signedCert.checkValidity();

    try {
        return systemStore.containsAlias(signedCert.getIssuerDN().getName());
    } catch (KeyStoreException e) {
        log.error("The keystore has not been initialized", e);
        throw new RelyingPartyException("errorLoadingTrustedKeystore", e);
    }
}

From source file:org.ejbca.core.protocol.ocsp.OCSPUtil.java

/**
 * Checks if a certificate is valid//from  w w  w  .  j  ava2  s .  c  om
 * Does also print a WARN if the certificate is about to expire.
 * @param signerCert the certificate to be tested
 * @return true if the certificate is valid
 */
public static boolean isCertificateValid(X509Certificate signerCert) {
    try {
        signerCert.checkValidity();
    } catch (CertificateExpiredException e) {
        m_log.error(intres.getLocalizedMessage("ocsp.errorcerthasexpired", signerCert.getSerialNumber(),
                signerCert.getIssuerDN()));
        return false;
    } catch (CertificateNotYetValidException e) {
        m_log.error(intres.getLocalizedMessage("ocsp.errornotyetvalid", signerCert.getSerialNumber(),
                signerCert.getIssuerDN()));
        return false;
    }
    final long warnBeforeExpirationTime = OcspConfiguration.getWarningBeforeExpirationTime();
    if (warnBeforeExpirationTime < 1) {
        return true;
    }
    final Date warnDate = new Date(new Date().getTime() + warnBeforeExpirationTime);
    try {
        signerCert.checkValidity(warnDate);
    } catch (CertificateExpiredException e) {
        m_log.warn(intres.getLocalizedMessage("ocsp.warncertwillexpire", signerCert.getSerialNumber(),
                signerCert.getIssuerDN(), signerCert.getNotAfter()));
    } catch (CertificateNotYetValidException e) {
        throw new Error("This should never happen.", e);
    }
    if (!m_log.isDebugEnabled()) {
        return true;
    }
    m_log.debug("Time for \"certificate will soon expire\" not yet reached. You will be warned after: "
            + new Date(signerCert.getNotAfter().getTime() - warnBeforeExpirationTime));
    return true;
}

From source file:com.vangent.hieos.services.sts.util.STSUtil.java

/**
 *
 * @param cert/*from  w w w.  j a  va  2s  .  c  om*/
 * @param trustStore
 * @throws STSException
 */
public static void validateCertificate(X509Certificate cert, KeyStore trustStore) throws STSException {
    try {
        // To check the validity of the dates
        cert.checkValidity();
    } catch (CertificateExpiredException ex) {
        throw new STSException("Certificate expired: " + ex.getMessage());
    } catch (CertificateNotYetValidException ex) {
        throw new STSException("Certificate not yet valid: " + ex.getMessage());
    }

    // Check the chain.
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        List<X509Certificate> mylist = new ArrayList<X509Certificate>();
        mylist.add(cert);
        CertPath cp = cf.generateCertPath(mylist);
        PKIXParameters params = new PKIXParameters(trustStore);
        // FIXME: Add revocation checking.
        params.setRevocationEnabled(false);
        CertPathValidator cpv = CertPathValidator.getInstance(CertPathValidator.getDefaultType());
        PKIXCertPathValidatorResult pkixCertPathValidatorResult = (PKIXCertPathValidatorResult) cpv.validate(cp,
                params);
        if (logger.isDebugEnabled()) {
            logger.debug(pkixCertPathValidatorResult);
        }
    } catch (Exception ex) {
        throw new STSException("Exception while validating Certificate: " + ex.getMessage());
    }
}

From source file:mitm.common.security.certificate.X509CertificateInspector.java

/**
 * Returns true if the current date falls outside the validity date of the certificate.
 *///  w w  w . j  ava2 s.c  o m
public static boolean isExpired(X509Certificate certificate) {
    boolean expired = true;

    try {
        certificate.checkValidity();

        expired = false;
    } catch (CertificateExpiredException e) {
        /* ignored */
    } catch (CertificateNotYetValidException e) {
        /* ignored */
    }

    return expired;
}

From source file:org.roda.common.certification.ODFSignatureUtils.java

private static void verifyCertificates(Path input, Node signatureNode)
        throws MarshalException, XMLSignatureException, NoSuchAlgorithmException, CertificateException,
        FileNotFoundException, IOException, KeyStoreException {

    XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM");
    DOMValidateContext domValidateContext = new DOMValidateContext(new KeyInfoKeySelector(), signatureNode);
    XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
    xmlSignature.getSignatureValue().validate(domValidateContext);
    // xmlSignature.validate(domValidateContext);

    KeyInfo keyInfo = xmlSignature.getKeyInfo();
    Iterator<?> it = keyInfo.getContent().iterator();
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    List<CRL> crls = new ArrayList<CRL>();

    while (it.hasNext()) {
        XMLStructure content = (XMLStructure) it.next();
        if (content instanceof X509Data) {
            X509Data certdata = (X509Data) content;
            Object[] entries = certdata.getContent().toArray();
            for (int i = 0; i < entries.length; i++) {
                if (entries[i] instanceof X509CRL) {
                    X509CRL crl = (X509CRL) entries[i];
                    crls.add(crl);//from   w  w  w  . j av a2 s  . c  om
                }
                if (entries[i] instanceof X509Certificate) {
                    X509Certificate cert = (X509Certificate) entries[i];
                    cert.checkValidity();
                    certs.add(cert);
                }
            }
        }
    }

    for (CRL c : crls) {
        for (X509Certificate cert : certs) {
            if (c.isRevoked(cert))
                throw new CertificateRevokedException(null, null, null, null);
        }
    }
}

From source file:com.vmware.identity.idm.ValidateUtil.java

/**
 * Validates that given certificate is <code>valid</code>.
 * clockTolerance - value of current clock tolerance in milliseconds
 * @throws IllegalArgumentException/*from  ww  w.j  av  a  2s. c  o m*/
 *            on validation failure
 */
public static void validateSolutionDetail(SolutionDetail fieldValue, String fieldName, long clockTolerance) {

    X509Certificate cert = fieldValue.getCertificate();
    ValidateUtil.validateNotNull(cert, "Solution user certificate");
    try {
        cert.checkValidity();
    } catch (CertificateException ex) {
        if (ex instanceof CertificateNotYetValidException) {
            // Check to see whether certificate is within clock tolerance
            // if so do not throw, cert passes the validation
            if (cert.getNotBefore().getTime() <= System.currentTimeMillis() + clockTolerance) {
                return;
            }
        }

        if (ex instanceof CertificateExpiredException) {
            // Check to see whether certificate is within clock tolerance
            // if so do not throw, cert passes the validation
            if (cert.getNotAfter().getTime() >= System.currentTimeMillis() - clockTolerance) {
                return;
            }
        }

        logAndThrow(String.format("'%s' certificate is invalid - " + "certificateException %s", fieldName,
                ex.toString()));
    }
}

From source file:org.roda.core.plugins.plugins.characterization.ODFSignatureUtils.java

private static void verifyCertificates(Node signatureNode) throws MarshalException, XMLSignatureException,
        NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException {

    XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM");
    DOMValidateContext domValidateContext = new DOMValidateContext(new KeyInfoKeySelector(), signatureNode);
    XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
    xmlSignature.getSignatureValue().validate(domValidateContext);
    // xmlSignature.validate(domValidateContext);

    KeyInfo keyInfo = xmlSignature.getKeyInfo();
    Iterator<?> it = keyInfo.getContent().iterator();
    List<X509Certificate> certs = new ArrayList<>();
    List<CRL> crls = new ArrayList<>();

    while (it.hasNext()) {
        XMLStructure content = (XMLStructure) it.next();
        if (content instanceof X509Data) {
            X509Data certdata = (X509Data) content;
            Object[] entries = certdata.getContent().toArray();
            for (int i = 0; i < entries.length; i++) {
                if (entries[i] instanceof X509CRL) {
                    X509CRL crl = (X509CRL) entries[i];
                    crls.add(crl);//  w w w.ja  va 2s . c o  m
                }

                if (entries[i] instanceof X509Certificate) {
                    X509Certificate cert = (X509Certificate) entries[i];
                    cert.checkValidity();
                    certs.add(cert);
                }
            }
        }
    }

    for (CRL c : crls) {
        for (X509Certificate cert : certs) {
            if (c.isRevoked(cert))
                throw new CertificateRevokedException(null, null, null, null);
        }
    }
}

From source file:com.amazon.speech.speechlet.authentication.SpeechletRequestSignatureVerifier.java

/**
 * Verifies the certificate authenticity using the configured TrustStore and the signature of
 * the speechlet request.//from w  w w .  java 2  s  . c  om
 *
 * @param serializedSpeechletRequest
 *            speechlet request serialized as a string of JSON
 * @param baseEncoded64Signature
 *            the signature for provided in the request header
 * @param signingCertificateChainUrl
 *            the certificate chain URL provided in the request header
 */
public static void checkRequestSignature(final byte[] serializedSpeechletRequest,
        final String baseEncoded64Signature, final String signingCertificateChainUrl) {
    if ((baseEncoded64Signature == null) || (signingCertificateChainUrl == null)) {
        throw new SecurityException("Missing signature/certificate for the provided speechlet request");
    }

    try {
        X509Certificate signingCertificate;
        if (CERTIFICATE_CACHE.containsKey(signingCertificateChainUrl)) {
            signingCertificate = CERTIFICATE_CACHE.get(signingCertificateChainUrl);
            /*
             * check the before/after dates on the certificate are still valid for the present
             * time
             */
            signingCertificate.checkValidity();
        } else {
            signingCertificate = retrieveAndVerifyCertificateChain(signingCertificateChainUrl);

            // if certificate is valid, then add it to the cache
            CERTIFICATE_CACHE.put(signingCertificateChainUrl, signingCertificate);
        }

        // verify that the request was signed by the provided certificate
        Signature signature = Signature.getInstance(Sdk.SIGNATURE_ALGORITHM);
        signature.initVerify(signingCertificate.getPublicKey());
        signature.update(serializedSpeechletRequest);
        if (!signature.verify(Base64.decodeBase64(baseEncoded64Signature.getBytes(Sdk.CHARACTER_ENCODING)))) {
            throw new SecurityException(
                    "Failed to verify the signature/certificate for the provided speechlet request");
        }
    } catch (CertificateException | SignatureException | NoSuchAlgorithmException | InvalidKeyException
            | IOException ex) {
        throw new SecurityException(
                "Failed to verify the signature/certificate for the provided speechlet request", ex);
    }
}