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:net.sf.dsig.DSApplet.java

/**
 * Retrieve a JSON expression of certificate aliases and their corresponding
 * descriptions/*  www. jav  a  2  s  .c  om*/
 * @return a JSON expression
 * @category JavaScript exposed method
 */
public String getAliasedDescriptions() {
    available.acquireUninterruptibly();
    try {
        String json = "";
        KeyStoreProxy proxy = getKeyStoreProxy();

        Map<String, X509Certificate[]> aliasX509CertificateChainPair = createAliasX509CertificateChainPair(
                proxy);
        CertificateTableModel ctm = new CertificateTableModel(aliasX509CertificateChainPair, messages);
        Environment.getSingleton().init(ctm);

        for (int i = 0; i < ctm.getRowCount(); i++) {
            X509Certificate certificate = ctm.getX509Certificate(i);
            if (new Date().compareTo(certificate.getNotAfter()) > 0) {
                continue;
            }

            String alias = ctm.getAlias(i);

            // Column #0 is the name
            // Column #1 is the friendly name
            String name = (String) ctm.getValueAt(i, 0);
            if (name != null) {
                name = StringEscapeUtils.escapeJavaScript(name);
            }
            String friendlyName = (String) ctm.getValueAt(i, 1);
            if (friendlyName != null) {
                friendlyName = StringEscapeUtils.escapeJavaScript(friendlyName);
            }
            String compositeName = (friendlyName != null && friendlyName.length() > 0)
                    ? (friendlyName + " - " + name)
                    : name;

            String entry = "{ \"alias\": \"" + alias + "\", \"description\": \"" + compositeName + "\" }";

            if (json.length() > 0) {
                json += ", ";
            }
            json += entry;
        }

        return "[ " + json + " ]";
    } catch (Exception e) {
        handleError("DSA0002", e);

        return "";
    } finally {
        available.release();
    }
}

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  v a  2 s.co  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:nl.nn.adapterframework.webcontrol.api.ShowConfigurationStatus.java

private ArrayList<Object> getCertificateInfo(final URL url, final String password, String keyStoreType,
        String prefix) {/*from ww  w. j  a  v  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:test.unit.org.owasp.webscarab.util.SunCertificateUtilsTest.java

@Test
public void testSign() throws Exception {
    // setup//from ww  w  .  j a  v  a2s  .  c  om
    KeyPair caKeyPair = generateKeyPair();
    KeyPair entityKeyPair = generateKeyPair();
    X500Principal subject = new X500Principal("CN=Test");
    PublicKey pubKey = entityKeyPair.getPublic();
    X500Principal issuer = new X500Principal("CN=CA");
    PublicKey caPubKey = caKeyPair.getPublic();
    PrivateKey caKey = caKeyPair.getPrivate();
    Date begin = new Date();
    Date ends = new Date(begin.getTime() + (long) 1000 * 60 * 60 * 24 * 30);
    BigInteger serialNo = BigInteger.valueOf(1234);
    JcaX509ExtensionUtils jxeu = new JcaX509ExtensionUtils();

    // operate
    X509Certificate resultCert = SunCertificateUtils.sign(subject, pubKey, issuer, caPubKey, caKey, begin, ends,
            serialNo, null);

    // verify
    assertNotNull(resultCert);
    LOG.debug("result certificate: " + resultCert);
    resultCert.verify(caPubKey);
    assertEquals(subject, resultCert.getSubjectX500Principal());
    assertEquals(issuer, resultCert.getIssuerX500Principal());
    assertEquals(serialNo, resultCert.getSerialNumber());
    assertEquals(pubKey, resultCert.getPublicKey());
    LOG.debug("expected begin: " + begin.getTime());
    LOG.debug("actual begin: " + resultCert.getNotBefore().getTime());
    /*
     * BouncyCastle drops the milliseconds.
     */
    assertTrue(Math.abs(begin.getTime() - resultCert.getNotBefore().getTime()) < 1000);
    assertTrue(Math.abs(ends.getTime() - resultCert.getNotAfter().getTime()) < 1000);

    byte[] subjectKeyIdentifierExtValue = resultCert
            .getExtensionValue(X509Extension.subjectKeyIdentifier.getId());
    assertNotNull(subjectKeyIdentifierExtValue);
    ASN1Primitive subjectKeyIdentifier = JcaX509ExtensionUtils
            .parseExtensionValue(subjectKeyIdentifierExtValue);
    ASN1Primitive expSKI = jxeu.createSubjectKeyIdentifier(pubKey).toASN1Primitive();
    assertArrayEquals(expSKI.getEncoded(), subjectKeyIdentifier.getEncoded());

    byte[] authorityKeyIdentifierExtValue = resultCert
            .getExtensionValue(X509Extension.authorityKeyIdentifier.getId());
    ASN1Primitive authorityKeyIdentifier = JcaX509ExtensionUtils
            .parseExtensionValue(authorityKeyIdentifierExtValue);
    ASN1Primitive expAKI = jxeu.createAuthorityKeyIdentifier(caPubKey).toASN1Primitive();
    assertArrayEquals(expAKI.getEncoded(), authorityKeyIdentifier.getEncoded());

    assertEquals(-1, resultCert.getBasicConstraints());

    byte[] netscapeCertTypeExtValue = resultCert
            .getExtensionValue(MiscObjectIdentifiers.netscapeCertType.getId());
    assertNotNull(netscapeCertTypeExtValue);
    DERBitString netscapeCertTypeExt = (DERBitString) X509ExtensionUtil
            .fromExtensionValue(netscapeCertTypeExtValue);
    NetscapeCertType netscapeCertType = new NetscapeCertType(netscapeCertTypeExt);
    assertEquals(NetscapeCertType.sslClient, netscapeCertType.intValue() & NetscapeCertType.sslClient);
    assertEquals(NetscapeCertType.sslServer, netscapeCertType.intValue() & NetscapeCertType.sslServer);

    assertTrue(resultCert.getKeyUsage()[0]);
    assertTrue(resultCert.getKeyUsage()[2]);

    byte[] extendedKeyUsageExtValue = resultCert.getExtensionValue(X509Extension.extendedKeyUsage.getId());
    assertNotNull(extendedKeyUsageExtValue);
    ExtendedKeyUsage extendedKeyUsage = ExtendedKeyUsage
            .getInstance(X509ExtensionUtil.fromExtensionValue(extendedKeyUsageExtValue));
    assertTrue(extendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_clientAuth));
    assertTrue(extendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_serverAuth));
}

From source file:org.cesecore.certificates.ocsp.CanLogCache.java

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

From source file:com.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./*  w w w  .j a v a 2s  . co m*/
 * 
 * @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: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 w w w  . java  2s. c  o 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: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/* w  w w .  j  a  v a2  s  .c o m*/
        Logger.getLogger(AuthSSLProtocolSocketFactory.class).debug(" Certificate :" + cert.getType());
}

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: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)));
}