Example usage for java.security.cert X509Certificate checkValidity

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

Introduction

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

Prototype

public abstract void checkValidity(Date date)
        throws CertificateExpiredException, CertificateNotYetValidException;

Source Link

Document

Checks that the given date is within the certificate's validity period.

Usage

From source file:com.aqnote.shared.cryptology.cert.gen.CertGenerator.java

private X509Certificate createMiddleCaCert(X500Name subject, PublicKey pubKey, KeyPair pKeyPair,
        X500Name issuer) throws Exception {

    BigInteger sno = BigInteger.valueOf(3);
    Date nb = new Date(System.currentTimeMillis() - HALF_DAY);
    Date na = new Date(nb.getTime() + TWENTY_YEAR);

    X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuer, sno, nb, na, subject,
            pubKey);//from   ww  w  .j ava 2 s.  com

    addSubjectKID(certBuilder, pubKey);
    addAuthorityKID(certBuilder, pKeyPair.getPublic());
    certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(3));
    certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(BASE_EKU));

    X509Certificate certificate = signCert(certBuilder, pKeyPair.getPrivate());
    certificate.checkValidity(new Date());
    certificate.verify(pKeyPair.getPublic());

    setPKCS9Info(certificate);

    return certificate;
}

From source file:com.aqnote.shared.encrypt.cert.gen.BCCertGenerator.java

public X509Certificate createClass3EndCert(long sno, X500Name sdn, Map<String, String> exts, KeyPair keyPair,
        KeyPair pKeyPair) throws Exception {
    PublicKey pPubKey = pKeyPair.getPublic();
    PrivateKey pPrivKey = pKeyPair.getPrivate();

    X500Name idn = X500NameUtil.createClass3RootPrincipal();
    BigInteger _sno = BigInteger.valueOf(sno <= 0 ? System.currentTimeMillis() : sno);
    Date nb = new Date(System.currentTimeMillis() - HALF_DAY);
    Date na = new Date(nb.getTime() + FIVE_YEAR);
    PublicKey pubKey = keyPair.getPublic();

    X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(idn, _sno, nb, na, sdn, pubKey);

    addSubjectKID(certBuilder, pubKey);/*  w  ww.  j a va  2 s  .c o m*/
    addAuthorityKID(certBuilder, pPubKey);
    certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(MOST_EKU));
    certBuilder.addExtension(Extension.keyUsage, false, new KeyUsage(END_KEY_USAGE));
    if (exts != null) {
        Set<String> key = exts.keySet();
        for (Iterator<String> it = key.iterator(); it.hasNext();) {
            String oid = it.next();
            String value = exts.get(oid);
            if (!StringUtils.isBlank(value)) {
                certBuilder.addExtension(new ASN1ObjectIdentifier(oid), false,
                        new DEROctetString(value.getBytes()));
            }
        }
    }

    X509Certificate certificate = signCert(certBuilder, pPrivKey);
    certificate.checkValidity(new Date());
    certificate.verify(pPubKey);

    setPKCS9Info(certificate);

    return certificate;
}

From source file:gov.nih.nci.firebird.service.signing.DigitalSigningHelper.java

/**
 * Generate the CA's certificate.//  w w w  . ja  va  2s.  co  m
 *
 * @param publicKey
 *            Public key.
 * @param privateKey
 *            Private key.
 * @param distinguishedName
 *            Distinguished Name.
 * @param serialNumber
 *            Unique serial number.
 * @param validDays
 *            valid Days.
 * @param certFriendlyName  Certificate friendly name
 *
 * @throws DigitalSigningException
 *             Customized exception with error message.
 *
 * @return a Certificate.
 */
@SuppressWarnings({ "PMD.AvoidCatchingGenericException", "PMD.ExcessiveParameterList" })
// same handling for multiple exception types, parameters required for generation
Certificate generateRootCert(PublicKey publicKey, PrivateKey privateKey,
        DigitalSigningDistinguishedName distinguishedName, long serialNumber, int validDays,
        String certFriendlyName) throws DigitalSigningException {

    try {
        X509V1CertificateGenerator v1CertGen = buildX509V1CertificateGenerator(publicKey, distinguishedName,
                serialNumber, validDays);
        X509Certificate cert = v1CertGen.generate(privateKey, BOUNCY_CASTLE_PROVIDER);
        cert.checkValidity(new Date());
        cert.verify(publicKey);
        PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) cert;
        bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
                new DERBMPString(certFriendlyName));
        return cert;
    } catch (Exception e) {
        throw new DigitalSigningException(ROOT_CA_GENERATION_ERROR_MESSAGE, e);
    }
}

From source file:gov.nih.nci.firebird.service.signing.DigitalSigningHelper.java

/**
 * Generate intermediate certificate signed by CA.
 *
 * @param publicKey//from w w w.  j  a  va2 s  . c  om
 *            Public key.
 * @param caPrivateKey
 *            Private key.
 * @param caDistinguishedName
 *            Issuer's Distinguished Name..
 * @param distinguishedName
 *            User's Distinguished Name.
 * @param serialNumber
 *            Unique serial number.
 * @param validDays
 *            valid Days.
 * @param friendName
 *            Set a friendly name for the certificate. Can be null.
 *
 * @throws DigitalSigningException
 *             Customized exception with error message.
 *
 * @return a Certificate.
 */
@SuppressWarnings({ "PMD.ExcessiveParameterList", "PMD.AvoidCatchingGenericException" })
// This is minimal parameter list.
// same handling for multiple exception types
Certificate generateUserCert(PublicKey publicKey, PrivateKey caPrivateKey, X509Certificate caCert,
        DigitalSigningDistinguishedName distinguishedName, long serialNumber, int validDays)
        throws DigitalSigningException {
    try {
        X509V3CertificateGenerator v3CertGen = buildX509V3CertificateGenerator(publicKey, caCert,
                distinguishedName, serialNumber, validDays);
        X509Certificate cert = v3CertGen.generate(caPrivateKey, BOUNCY_CASTLE_PROVIDER);
        cert.checkValidity(new Date());
        cert.verify(caCert.getPublicKey());
        PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) cert;

        bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
                new DERBMPString("User Certificate"));
        bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                new SubjectKeyIdentifierStructure(publicKey));

        return cert;
    } catch (Exception e) {
        throw new DigitalSigningException(CERT_GENERATION_ERROR_MESSAGE, e);
    }
}

From source file:be.fedict.trust.TrustValidator.java

private void checkSelfSignedTrust(X509Certificate certificate, Date validationDate)
        throws CertPathValidatorException {
    try {/*from  w ww.ja  va 2  s.  c  om*/
        certificate.checkValidity(validationDate);
    } catch (Exception e) {
        this.result = new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_VALIDITY_INTERVAL,
                "certificate validity error: " + e.getMessage());
        throw new CertPathValidatorException(this.result.getMessage());
    }
    if (this.certificateRepository.isTrustPoint(certificate)) {
        return;
    }

    this.result = new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST,
            "self-signed certificate not in repository: " + certificate.getSubjectX500Principal());
    throw new CertPathValidatorException(this.result.getMessage());
}

From source file:org.apache.drill.exec.server.rest.WebServer.java

/**
 * Create an HTTPS connector for given jetty server instance. If the admin has specified keystore/truststore settings
 * they will be used else a self-signed certificate is generated and used.
 *
 * @return Initialized {@link ServerConnector} for HTTPS connectios.
 * @throws Exception/*from   ww w  .j av a2 s  .  c om*/
 */
private ServerConnector createHttpsConnector() throws Exception {
    logger.info("Setting up HTTPS connector for web server");

    final SslContextFactory sslContextFactory = new SslContextFactory();

    if (config.hasPath(ExecConstants.HTTP_KEYSTORE_PATH)
            && !Strings.isNullOrEmpty(config.getString(ExecConstants.HTTP_KEYSTORE_PATH))) {
        logger.info("Using configured SSL settings for web server");
        sslContextFactory.setKeyStorePath(config.getString(ExecConstants.HTTP_KEYSTORE_PATH));
        sslContextFactory.setKeyStorePassword(config.getString(ExecConstants.HTTP_KEYSTORE_PASSWORD));

        // TrustStore and TrustStore password are optional
        if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PATH)) {
            sslContextFactory.setTrustStorePath(config.getString(ExecConstants.HTTP_TRUSTSTORE_PATH));
            if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)) {
                sslContextFactory
                        .setTrustStorePassword(config.getString(ExecConstants.HTTP_TRUSTSTORE_PASSWORD));
            }
        }
    } else {
        logger.info("Using generated self-signed SSL settings for web server");
        final SecureRandom random = new SecureRandom();

        // Generate a private-public key pair
        final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024, random);
        final KeyPair keyPair = keyPairGenerator.generateKeyPair();

        final DateTime now = DateTime.now();

        // Create builder for certificate attributes
        final X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE)
                .addRDN(BCStyle.OU, "Apache Drill (auth-generated)")
                .addRDN(BCStyle.O, "Apache Software Foundation (auto-generated)")
                .addRDN(BCStyle.CN, workManager.getContext().getEndpoint().getAddress());

        final Date notBefore = now.minusMinutes(1).toDate();
        final Date notAfter = now.plusYears(5).toDate();
        final BigInteger serialNumber = new BigInteger(128, random);

        // Create a certificate valid for 5years from now.
        final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), // attributes
                serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic());

        // Sign the certificate using the private key
        final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
                .build(keyPair.getPrivate());
        final X509Certificate certificate = new JcaX509CertificateConverter()
                .getCertificate(certificateBuilder.build(contentSigner));

        // Check the validity
        certificate.checkValidity(now.toDate());

        // Make sure the certificate is self-signed.
        certificate.verify(certificate.getPublicKey());

        // Generate a random password for keystore protection
        final String keyStorePasswd = RandomStringUtils.random(20);
        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null, null);
        keyStore.setKeyEntry("DrillAutoGeneratedCert", keyPair.getPrivate(), keyStorePasswd.toCharArray(),
                new java.security.cert.Certificate[] { certificate });

        sslContextFactory.setKeyStore(keyStore);
        sslContextFactory.setKeyStorePassword(keyStorePasswd);
    }

    final HttpConfiguration httpsConfig = new HttpConfiguration();
    httpsConfig.addCustomizer(new SecureRequestCustomizer());

    // SSL Connector
    final ServerConnector sslConnector = new ServerConnector(embeddedJetty,
            new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
            new HttpConnectionFactory(httpsConfig));
    sslConnector.setPort(config.getInt(ExecConstants.HTTP_PORT));

    return sslConnector;
}

From source file:org.jvnet.hudson.update_center.Main.java

/**
 * Loads a certificate chain and makes sure it's valid.
 *//*  w  w  w  . ja v  a 2s  .com*/
protected List<X509Certificate> getCertificateChain() throws IOException, GeneralSecurityException {
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    for (File f : certificates) {
        X509Certificate c = loadCertificate(cf, f);
        c.checkValidity(new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(30)));
        certs.add(c);
    }

    Set<TrustAnchor> rootCAs = CertificateUtil.getDefaultRootCAs();
    rootCAs.add(new TrustAnchor(
            (X509Certificate) cf.generateCertificate(getClass().getResourceAsStream("/hudson-community.cert")),
            null));
    for (File f : rootCA) {
        rootCAs.add(new TrustAnchor(loadCertificate(cf, f), null));
    }

    try {
        CertificateUtil.validatePath(certs, rootCAs);
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    }
    return certs;
}

From source file:com.vmware.demo.SamlUtils.java

/**
 * Generate a public x509 cert, based on a key.
 *
 * @param key KeyPair used to generate public Cert, private key in KeyPair not exposed.
 * @param issuer If generating an SSL Cert, issuer needs to match hostname
 * @return//  ww  w .jav  a  2s .  co  m
 * @throws SamlException
 */
public static X509Certificate generateCert(KeyPair key, String issuer) throws SamlException {
    X509Certificate binCert;
    try {
        X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

        // create the certificate - version 3
        v3CertGen.reset();
        v3CertGen.setSerialNumber(BigInteger.valueOf(1));
        v3CertGen.setIssuerDN(new X509Principal(issuer));
        v3CertGen.setNotBefore(new Date(System.currentTimeMillis()));
        v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10))); //10 years
        v3CertGen.setSubjectDN(new X509Principal(issuer));
        v3CertGen.setPublicKey(key.getPublic());
        v3CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

        // add the extensions
        v3CertGen.addExtension(org.bouncycastle.asn1.x509.X509Extensions.BasicConstraints, false,
                new BasicConstraints(true));

        // generate the actual cert
        binCert = v3CertGen.generate(key.getPrivate());

        // check the cert
        binCert.checkValidity(new Date());
        binCert.verify(key.getPublic());
    } catch (Exception e) {
        throw new SamlException("Failed to generate certificate.", e);
    }

    return binCert;
}

From source file:org.apache.drill.cv.exec.server.rest.CvDrillWebServer.java

/**
 * Create an HTTPS connector for given jetty server instance. If the admin has specified
 * keystore/truststore settings they will be used else a self-signed certificate is generated and
 * used./*from  w ww.  j  ava  2 s.co m*/
 *
 * @return Initialized {@link ServerConnector} for HTTPS connectios.
 * @throws Exception
 */
private ServerConnector createHttpsConnector() throws Exception {
    CvDrillWebServer.logger.info("Setting up HTTPS connector for web server");

    final SslContextFactory sslContextFactory = new SslContextFactory();

    if (config.hasPath(ExecConstants.HTTP_KEYSTORE_PATH)
            && !Strings.isNullOrEmpty(config.getString(ExecConstants.HTTP_KEYSTORE_PATH))) {
        CvDrillWebServer.logger.info("Using configured SSL settings for web server");
        sslContextFactory.setKeyStorePath(config.getString(ExecConstants.HTTP_KEYSTORE_PATH));
        sslContextFactory.setKeyStorePassword(config.getString(ExecConstants.HTTP_KEYSTORE_PASSWORD));

        // TrustStore and TrustStore password are optional
        if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PATH)) {
            sslContextFactory.setTrustStorePath(config.getString(ExecConstants.HTTP_TRUSTSTORE_PATH));
            if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)) {
                sslContextFactory
                        .setTrustStorePassword(config.getString(ExecConstants.HTTP_TRUSTSTORE_PASSWORD));
            }
        }
    } else {
        CvDrillWebServer.logger.info("Using generated self-signed SSL settings for web server");
        final SecureRandom random = new SecureRandom();

        // Generate a private-public key pair
        final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024, random);
        final KeyPair keyPair = keyPairGenerator.generateKeyPair();

        final DateTime now = DateTime.now();

        // Create builder for certificate attributes
        final X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE)
                .addRDN(BCStyle.OU, "Apache Drill (auth-generated)")
                .addRDN(BCStyle.O, "Apache Software Foundation (auto-generated)")
                .addRDN(BCStyle.CN, workManager.getContext().getEndpoint().getAddress());

        final Date notBefore = now.minusMinutes(1).toDate();
        final Date notAfter = now.plusYears(5).toDate();
        final BigInteger serialNumber = new BigInteger(128, random);

        // Create a certificate valid for 5years from now.
        final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), // attributes
                serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic());

        // Sign the certificate using the private key
        final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
                .build(keyPair.getPrivate());
        final X509Certificate certificate = new JcaX509CertificateConverter()
                .getCertificate(certificateBuilder.build(contentSigner));

        // Check the validity
        certificate.checkValidity(now.toDate());

        // Make sure the certificate is self-signed.
        certificate.verify(certificate.getPublicKey());

        // Generate a random password for keystore protection
        final String keyStorePasswd = RandomStringUtils.random(20);
        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null, null);
        keyStore.setKeyEntry("DrillAutoGeneratedCert", keyPair.getPrivate(), keyStorePasswd.toCharArray(),
                new java.security.cert.Certificate[] { certificate });

        sslContextFactory.setKeyStore(keyStore);
        sslContextFactory.setKeyStorePassword(keyStorePasswd);
    }

    final HttpConfiguration httpsConfig = new HttpConfiguration();
    httpsConfig.addCustomizer(new SecureRequestCustomizer());

    // SSL Connector
    final ServerConnector sslConnector = new ServerConnector(embeddedJetty,
            new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
            new HttpConnectionFactory(httpsConfig));
    sslConnector.setPort(getWebserverPort());

    return sslConnector;
}

From source file:org.apache.drill.yarn.appMaster.http.WebServer.java

/**
 * Create an HTTPS connector for given jetty server instance. If the admin has
 * specified keystore/truststore settings they will be used else a self-signed
 * certificate is generated and used.//from   ww w .  j a  v a 2  s  .c  o  m
 * <p>
 * This is a shameless copy of
 * {@link org.apache.drill.exec.server.rest.Webserver#createHttpsConnector( )}.
 * The two should be merged at some point. The primary issue is that the Drill
 * version is tightly coupled to Drillbit configuration.
 *
 * @return Initialized {@link ServerConnector} for HTTPS connections.
 * @throws Exception
 */

private ServerConnector createHttpsConnector(Config config) throws Exception {
    LOG.info("Setting up HTTPS connector for web server");

    final SslContextFactory sslContextFactory = new SslContextFactory();

    // if (config.hasPath(ExecConstants.HTTP_KEYSTORE_PATH) &&
    // !Strings.isNullOrEmpty(config.getString(ExecConstants.HTTP_KEYSTORE_PATH)))
    // {
    // LOG.info("Using configured SSL settings for web server");
    // sslContextFactory.setKeyStorePath(config.getString(ExecConstants.HTTP_KEYSTORE_PATH));
    // sslContextFactory.setKeyStorePassword(config.getString(ExecConstants.HTTP_KEYSTORE_PASSWORD));
    //
    // // TrustStore and TrustStore password are optional
    // if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PATH)) {
    // sslContextFactory.setTrustStorePath(config.getString(ExecConstants.HTTP_TRUSTSTORE_PATH));
    // if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)) {
    // sslContextFactory.setTrustStorePassword(config.getString(ExecConstants.HTTP_TRUSTSTORE_PASSWORD));
    // }
    // }
    // } else {
    LOG.info("Using generated self-signed SSL settings for web server");
    final SecureRandom random = new SecureRandom();

    // Generate a private-public key pair
    final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024, random);
    final KeyPair keyPair = keyPairGenerator.generateKeyPair();

    final DateTime now = DateTime.now();

    // Create builder for certificate attributes
    final X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE)
            .addRDN(BCStyle.OU, "Apache Drill (auth-generated)")
            .addRDN(BCStyle.O, "Apache Software Foundation (auto-generated)").addRDN(BCStyle.CN, "Drill AM");

    final Date notBefore = now.minusMinutes(1).toDate();
    final Date notAfter = now.plusYears(5).toDate();
    final BigInteger serialNumber = new BigInteger(128, random);

    // Create a certificate valid for 5years from now.
    final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), // attributes
            serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic());

    // Sign the certificate using the private key
    final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
            .build(keyPair.getPrivate());
    final X509Certificate certificate = new JcaX509CertificateConverter()
            .getCertificate(certificateBuilder.build(contentSigner));

    // Check the validity
    certificate.checkValidity(now.toDate());

    // Make sure the certificate is self-signed.
    certificate.verify(certificate.getPublicKey());

    // Generate a random password for keystore protection
    final String keyStorePasswd = RandomStringUtils.random(20);
    final KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(null, null);
    keyStore.setKeyEntry("DrillAutoGeneratedCert", keyPair.getPrivate(), keyStorePasswd.toCharArray(),
            new java.security.cert.Certificate[] { certificate });

    sslContextFactory.setKeyStore(keyStore);
    sslContextFactory.setKeyStorePassword(keyStorePasswd);
    // }

    final HttpConfiguration httpsConfig = new HttpConfiguration();
    httpsConfig.addCustomizer(new SecureRequestCustomizer());

    // SSL Connector
    final ServerConnector sslConnector = new ServerConnector(jettyServer,
            new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
            new HttpConnectionFactory(httpsConfig));
    sslConnector.setPort(config.getInt(DrillOnYarnConfig.HTTP_PORT));

    return sslConnector;
}