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:com.otterca.persistence.dao.X509CertificateDaoDatastore.java

/**
 * @see com.otterca.persistence.dao.X509CertificateDao#put(java.security.cert
 *      .X509Certificate)/* ww w .j a va 2s. com*/
 */
public void put(X509Certificate cert) throws IOException, CertificateEncodingException {

    // TODO: we want cert's issuer to be its parent. For now certs don't
    // have parents.
    Key key = generateKey(cert);
    Entity e = new Entity(key);

    // also set parent...

    e.setProperty(CERTIFICATE, new Blob(cert.getEncoded()));
    // up to 20 octets - 40 characters
    e.setProperty(SERIAL_NUMBER, cert.getSerialNumber().toString(16));
    // up to 500 unicode characters
    e.setProperty(SUBJECT_DN, cert.getSubjectDN().getName());
    // up to 500 unicode characters
    e.setProperty(ISSUER_DN, cert.getIssuerDN().getName());
    e.setProperty(NOT_BEFORE, cert.getNotBefore());
    e.setProperty(NOT_AFTER, cert.getNotAfter());

    // RFC search criteria
    e.setProperty(COMMON_NAME, x509CertUtil.getName(cert));
    e.setProperty(FINGERPRINT, x509CertUtil.getFingerprint(cert));
    e.setProperty(CERT_HASH, x509CertUtil.getCertificateHash(cert));
    e.setProperty(ISSUER_HASH, x509CertUtil.getIHash(cert));
    e.setProperty(SUBJECT_HASH, x509CertUtil.getSHash(cert));
    // e.setProperty(AKID_HASH, x509CertUtil.getAkidHash(cert));
    e.setProperty(SKID_HASH, x509CertUtil.getSkidHash(cert));
    // e.setProperty(IANDS_HASH, x509CertUtil.getIandSHash(cert));

    // e.setProperty(EMAIL) ?...

    e.setUnindexedProperty(TRUSTED, false);
    e.setUnindexedProperty(STATUS, UNKNOWN);

    datastore.put(e);
}

From source file:be.fedict.eid.tsl.tool.TslInternalFrame.java

@Override
public void valueChanged(TreeSelectionEvent event) {
    DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
    if (treeNode.isLeaf()) {
        TrustService trustService = (TrustService) treeNode.getUserObject();
        this.serviceName.setText(trustService.getName());
        this.serviceType.setText(trustService.getType()
                .substring(trustService.getType().indexOf("Svctype/") + "Svctype/".length()));
        this.serviceStatus.setText(trustService.getStatus()
                .substring(trustService.getStatus().indexOf("Svcstatus/") + "Svcstatus/".length()));
        X509Certificate certificate = trustService.getServiceDigitalIdentity();
        byte[] encodedCertificate;
        try {//  www. j a v  a2 s  .c om
            encodedCertificate = certificate.getEncoded();
        } catch (CertificateEncodingException e) {
            throw new RuntimeException("cert: " + e.getMessage(), e);
        }
        String sha1Thumbprint = DigestUtils.shaHex(encodedCertificate);
        this.serviceSha1Thumbprint.setText(sha1Thumbprint);

        String sha256Thumbprint = DigestUtils.sha256Hex(encodedCertificate);
        this.serviceSha256Thumbprint.setText(sha256Thumbprint);

        this.validityBegin.setText(certificate.getNotBefore().toString());
        this.validityEnd.setText(certificate.getNotAfter().toString());
    } else {
        this.serviceName.setText("");
        this.serviceType.setText("");
        this.serviceStatus.setText("");
        this.serviceSha1Thumbprint.setText("");
        this.serviceSha256Thumbprint.setText("");
        this.validityBegin.setText("");
        this.validityEnd.setText("");
    }
}

From source file:com.fine47.http.SecureSocketFactory.java

private SecureSocketFactory(String factoryId, KeyStore store, String alias) throws CertificateException,
        NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    super(store);

    // Loading the CA certificate from store.
    Certificate rootca = store.getCertificate(alias);

    // Turn it to X509 format.
    InputStream is = new ByteArrayInputStream(rootca.getEncoded());
    X509Certificate x509ca = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(is);
    ActivityHttpClient.silentCloseInputStream(is);

    if (null == x509ca) {
        throw new CertificateException("Found expired SSL certificate in this store: " + factoryId);
    }/*from  ww w  . j  a v a 2 s  .c  o m*/

    // Check the CA's validity.
    x509ca.checkValidity();

    // Accepted CA is only the one installed in the store.
    acceptedIssuers = new X509Certificate[] { x509ca };

    // Get the public key.
    publicKey = rootca.getPublicKey();

    sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(null, new TrustManager[] { new X509TrustManager() {

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            Exception error = null;

            if (null == chain || 0 == chain.length) {
                error = new CertificateException("Certificate chain is invalid");
            } else if (null == authType || 0 == authType.length()) {
                error = new CertificateException("Authentication type is invalid");
            } else
                try {
                    for (X509Certificate cert : chain) {
                        if (ActivityHttpClient.isDebugging()) {
                            Log.d(ActivityHttpClient.LOG_TAG, "Server Certificate Details:");
                            Log.d(ActivityHttpClient.LOG_TAG, "---------------------------");
                            Log.d(ActivityHttpClient.LOG_TAG, "IssuerDN: " + cert.getIssuerDN().toString());
                            Log.d(ActivityHttpClient.LOG_TAG, "SubjectDN: " + cert.getSubjectDN().toString());
                            Log.d(ActivityHttpClient.LOG_TAG, "Serial Number: " + cert.getSerialNumber());
                            Log.d(ActivityHttpClient.LOG_TAG, "Version: " + cert.getVersion());
                            Log.d(ActivityHttpClient.LOG_TAG, "Not before: " + cert.getNotBefore().toString());
                            Log.d(ActivityHttpClient.LOG_TAG, "Not after: " + cert.getNotAfter().toString());
                            Log.d(ActivityHttpClient.LOG_TAG, "---------------------------");
                        }

                        // Make sure that it hasn't expired.
                        cert.checkValidity();

                        // Verify the certificate's chain.
                        cert.verify(publicKey);
                    }
                } catch (InvalidKeyException ex) {
                    error = ex;
                } catch (NoSuchAlgorithmException ex) {
                    error = ex;
                } catch (NoSuchProviderException ex) {
                    error = ex;
                } catch (SignatureException ex) {
                    error = ex;
                }
            if (null != error && ActivityHttpClient.isDebugging()) {
                Log.e(ActivityHttpClient.LOG_TAG, "Error while setting up a secure socket factory.", error);
                throw new CertificateException(error);
            }
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return acceptedIssuers;
        }
    } }, null);

    setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
}

From source file:org.gluu.oxtrust.action.ManageCertificateAction.java

private void loadCert(X509Certificate cert) {
    if (cert != null) {
        String issuerDN = cert.getIssuerX500Principal().getName();
        String[] values = issuerDN.split("(?<!\\\\),");
        for (String value : values) {
            String[] keyValue = value.split("=");
            issuer.put(keyValue[0], keyValue[1]);
        }/*from  ww w . ja v a  2  s.c  o m*/
        String subjectDN = cert.getSubjectX500Principal().getName();
        values = subjectDN.split("(?<!\\\\),");
        for (String value : values) {
            String[] keyValue = value.split("=");
            subject.put(keyValue[0], keyValue[1]);
        }
        subject.put("validUntil", StringHelper.toString(cert.getNotAfter()));
        subject.put("validAfter", StringHelper.toString(cert.getNotBefore()));
    }
}

From source file:org.syncany.plugins.webdav.WebdavTransferManager.java

private String formatCertificate(X509Certificate cert) {
    try {//w ww  . j  a v a2  s . c  o m
        CipherUtil.enableUnlimitedStrength(); // Dirty!

        String checksumMd5 = formatChecksum(createChecksum(cert.getEncoded(), "MD5"));
        String checksumSha1 = formatChecksum(createChecksum(cert.getEncoded(), "SHA1"));
        String checksumSha256 = formatChecksum(createChecksum(cert.getEncoded(), "SHA256"));

        StringBuilder sb = new StringBuilder();

        sb.append(String.format("Owner: %s\n", cert.getSubjectDN().getName()));
        sb.append(String.format("Issuer: %s\n", cert.getIssuerDN().getName()));
        sb.append(String.format("Serial number: %d\n", cert.getSerialNumber()));
        sb.append(String.format("Valid from %s until: %s\n", cert.getNotBefore().toString(),
                cert.getNotAfter().toString()));
        sb.append("Certificate fingerprints:\n");
        sb.append(String.format(" MD5:  %s\n", checksumMd5));
        sb.append(String.format(" SHA1: %s\n", checksumSha1));
        sb.append(String.format(" SHA256: %s", checksumSha256));

        return sb.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:nl.nn.adapterframework.webcontrol.action.ShowSecurityItems.java

private void addCertificateInfo(XmlBuilder certElem, final URL url, final String password, String keyStoreType,
        String prefix) {//from   ww w .j  ava  2 s. c o  m
    try {
        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();
                XmlBuilder infoElem = new XmlBuilder("info");
                infoElem.setCdataValue(prefix + " '" + alias + "':");
                certElem.addSubElement(infoElem);
                Certificate trustedcert = keystore.getCertificate(alias);
                if (trustedcert != null && trustedcert instanceof X509Certificate) {
                    X509Certificate cert = (X509Certificate) trustedcert;
                    infoElem = new XmlBuilder("info");
                    infoElem.setCdataValue("  Subject DN: " + cert.getSubjectDN());
                    certElem.addSubElement(infoElem);
                    infoElem = new XmlBuilder("info");
                    infoElem.setCdataValue("  Signature Algorithm: " + cert.getSigAlgName());
                    certElem.addSubElement(infoElem);
                    infoElem = new XmlBuilder("info");
                    infoElem.setCdataValue("  Valid from: " + cert.getNotBefore());
                    certElem.addSubElement(infoElem);
                    infoElem = new XmlBuilder("info");
                    infoElem.setCdataValue("  Valid until: " + cert.getNotAfter());
                    certElem.addSubElement(infoElem);
                    infoElem = new XmlBuilder("info");
                    infoElem.setCdataValue("  Issuer: " + cert.getIssuerDN());
                    certElem.addSubElement(infoElem);
                }
            }
        }
    } catch (Exception e) {
        XmlBuilder infoElem = new XmlBuilder("info");
        infoElem.setCdataValue("*** ERROR ***");
        certElem.addSubElement(infoElem);
    }
}

From source file:com.stargame.ad.util.http.ssl.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {//from   ww w. j a v  a2 s.com
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
            if (LogUtil.D) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        LogUtil.d(AuthSSLProtocolSocketFactory.class, "Certificate chain '" + alias + "':");
                        for (int c = 0; c < certs.length; c++) {
                            if (certs[c] instanceof X509Certificate) {
                                X509Certificate cert = (X509Certificate) certs[c];
                                LogUtil.d(AuthSSLProtocolSocketFactory.class, " Certificate " + (c + 1) + ":");
                                LogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Subject DN: " + cert.getSubjectDN());
                                LogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Signature Algorithm: " + cert.getSigAlgName());
                                LogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Valid from: " + cert.getNotBefore());
                                LogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Valid until: " + cert.getNotAfter());
                                LogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Issuer: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        if (this.truststoreUrl != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
            if (LogUtil.D) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    LogUtil.d(AuthSSLProtocolSocketFactory.class, "Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        LogUtil.d(AuthSSLProtocolSocketFactory.class, "  Subject DN: " + cert.getSubjectDN());
                        LogUtil.d(AuthSSLProtocolSocketFactory.class,
                                "  Signature Algorithm: " + cert.getSigAlgName());
                        LogUtil.d(AuthSSLProtocolSocketFactory.class, "  Valid from: " + cert.getNotBefore());
                        LogUtil.d(AuthSSLProtocolSocketFactory.class, "  Valid until: " + cert.getNotAfter());
                        LogUtil.d(AuthSSLProtocolSocketFactory.class, "  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        LogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage());
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        LogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage());
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        LogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage());
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        LogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage());
        throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:org.wso2.carbon.security.keystore.KeyStoreAdmin.java

private CertData fillCertData(X509Certificate cert, String alise, Format formatter)
        throws CertificateEncodingException {
    CertData certData = null;//w w w  . ja  va 2  s. co  m

    if (includeCert) {
        certData = new CertDataDetail();
    } else {
        certData = new CertData();
    }
    certData.setAlias(alise);
    certData.setSubjectDN(cert.getSubjectDN().getName());
    certData.setIssuerDN(cert.getIssuerDN().getName());
    certData.setSerialNumber(cert.getSerialNumber());
    certData.setVersion(cert.getVersion());
    certData.setNotAfter(formatter.format(cert.getNotAfter()));
    certData.setNotBefore(formatter.format(cert.getNotBefore()));
    certData.setPublicKey(Base64.encode(cert.getPublicKey().getEncoded()));

    if (includeCert) {
        ((CertDataDetail) certData).setCertificate(cert);
    }

    return certData;
}

From source file:org.alfresco.encryption.AlfrescoKeyStoreImpl.java

protected KeyMap cacheKeys(KeyStore ks, KeyInfoManager keyInfoManager)
        throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException {
    KeyMap keys = new KeyMap();

    // load and cache the keys
    for (Entry<String, KeyInformation> keyEntry : keyInfoManager.getKeyInfo().entrySet()) {
        String keyAlias = keyEntry.getKey();

        KeyInformation keyInfo = keyInfoManager.getKeyInformation(keyAlias);
        String passwordStr = keyInfo != null ? keyInfo.getPassword() : null;

        // Null is an acceptable value (means no key)
        Key key = null;//from   ww w.j ava2  s .c  o  m

        // Attempt to get the key
        key = ks.getKey(keyAlias, passwordStr == null ? null : passwordStr.toCharArray());
        if (key != null) {
            keys.setKey(keyAlias, key);
        }
        // Key loaded
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "Retrieved key from keystore: \n" + "   Location: " + getKeyStoreParameters().getLocation()
                            + "\n" + "   Provider: " + getKeyStoreParameters().getProvider() + "\n"
                            + "   Type:     " + getKeyStoreParameters().getType() + "\n" + "   Alias:    "
                            + keyAlias + "\n" + "   Password?: " + (passwordStr != null));

            Certificate[] certs = ks.getCertificateChain(keyAlias);
            if (certs != null) {
                logger.debug("Certificate chain '" + keyAlias + "':");
                for (int c = 0; c < certs.length; c++) {
                    if (certs[c] instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) certs[c];
                        logger.debug(" Certificate " + (c + 1) + ":");
                        logger.debug("  Subject DN: " + cert.getSubjectDN());
                        logger.debug("  Signature Algorithm: " + cert.getSigAlgName());
                        logger.debug("  Valid from: " + cert.getNotBefore());
                        logger.debug("  Valid until: " + cert.getNotAfter());
                        logger.debug("  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
        }
    }

    return keys;
}

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

/** Checks the signature on an OCSP request and checks that it is signed by an allowed CA.
 * Does not check for revocation of the signer certificate
 * /*from   ww w . jav  a  2s. co  m*/
 * @param clientRemoteAddr The ip address or hostname of the remote client that sent the request, can be null.
 * @param req The signed OCSPReq
 * @param cacerts a CertificateCache of Certificates, the authorized CA-certificates. The signer certificate must be issued by one of these.
 * @return X509Certificate which is the certificate that signed the OCSP request
 * @throws SignRequestSignatureException if signature verification fail, or if the signing certificate is not authorized
 * @throws SignRequestException if there is no signature on the OCSPReq
 * @throws OCSPException if the request can not be parsed to retrieve certificates
 * @throws NoSuchProviderException if the BC provider is not installed
 * @throws CertificateException if the certificate can not be parsed
 * @throws NoSuchAlgorithmException if the certificate contains an unsupported algorithm
 * @throws InvalidKeyException if the certificate, or CA key is invalid
 */
public static X509Certificate checkRequestSignature(String clientRemoteAddr, OCSPReq req,
        ICertificateCache cacerts) throws SignRequestException, OCSPException, NoSuchProviderException,
        CertificateException, NoSuchAlgorithmException, InvalidKeyException, SignRequestSignatureException {

    X509Certificate signercert = null;

    if (!req.isSigned()) {
        String infoMsg = intres.getLocalizedMessage("ocsp.errorunsignedreq", clientRemoteAddr);
        m_log.info(infoMsg);
        throw new SignRequestException(infoMsg);
    }
    // Get all certificates embedded in the request (probably a certificate chain)
    X509Certificate[] certs = req.getCerts("BC");
    // Set, as a try, the signer to be the first certificate, so we have a name to log...
    String signer = null;
    if (certs.length > 0) {
        signer = CertTools.getSubjectDN(certs[0]);
    }

    // We must find a cert to verify the signature with...
    boolean verifyOK = false;
    for (int i = 0; i < certs.length; i++) {
        if (req.verify(certs[i].getPublicKey(), "BC") == true) {
            signercert = certs[i];
            signer = CertTools.getSubjectDN(signercert);
            Date now = new Date();
            String signerissuer = CertTools.getIssuerDN(signercert);
            String infoMsg = intres.getLocalizedMessage("ocsp.infosigner", signer);
            m_log.info(infoMsg);
            verifyOK = true;
            // Also check that the signer certificate can be verified by one of the CA-certificates
            // that we answer for
            X509Certificate signerca = cacerts.findLatestBySubjectDN(HashID.getFromIssuerDN(certs[i]));
            String subject = signer;
            String issuer = signerissuer;
            if (signerca != null) {
                try {
                    signercert.verify(signerca.getPublicKey());
                    if (m_log.isDebugEnabled()) {
                        m_log.debug("Checking validity. Now: " + now + ", signerNotAfter: "
                                + signercert.getNotAfter());
                    }
                    CertTools.checkValidity(signercert, now);
                    // Move the error message string to the CA cert
                    subject = CertTools.getSubjectDN(signerca);
                    issuer = CertTools.getIssuerDN(signerca);
                    CertTools.checkValidity(signerca, now);
                } catch (SignatureException e) {
                    infoMsg = intres.getLocalizedMessage("ocsp.infosigner.invalidcertsignature", subject,
                            issuer, e.getMessage());
                    m_log.info(infoMsg);
                    verifyOK = false;
                } catch (InvalidKeyException e) {
                    infoMsg = intres.getLocalizedMessage("ocsp.infosigner.invalidcertsignature", subject,
                            issuer, e.getMessage());
                    m_log.info(infoMsg);
                    verifyOK = false;
                } catch (CertificateNotYetValidException e) {
                    infoMsg = intres.getLocalizedMessage("ocsp.infosigner.certnotyetvalid", subject, issuer,
                            e.getMessage());
                    m_log.info(infoMsg);
                    verifyOK = false;
                } catch (CertificateExpiredException e) {
                    infoMsg = intres.getLocalizedMessage("ocsp.infosigner.certexpired", subject, issuer,
                            e.getMessage());
                    m_log.info(infoMsg);
                    verifyOK = false;
                }
            } else {
                infoMsg = intres.getLocalizedMessage("ocsp.infosigner.nocacert", signer, signerissuer);
                m_log.info(infoMsg);
                verifyOK = false;
            }
            break;
        }
    }
    if (!verifyOK) {
        String errMsg = intres.getLocalizedMessage("ocsp.errorinvalidsignature", signer);
        m_log.info(errMsg);
        throw new SignRequestSignatureException(errMsg);
    }

    return signercert;
}