Example usage for java.security.cert X509Certificate getNotAfter

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

Introduction

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

Prototype

public abstract Date getNotAfter();

Source Link

Document

Gets the notAfter date from the validity period of the certificate.

Usage

From source file:be.fedict.eid.applet.service.JSONServlet.java

private static JSONObject createCertJSONObject(X509Certificate certificate, SimpleDateFormat simpleDateFormat)
        throws CertificateEncodingException, IOException {
    JSONObject certJSONObject = new JSONObject();
    certJSONObject.put("subject", certificate.getSubjectX500Principal().toString());
    certJSONObject.put("issuer", certificate.getIssuerX500Principal().toString());
    certJSONObject.put("serialNumber", certificate.getSerialNumber().toString());
    certJSONObject.put("notBefore", certificate.getNotBefore().toString());
    certJSONObject.put("notAfter", certificate.getNotAfter().toString());
    certJSONObject.put("signatureAlgo", certificate.getSigAlgName());
    certJSONObject.put("thumbprint", DigestUtils.shaHex(certificate.getEncoded()));
    certJSONObject.put("details", certificate.toString());
    certJSONObject.put("pem", toPem(certificate));

    return certJSONObject;
}

From source file:nl.nn.adapterframework.http.AuthSSLProtocolSocketFactoryBase.java

protected static KeyStore createKeyStore(final URL url, final String password, String keyStoreType,
        String prefix) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    if (url == null) {
        throw new IllegalArgumentException("Keystore url for " + prefix + " may not be null");
    }//from w  w w  .j ava2s.c o  m
    log.info("Initializing keystore for " + prefix + " from " + url.toString());
    KeyStore keystore = KeyStore.getInstance(keyStoreType);
    keystore.load(url.openStream(), password != null ? password.toCharArray() : null);
    if (log.isInfoEnabled()) {
        Enumeration aliases = keystore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = (String) aliases.nextElement();
            log.info(prefix + " '" + alias + "':");
            Certificate trustedcert = keystore.getCertificate(alias);
            if (trustedcert != null && trustedcert instanceof X509Certificate) {
                X509Certificate cert = (X509Certificate) trustedcert;
                log.info("  Subject DN: " + cert.getSubjectDN());
                log.info("  Signature Algorithm: " + cert.getSigAlgName());
                log.info("  Valid from: " + cert.getNotBefore());
                log.info("  Valid until: " + cert.getNotAfter());
                log.info("  Issuer: " + cert.getIssuerDN());
            }
        }
    }
    return keystore;
}

From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator.java

public static void extractCertificateDetails(byte[] certificateBytes, CertificateResponse certificateResponse)
        throws CertificateManagementDAOException {
    try {//from w w w.  j  a  v  a  2  s. c o m
        if (certificateBytes != null) {
            java.security.cert.Certificate x509Certificate = (java.security.cert.Certificate) Serializer
                    .deserialize(certificateBytes);
            if (x509Certificate instanceof X509Certificate) {
                X509Certificate certificate = (X509Certificate) x509Certificate;
                certificateResponse.setNotAfter(certificate.getNotAfter().getTime());
                certificateResponse.setNotBefore(certificate.getNotBefore().getTime());
                certificateResponse.setCertificateserial(certificate.getSerialNumber());
                certificateResponse.setIssuer(certificate.getIssuerDN().getName());
                certificateResponse.setSubject(certificate.getSubjectDN().getName());
                certificateResponse.setCertificateVersion(certificate.getVersion());
            }
        }
    } catch (ClassNotFoundException | IOException e) {
        String errorMsg = "Error while during deserialization of the certificate.";
        throw new CertificateManagementDAOException(errorMsg, e);
    }

}

From source file:wptools.cmds.DumpCerts.java

private static void dumpCert(X509Certificate cert) {
    System.out.println("Serial No.: " + formatFing(cert.getSerialNumber().toByteArray()));
    try {//  w ww. java 2s . c  om
        for (String ftype : FTYPES) {
            MessageDigest md = MessageDigest.getInstance(ftype);
            md.reset();
            System.out.format("%s: %s%n", ftype, formatFing(md.digest(cert.getEncoded())));
        }
    } catch (NoSuchAlgorithmException | CertificateException e) {
        Misc.die(e.getMessage());
    }
    System.out.println("Issued To: " + cert.getSubjectX500Principal());
    System.out.println("Issued By: " + cert.getIssuerX500Principal());
    System.out.format("Valid: from %tFT%<tT%<tz to %tFT%<tT%<tz%n%n", cert.getNotBefore(), cert.getNotAfter());
}

From source file:com.dbay.apns4j.tools.ApnsTools.java

public final static SocketFactory createSocketFactory(InputStream keyStore, String password,
        String keystoreType, String algorithm, String protocol)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
        UnrecoverableKeyException, KeyManagementException, CertificateExpiredException {

    char[] pwdChars = password.toCharArray();
    KeyStore ks = KeyStore.getInstance(keystoreType);
    ks.load(keyStore, pwdChars);/*w  w  w .ja  v a  2 s.  c  o  m*/

    // ??
    Enumeration<String> enums = ks.aliases();
    String alias = "";
    if (enums.hasMoreElements()) {
        alias = enums.nextElement();
    }
    if (StringUtils.isNotEmpty(alias)) {
        X509Certificate certificate = (X509Certificate) ks.getCertificate(alias);
        if (null != certificate) {
            String type = certificate.getType();
            int ver = certificate.getVersion();
            String name = certificate.getSubjectDN().getName();
            String serialNumber = certificate.getSerialNumber().toString(16);
            String issuerDN = certificate.getIssuerDN().getName();
            String sigAlgName = certificate.getSigAlgName();
            String publicAlgorithm = certificate.getPublicKey().getAlgorithm();
            Date before = certificate.getNotBefore();
            Date after = certificate.getNotAfter();

            String beforeStr = DateFormatUtils.format(before, "yyyy-MM-dd HH:mm:ss");
            String afterStr = DateFormatUtils.format(after, "yyyy-MM-dd HH:mm:ss");

            // ??
            long expire = DateUtil.getNumberOfDaysBetween(new Date(), after);
            if (expire <= 0) {
                if (LOG.isErrorEnabled()) {
                    LOG.error(
                            "?[{}], [{}], ?[{}], ??[{}], ?[{}], ??[{}], [{}], [{}][{}], ?[{}]",
                            name, type, ver, serialNumber, issuerDN, sigAlgName, publicAlgorithm, beforeStr,
                            afterStr, Math.abs(expire));
                }

                throw new CertificateExpiredException("??[" + Math.abs(expire) + "]");
            }

            if (LOG.isInfoEnabled()) {
                LOG.info(
                        "?[{}], [{}], ?[{}], ??[{}], ?[{}], ??[{}], [{}], [{}][{}], ?[{}]?",
                        name, type, ver, serialNumber, issuerDN, sigAlgName, publicAlgorithm, beforeStr,
                        afterStr, expire);
            }
        }
    }

    KeyManagerFactory kf = KeyManagerFactory.getInstance(algorithm);
    kf.init(ks, pwdChars);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
    tmf.init((KeyStore) null);
    SSLContext context = SSLContext.getInstance(protocol);
    context.init(kf.getKeyManagers(), tmf.getTrustManagers(), null);

    return context.getSocketFactory();
}

From source file:com.xwiki.authentication.sts.STSTokenValidator.java

/**
  * validateToken(SignableSAMLObject samlToken)
  * Validates Token from SAMLlObject - returns boolen
  * Validates Token - exitracting sertificate from samlToken.
  * And validates it. Returning true or false according on validation results.
  * @param samlToken SignableSAMLObject// www.j  av a 2 s  .c  o  m
  * @return boolean valid => true, not valid => false
  */
private static boolean validateToken(SignableSAMLObject samlToken)
        throws SecurityException, ValidationException, ConfigurationException, UnmarshallingException,
        CertificateException, KeyException {

    // Validate XML structure
    samlToken.validate(true);

    Signature signature = samlToken.getSignature();
    X509Certificate certificate = certFromToken(samlToken);

    // Certificate data
    log.debug("certificate issuerDN: " + certificate.getIssuerDN());
    log.debug("certificate issuerUniqueID: " + certificate.getIssuerUniqueID());
    log.debug("certificate issuerX500Principal: " + certificate.getIssuerX500Principal());
    log.debug("certificate notBefore: " + certificate.getNotBefore());
    log.debug("certificate notAfter: " + certificate.getNotAfter());
    log.debug("certificate serialNumber: " + certificate.getSerialNumber());
    log.debug("certificate sigAlgName: " + certificate.getSigAlgName());
    log.debug("certificate sigAlgOID: " + certificate.getSigAlgOID());
    log.debug("certificate signature: " + new String(certificate.getSignature()));
    log.debug("certificate issuerX500Principal: " + certificate.getIssuerX500Principal().toString());
    log.debug("certificate publicKey: " + certificate.getPublicKey());
    log.debug("certificate subjectDN: " + certificate.getSubjectDN());
    log.debug("certificate sigAlgOID: " + certificate.getSigAlgOID());
    log.debug("certificate version: " + certificate.getVersion());

    BasicX509Credential cred = new BasicX509Credential();
    cred.setEntityCertificate(certificate);

    // Credential data
    cred.setEntityId(entityId);
    log.debug("cred entityId: " + cred.getEntityId());
    log.debug("cred usageType: " + cred.getUsageType());
    log.debug("cred credentalContextSet: " + cred.getCredentalContextSet());
    log.debug("cred hashCode: " + cred.hashCode());
    log.debug("cred privateKey: " + cred.getPrivateKey());
    log.debug("cred publicKey: " + cred.getPublicKey());
    log.debug("cred secretKey: " + cred.getSecretKey());
    log.debug("cred entityCertificateChain: " + cred.getEntityCertificateChain());

    ArrayList<Credential> trustedCredentials = new ArrayList<Credential>();
    trustedCredentials.add(cred);

    CollectionCredentialResolver credResolver = new CollectionCredentialResolver(trustedCredentials);
    KeyInfoCredentialResolver kiResolver = SecurityTestHelper.buildBasicInlineKeyInfoResolver();
    ExplicitKeySignatureTrustEngine engine = new ExplicitKeySignatureTrustEngine(credResolver, kiResolver);

    CriteriaSet criteriaSet = new CriteriaSet();
    criteriaSet.add(new EntityIDCriteria(entityId));

    Base64 decoder = new Base64();
    // In trace mode write certificate in the file
    if (log.isTraceEnabled()) {
        String certEncoded = new String(decoder.encode(certificate.getEncoded()));
        try {
            FileUtils.writeStringToFile(new File("/tmp/Certificate.cer"),
                    "-----BEGIN CERTIFICATE-----\n" + certEncoded + "\n-----END CERTIFICATE-----");
            log.trace("Certificate file was saved in: /tmp/Certificate.cer");
        } catch (IOException e1) {
            log.error(e1);
        }
    }
    return engine.validate(signature, criteriaSet);
}

From source file:org.digidoc4j.impl.bdoc.xades.validation.TimemarkSignatureValidator.java

private void addCertificateExpirationError() {
    Date signingTime = signature.getTrustedSigningTime();
    if (signingTime == null) {
        return;/*  w  w w .j  a va2s. co  m*/
    }
    X509Certificate signerCert = signature.getSigningCertificate().getX509Certificate();
    Date notBefore = signerCert.getNotBefore();
    Date notAfter = signerCert.getNotAfter();
    boolean isCertValid = signingTime.compareTo(notBefore) >= 0 && signingTime.compareTo(notAfter) <= 0;
    if (!isCertValid) {
        logger.error("Signature has been created with expired certificate");
        addValidationError(new SignedWithExpiredCertificateException());
    }
}

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   w  ww  .ja v 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:net.solarnetwork.node.setup.web.NodeCertificatesController.java

/**
 * View the main certs page./*from   w  ww. j a v  a  2 s.c  o m*/
 * 
 * @param model
 *        the view model
 * @return
 */
@RequestMapping
public String home(Model model) {
    X509Certificate nodeCert = pkiService.getNodeCertificate();
    final Date now = new Date();
    final boolean expired = (nodeCert != null && now.after(nodeCert.getNotAfter()));
    final boolean valid = (nodeCert != null && (!nodeCert.getIssuerDN().equals(nodeCert.getSubjectDN())
            && !now.before(nodeCert.getNotBefore()) && !expired));
    model.addAttribute("nodeCert", nodeCert);
    model.addAttribute("nodeCertExpired", expired);
    model.addAttribute("nodeCertValid", valid);
    return "certs/home";
}

From source file:org.openremote.controller.rest.FindCertificateByID.java

protected String getChain(String username) throws Exception {
    username = URLDecoder.decode(username, "UTF-8");
    String rootCAPath = configurationService.getItem("ca_path");
    String keystore = rootCAPath + "/server.jks";

    StringBuffer sb = new StringBuffer();
    sb.append(Constants.STATUS_XML_HEADER);

    sb.append("\n<chain>\n<server>\n");

    try {// w ww. ja va2  s.  c o  m
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(new FileInputStream(keystore), "password".toCharArray());
        Certificate certificate = ks.getCertificate(CA_ALIAS);
        sb.append(new String(Base64.encodeBase64(certificate.getEncoded())));
    } catch (KeyStoreException e) {
        logger.error(e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        logger.error(e.getMessage());
    } catch (CertificateException e) {
        logger.error(e.getMessage());
    }

    sb.append("</server>\n<client>\n");

    try {
        Certificate certificate = clientService.getClientCertificate(username);
        if (certificate != null) {
            // Check client certificate
            //if(clientService.(dn, datum)
            X509Certificate x509cert = (X509Certificate) certificate;
            Principal dname = x509cert.getSubjectDN();
            Date notAfterDate = x509cert.getNotAfter();

            if (clientService.isClientValid(dname.toString())) {
                if (clientService.isClientDateValid(notAfterDate)) {
                    sb.append(new String(Base64.encodeBase64(certificate.getEncoded())));
                } else {
                    throw new Exception(ERROR_DATE_EXPIRED);
                }
            } else {
                throw new Exception(ERROR_INVALID_DN);
            }
        } else {
            logger.error("Client certificate is not found/null.");
        }
    } catch (CertificateEncodingException e) {
        logger.error(e.getMessage());
    }

    sb.append("</client>\n</chain>");
    sb.append(Constants.STATUS_XML_TAIL);

    return sb.toString();
}