Example usage for java.security.cert X509Certificate getNotBefore

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

Introduction

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

Prototype

public abstract Date getNotBefore();

Source Link

Document

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

Usage

From source file:org.ovirt.engine.core.utils.ssl.AuthSSLProtocolSocketFactory.java

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

From source file:org.openanzo.client.AnzoTrustManager.java

private void handleCertificateException(CertificateException ce, X509Certificate[] chain)
        throws CertificateException {
    if (trustAll) {
        return;//  w  w w .  ja  v a  2  s.  co m
    }

    System.err.println(ce.getMessage());
    System.err.println("Certificate Information: \n");
    Calendar cal = new GregorianCalendar();
    cal.setTimeInMillis(chain[0].getNotBefore().getTime());
    System.err.println("Creation Date: " + MONTHS[cal.get(Calendar.MONTH)] + " "
            + cal.get(Calendar.DAY_OF_MONTH) + ", " + cal.get(Calendar.YEAR));
    //System.err.println("Entry type: " + chain[0].getType());
    System.err.println("Certificate chain length: " + chain.length);

    // print some information about the certificate(s) that failed
    int i = 1;
    for (X509Certificate cert : chain) {
        System.err.println("Certificate[" + i++ + "]:");
        System.err.println("Owner: " + cert.getSubjectX500Principal().toString());
        System.err.println("Issuer: " + cert.getIssuerX500Principal().toString());

        String serialNum = new String(Hex.encodeHex(cert.getSerialNumber().toByteArray()));
        System.err.println("Serial Number: " + serialNum);
        System.err.println(
                "Valid from: " + cert.getNotBefore().toString() + " until: " + cert.getNotAfter().toString());
        System.err.println("Certificate fingerprints: ");
        try {
            byte[] sig = cert.getEncoded();
            System.err.println("\tMD5: " + getHash(sig, "MD5"));
            System.err.println("\tSHA1: " + getHash(sig, "SHA1"));
        } catch (NoSuchAlgorithmException e) {
        }
        System.err.println("\tSignature Algorithm Name: " + cert.getSigAlgName());
        System.err.println("\tVersion: " + cert.getVersion());
        System.err.println("-----------------------------------------------------");
    }
    System.err.println("Would you like to accept this certificate? (o)nce, (a)lways, (n)o");
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String line = "";
    try {
        line = in.readLine();
    } catch (IOException e) {
        CommandLineInterface.DEFAULT_CONSOLE.printException(e, showTrace);
        System.exit(1);
    }
    if (Character.toLowerCase(line.charAt(0)) == 'o') {
        return;
    } else if (Character.toLowerCase(line.charAt(0)) == 'a') {
        try {
            String truststoreType = System.getProperty("javax.net.ssl.trustStoreType", "JCEKS");
            String truststorePassword = System.getProperty("javax.net.ssl.trustStorePassword", DEFAULT_PWORD);

            String truststorePath = System.getProperty("javax.net.ssl.trustStore");
            if (truststorePath == null) { // there is no trust store location in the user's settings.trig file
                String userHome = System.getProperty("user.home");
                if (userHome == null)
                    throw new AnzoException(ExceptionConstants.CLIENT.FAILED_INITIALIZE_TRUST_MANAGER,
                            "User's home directory is not specified");
                File truststoreFile = new File(new File(userHome, ANZO_DIR), DEFAULT_CLIENT_TRUST);
                truststorePath = truststoreFile.getCanonicalPath();
                if (!truststoreFile.exists())
                    openTruststore(truststoreType, truststorePath, truststorePassword);
            } else {
                truststorePath = CommandContext.preprocessString(truststorePath);
                File truststoreFile = new File(truststorePath);

                if (!truststoreFile.exists()) {
                    System.err.println("Could not find the specified trust store file at:");
                    System.err.println(truststoreFile.getCanonicalPath());
                    System.err.println(
                            "The trust store file is used for permanently trusting server certificates that");
                    System.err.println("are not trusted by default.");
                    System.err.println(
                            "Would you like to create a new trust store file at the specified location?");
                    System.err.println("(y)es, (n)o");
                    try {
                        line = in.readLine();
                    } catch (IOException e) {
                        CommandLineInterface.DEFAULT_CONSOLE.printException(e, showTrace);
                        System.exit(1);
                    }
                    if (Character.toLowerCase(line.charAt(0)) == 'y')
                        openTruststore(truststoreType, truststorePath, truststorePassword);
                    else
                        System.exit(1);
                }
            }

            KeystoreUtils.addTrustedCert(truststorePath, truststoreType, truststorePassword,
                    "imported_" + System.currentTimeMillis(), chain[0]);
        } catch (AnzoException ae) {
            System.err.println("Error importing certificate into truststore: ");
            CommandLineInterface.DEFAULT_CONSOLE.printException(ae, showTrace);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Error importing certificate into truststore: ");
            CommandLineInterface.DEFAULT_CONSOLE.printException(e, showTrace);
            System.exit(1);
        }
    } else {
        System.exit(1); // if the user does not want to trust the certificate then exit
    }
}

From source file:com.qut.middleware.crypto.impl.CryptoProcessorImpl.java

public KeyStore generateKeyStore() throws CryptoException {
    try {//  w w  w  .  jav a 2  s. c om
        logger.debug("Generating a new key store.");

        /* Add BC to the jdk security manager to be able to use it as a provider */
        Security.addProvider(new BouncyCastleProvider());

        /* Create and init an empty key store */
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null, null);

        /*
         * Populate all new key stores with the key data of the local resolver, generally this is for metadata
         * purposes to ensure that all systems in the authentication network can correctly validate the signed
         * metadata document
         */
        X509Certificate localCertificate = (X509Certificate) localResolver.getLocalCertificate();
        Calendar before = new GregorianCalendar();
        Calendar expiry = new GregorianCalendar();
        before.setTime(localCertificate.getNotBefore());
        expiry.setTime(localCertificate.getNotAfter());

        addPublicKey(keyStore,
                new KeyPair(this.localResolver.getLocalPublicKey(), this.localResolver.getLocalPrivateKey()),
                this.localResolver.getLocalKeyAlias(), this.certIssuerDN, before, expiry);

        return keyStore;
    } catch (KeyStoreException e) {
        this.logger.error("KeyStoreException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        this.logger.error("NoSuchAlgorithmException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (CertificateException e) {
        this.logger.error("CertificateException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (IOException e) {
        this.logger.error("IOException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    }
}

From source file:hk.hku.cecid.ebms.admin.listener.PartnershipPageletAdaptor.java

private void getCertificateForPartnership(byte[] cert, PropertyTree dom, String prefix) {
    if (cert != null) {
        try {/*  w  w  w . j a  va2  s.  c o m*/
            ByteArrayInputStream bais = new ByteArrayInputStream(cert);
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate verifyCert = (X509Certificate) cf.generateCertificate(bais);
            bais.close();
            dom.setProperty(prefix + "issuer", verifyCert.getIssuerDN().getName());
            dom.setProperty(prefix + "subject", verifyCert.getSubjectDN().getName());
            dom.setProperty(prefix + "thumbprint", getCertFingerPrint(verifyCert));
            dom.setProperty(prefix + "valid-from", StringUtilities.toGMTString(verifyCert.getNotBefore()));
            dom.setProperty(prefix + "valid-to", StringUtilities.toGMTString(verifyCert.getNotAfter()));
        } catch (Exception e) {
            dom.setProperty(prefix + "Error", e.toString());
        }
    } else {
        dom.setProperty(prefix, "");
    }
}

From source file:it.greenvulcano.gvesb.http.ssl.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {/*  ww  w. ja  va2  s . com*/
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreID != null) {
            KeyStore keystore = createKeyStore(this.keystoreID);
            if (logger.isDebugEnabled()) {
                Enumeration<String> aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        logger.debug("Certificate chain '" + alias + "':");
                        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());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keyPassword);
        }
        if (this.truststoreID != null) {
            KeyStore keystore = createKeyStore(this.truststoreID);
            if (logger.isDebugEnabled()) {
                Enumeration<String> aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = aliases.nextElement();
                    logger.debug("Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        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());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslctx = SSLContext.getInstance("SSL");
        sslctx.init(keymanagers, trustmanagers, null);
        return sslctx;
    } catch (NoSuchAlgorithmException e) {
        logger.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        logger.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        logger.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:nl.nn.adapterframework.webcontrol.api.ShowConfigurationStatus.java

private ArrayList<Object> getCertificateInfo(final URL url, final String password, String keyStoreType,
        String prefix) {//from w w  w.  j av  a2  s.c o m
    ArrayList<Object> certificateList = new ArrayList<Object>();
    try {
        KeyStore keystore = KeyStore.getInstance(keyStoreType);
        keystore.load(url.openStream(), password != null ? password.toCharArray() : null);
        if (log.isInfoEnabled()) {
            Enumeration<String> aliases = keystore.aliases();
            while (aliases.hasMoreElements()) {
                String alias = (String) aliases.nextElement();
                ArrayList<Object> infoElem = new ArrayList<Object>();
                infoElem.add(prefix + " '" + alias + "':");
                Certificate trustedcert = keystore.getCertificate(alias);
                if (trustedcert != null && trustedcert instanceof X509Certificate) {
                    X509Certificate cert = (X509Certificate) trustedcert;
                    infoElem.add("Subject DN: " + cert.getSubjectDN());
                    infoElem.add("Signature Algorithm: " + cert.getSigAlgName());
                    infoElem.add("Valid from: " + cert.getNotBefore());
                    infoElem.add("Valid until: " + cert.getNotAfter());
                    infoElem.add("Issuer: " + cert.getIssuerDN());
                }
                certificateList.add(infoElem);
            }
        }
    } catch (Exception e) {
        certificateList.add("*** ERROR ***");
    }
    return certificateList;
}

From source file:com.otterca.persistence.dao.X509CertificateDaoDatastore.java

/**
 * Verify that cached results are consistent. It's a strong indication that
 * someone has been screwing with the database if the values are
 * inconsistent. This is computationally expensive but the cost of a
 * corrupted database is far worse.//from   w  w  w  .j ava 2 s .com
 * 
 * @param entity
 * @param cert
 */
public void validate(Entity entity, X509Certificate cert) throws CertificateException {
    if (!cert.getSerialNumber().equals(entity.getProperty(SERIAL_NUMBER))) {
        throw new CertificateException("serial number did not match");
    }
    if (!cert.getIssuerDN().equals(entity.getProperty(ISSUER_DN))) {
        throw new CertificateException("issuer dn did not match");
    }
    if (!cert.getSubjectDN().equals(entity.getProperty(SUBJECT_DN))) {
        throw new CertificateException("subject dn did not match");
    }
    if (!cert.getNotBefore().equals(entity.getProperty(NOT_BEFORE))) {
        throw new CertificateException("notBefore did not match");
    }
    if (!cert.getNotAfter().equals(entity.getProperty(NOT_AFTER))) {
        throw new CertificateException("notAfter did not match");
    }
    if (!x509CertUtil.getName(cert).equals(entity.getProperty(COMMON_NAME))) {
        throw new CertificateException("common name did not match");
    }
    if (!x509CertUtil.getFingerprint(cert).equals(entity.getProperty(FINGERPRINT))) {
        throw new CertificateException("cached fingerprints did not match");
    }
    if (!x509CertUtil.getCertificateHash(cert).equals(entity.getProperty(CERT_HASH))) {
        throw new CertificateException("cached certificate hash did not match");
    }
    if (!x509CertUtil.getIHash(cert).equals(entity.getProperty(ISSUER_HASH))) {
        throw new CertificateException("cached issuer hash did not match");
    }
    if (!x509CertUtil.getSHash(cert).equals(entity.getProperty(SUBJECT_HASH))) {
        throw new CertificateException("cached subject hash did not match");
    }
    if (!x509CertUtil.getAkidHash(cert).equals(entity.getProperty(AKID_HASH))) {
        throw new CertificateException("cached AKID hash did not match");
    }
    if (!x509CertUtil.getSkidHash(cert).equals(entity.getProperty(SKID_HASH))) {
        throw new CertificateException("cached SKID hash did not match");
    }
}

From source file:org.apache.nifi.toolkit.tls.util.TlsHelperTest.java

@Test
public void testIssueCert() throws IOException, CertificateException, NoSuchAlgorithmException,
        OperatorCreationException, NoSuchProviderException, InvalidKeyException, SignatureException {
    X509Certificate issuer = loadCertificate(
            new InputStreamReader(getClass().getClassLoader().getResourceAsStream("rootCert.crt")));
    KeyPair issuerKeyPair = loadKeyPair(
            new InputStreamReader(getClass().getClassLoader().getResourceAsStream("rootCert.key")));

    String dn = "CN=testIssued, O=testOrg";

    KeyPair keyPair = TlsHelper.generateKeyPair(keyPairAlgorithm, keySize);
    X509Certificate x509Certificate = CertificateUtils.generateIssuedCertificate(dn, keyPair.getPublic(),
            issuer, issuerKeyPair, signingAlgorithm, days);
    assertEquals(dn, x509Certificate.getSubjectX500Principal().toString());
    assertEquals(issuer.getSubjectX500Principal().toString(),
            x509Certificate.getIssuerX500Principal().toString());
    assertEquals(keyPair.getPublic(), x509Certificate.getPublicKey());

    Date notAfter = x509Certificate.getNotAfter();
    assertTrue(notAfter.after(inFuture(days - 1)));
    assertTrue(notAfter.before(inFuture(days + 1)));

    Date notBefore = x509Certificate.getNotBefore();
    assertTrue(notBefore.after(inFuture(-1)));
    assertTrue(notBefore.before(inFuture(1)));

    assertEquals(signingAlgorithm, x509Certificate.getSigAlgName());
    assertEquals(keyPairAlgorithm, x509Certificate.getPublicKey().getAlgorithm());

    x509Certificate.verify(issuerKeyPair.getPublic());
}

From source file:gov.va.med.imaging.proxy.ssl.AuthSSLProtocolSocketFactory.java

private void logCertificateContents(Certificate cert) {
    if (cert instanceof X509Certificate) {
        X509Certificate x509Cert = (X509Certificate) cert;
        Logger.getLogger(AuthSSLProtocolSocketFactory.class).debug(" X509 Certificate :");
        Logger.getLogger(AuthSSLProtocolSocketFactory.class).debug("  Subject DN: " + x509Cert.getSubjectDN());
        Logger.getLogger(AuthSSLProtocolSocketFactory.class)
                .debug("  Signature Algorithm: " + x509Cert.getSigAlgName());
        Logger.getLogger(AuthSSLProtocolSocketFactory.class)
                .debug("  Signature: " + x509Cert.getPublicKey().toString());
        Logger.getLogger(AuthSSLProtocolSocketFactory.class).debug("  Valid from: " + x509Cert.getNotBefore());
        Logger.getLogger(AuthSSLProtocolSocketFactory.class).debug("  Valid until: " + x509Cert.getNotAfter());
        Logger.getLogger(AuthSSLProtocolSocketFactory.class).debug("  Issuer: " + x509Cert.getIssuerDN());
    } else/*from w  w w  .  j  a  va 2 s.c  om*/
        Logger.getLogger(AuthSSLProtocolSocketFactory.class).debug(" Certificate :" + cert.getType());
}

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 w ww.  ja v  a2  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);
    }
}