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.sinekartads.integration.cms.SignCMSonAlfresco.java

private void showCertificate(X509Certificate certificate) {
    Map<String, String> dns = DNParser.parse(certificate.getSubjectDN());
    tracer.info(String.format("subject:             %s", dns.get(SinekartaDsObjectIdentifiers.dn_commonName)));
    tracer.info(String.format("country:             %s", dns.get(SinekartaDsObjectIdentifiers.dn_countryName)));
    tracer.info(String.format("organization:        %s",
            dns.get(SinekartaDsObjectIdentifiers.dn_organizationName)));
    tracer.info(String.format("organization unit:   %s",
            dns.get(SinekartaDsObjectIdentifiers.dn_organizationUnitName)));
    tracer.info(String.format("not before:          %s", formatDate(certificate.getNotBefore())));
    tracer.info(String.format("not after:           %s", formatDate(certificate.getNotAfter())));
    dns = DNParser.parse(certificate.getIssuerDN());
    tracer.info(String.format("issuer:              %s", dns.get(SinekartaDsObjectIdentifiers.dn_commonName)));
}

From source file:de.duenndns.ssl.MemorizingTrustManager.java

private void certDetails(StringBuffer si, X509Certificate c) {
    SimpleDateFormat validityDateFormater = new SimpleDateFormat("yyyy-MM-dd");
    si.append("\n");
    si.append(c.getSubjectDN().toString());
    si.append("\n");
    si.append(validityDateFormater.format(c.getNotBefore()));
    si.append(" - ");
    si.append(validityDateFormater.format(c.getNotAfter()));
    si.append("\nSHA-256: ");
    si.append(certHash(c, "SHA-256"));
    si.append("\nSHA-1: ");
    si.append(certHash(c, "SHA-1"));
    si.append("\nSigned by: ");
    si.append(c.getIssuerDN().toString());
    si.append("\n");
}

From source file:ch.bfh.unicert.certimport.Certificate.java

/**
 * Create an object representing a X509 certificate with redundant information
 * @param cert the X509 certificate to store in the object
 * @param commonName the common name appearing in the given certificate
 * @param uniqueId the unique identifier appearing in the given certificate
 * @param organisation the organisation appearing in the given certificate
 * @param organisationUnit the organisation unit appearing in the given certificate
 * @param countryName the country appearing in the given certificate
 * @param state the state appearing in the given certificate
 * @param locality the locality appearing in the given certificate
 * @param surname the surname appearing in the given certificate
 * @param givenName the given name appearing in the given certificate
 * @param applicationIdentifier the identifier of the application the certificate is issued for
 * @param role the role the certificate is issued certificate
 * @param identityProvider the identity provider used to authenticate the requester of the certificate
 * @param extension the extension appearing in the given certificate
 * /*from www  .ja  v  a 2 s.co m*/
 * If some information does not appear in the certificate, null can be passed
 */
public Certificate(X509Certificate cert, String commonName, String uniqueId, String organisation,
        String organisationUnit, String countryName, String state, String locality, String surname,
        String givenName, String applicationIdentifier, String[] roles, String identityProvider,
        Map extension) {

    this.commonName = commonName;
    this.uniqueIdentifier = uniqueId;
    this.organisation = organisation;
    this.organisationUnit = organisationUnit;
    this.countryName = countryName;
    this.state = state;
    this.locality = locality;
    this.surname = surname;
    this.givenName = givenName;

    this.issuer = cert.getIssuerDN().getName();
    this.serialNumber = cert.getSerialNumber();
    this.validFrom = cert.getNotBefore();
    this.validUntil = cert.getNotAfter();
    this.applicationIdentifier = applicationIdentifier;
    this.roles = roles;
    this.identityProvider = identityProvider;
    this.extension = extension;
    try {
        this.pem = CertificateHelper.x509ToBase64PEMString(cert);
    } catch (IOException ex) {

        Logger.getLogger(Certificate.class.getName()).log(Level.SEVERE, null, ex);
    }
    this.cert = cert;
}

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  va2  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:com.stargame.ad.util.http.ssl.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {//from  w w  w  .  j a  v  a2  s.c o  m
        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: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 {//w  w w  .j  av  a  2s  .c o m
            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.otterca.persistence.dao.X509CertificateDaoDatastore.java

/**
 * @see com.otterca.persistence.dao.X509CertificateDao#put(java.security.cert
 *      .X509Certificate)//ww  w .  ja v a 2s.  c  o  m
 */
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:cn.org.eshow.framwork.http.ssl.AuthSSLProtocolSocketFactory.java

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

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 w  w  w  . j av a  2  s  .co  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.syncany.plugins.webdav.WebdavTransferManager.java

private String formatCertificate(X509Certificate cert) {
    try {//from   w w w .  ja  v a2 s . c  om
        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);
    }
}