List of usage examples for java.security.cert X509Certificate checkValidity
public abstract void checkValidity(Date date) throws CertificateExpiredException, CertificateNotYetValidException;
From source file:com.wandrell.util.ksgen.BouncyCastleKeyStoreFactory.java
/** * Returns a {@code Certificate} with the received data. * * @param keypair/*from w ww. j a v a2s . c o m*/ * key pair for the certificate * @param issuer * issuer for the certificate * @return a {@code Certificate} with the received data * @throws IOException * if there is an I/O or format problem with the certificate * data * @throws OperatorCreationException * if there was a problem creation a bouncy castle operator * @throws CertificateException * if any of the certificates in the keystore could not be * loaded * @throws InvalidKeyException * if there was a problem with the key * @throws NoSuchAlgorithmException * if an algorithm required to create the key store could not be * found * @throws NoSuchProviderException * if a required provider is missing * @throws SignatureException * if any problem occurs while signing the certificate */ private final Certificate getCertificate(final KeyPair keypair, final String issuer) throws IOException, OperatorCreationException, CertificateException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException { final X509v3CertificateBuilder builder; // Certificate builder final X509Certificate certificate; // Certificate // Generates the certificate builder builder = getCertificateBuilder(keypair.getPublic(), issuer); // Generates the signed certificate certificate = getSignedCertificate(builder, keypair.getPrivate()); // Verifies the certificate certificate.checkValidity(getCurrentDate()); certificate.verify(keypair.getPublic()); LOGGER.debug("Created certificate of type {} with encoded value {}", certificate.getType(), Arrays.asList(certificate.getEncoded())); LOGGER.debug("Created certificate with public key:{}", certificate.getPublicKey()); return certificate; }
From source file:org.forgerock.openidm.security.impl.SecurityResourceProvider.java
/** * Generates a self signed certificate using the given properties. * * @param commonName the subject's common name * @param organization the subject's organization name * @param organizationUnit the subject's organization unit name * @param stateOrProvince the subject's state or province * @param country the subject's country code * @param locality the subject's locality * @param algorithm the algorithm to use * @param keySize the keysize to use/*from ww w. j a v a 2 s .c o m*/ * @param signatureAlgorithm the signature algorithm to use * @param validFrom when the certificate is valid from * @param validTo when the certificate is valid until * @return The generated certificate * @throws Exception */ protected Pair<X509Certificate, PrivateKey> generateCertificate(String commonName, String organization, String organizationUnit, String stateOrProvince, String country, String locality, String algorithm, int keySize, String signatureAlgorithm, String validFrom, String validTo) throws Exception { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm); // "RSA","BC" keyPairGenerator.initialize(keySize); KeyPair keyPair = keyPairGenerator.generateKeyPair(); // Generate self-signed certificate X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE); builder.addRDN(BCStyle.C, country); builder.addRDN(BCStyle.ST, stateOrProvince); builder.addRDN(BCStyle.L, locality); builder.addRDN(BCStyle.OU, organizationUnit); builder.addRDN(BCStyle.O, organization); builder.addRDN(BCStyle.CN, commonName); Date notBefore = null; Date notAfter = null; if (validFrom == null) { notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30); } else { DateTime notBeforeDateTime = DateUtil.getDateUtil().parseIfDate(validFrom); if (notBeforeDateTime == null) { throw new InternalServerErrorException("Invalid date format for 'validFrom' property"); } else { notBefore = notBeforeDateTime.toDate(); } } if (validTo == null) { Calendar date = Calendar.getInstance(); date.setTime(new Date()); date.add(Calendar.YEAR, 10); notAfter = date.getTime(); } else { DateTime notAfterDateTime = DateUtil.getDateUtil().parseIfDate(validTo); if (notAfterDateTime == null) { throw new InternalServerErrorException("Invalid date format for 'validTo' property"); } else { notAfter = notAfterDateTime.toDate(); } } BigInteger serial = BigInteger.valueOf(System.currentTimeMillis()); X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(builder.build(), serial, notBefore, notAfter, builder.build(), keyPair.getPublic()); ContentSigner sigGen = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(BC) .build(keyPair.getPrivate()); X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC) .getCertificate(v3CertGen.build(sigGen)); cert.checkValidity(new Date()); cert.verify(cert.getPublicKey()); return Pair.of(cert, keyPair.getPrivate()); }
From source file:org.apache.jmeter.protocol.http.proxy.JMeterProxyControl.java
/** * Initialise the single key JMeter keystore (original behaviour) *//* w w w. j av a 2s . c o m*/ private void initJMeterKeyStore() throws IOException, GeneralSecurityException { if (storePassword != null) { // Assume we have already created the store try { sslKeyStore = getKeyStore(storePassword.toCharArray()); X509Certificate caCert = (X509Certificate) sslKeyStore.getCertificate(JMETER_SERVER_ALIAS); caCert.checkValidity(new Date(System.currentTimeMillis() + DateUtils.MILLIS_PER_DAY)); } catch (Exception e) { // store is faulty, we need to recreate it sslKeyStore = null; // if cert is not valid, flag up to recreate it LOG.warn("Could not open expected file or certificate is not valid " + CERT_PATH_ABS + " " + e.getMessage()); } } if (sslKeyStore == null) { // no existing file or not valid storePassword = RandomStringUtils.randomAlphanumeric(20); // Alphanum to avoid issues with command-line quoting keyPassword = storePassword; // we use same password for both setPassword(storePassword); LOG.info("Generating standard keypair in " + CERT_PATH_ABS); if (!CERT_PATH.delete()) { // safer to start afresh LOG.warn("Could not delete " + CERT_PATH.getAbsolutePath() + ", this could create issues, stop jmeter, ensure file is deleted and restart again"); } KeyToolUtils.genkeypair(CERT_PATH, JMETER_SERVER_ALIAS, storePassword, CERT_VALIDITY, null, null); sslKeyStore = getKeyStore(storePassword.toCharArray()); // This should now work } }
From source file:org.apache.jmeter.protocol.http.proxy.JMeterProxyControl.java
/** * Initialise the user-provided keystore *//*from www . jav a 2s. co m*/ private void initUserKeyStore() { try { sslKeyStore = getKeyStore(storePassword.toCharArray()); X509Certificate caCert = (X509Certificate) sslKeyStore.getCertificate(CERT_ALIAS); if (caCert == null) { LOG.error("Could not find key with alias " + CERT_ALIAS); sslKeyStore = null; } else { caCert.checkValidity(new Date(System.currentTimeMillis() + DateUtils.MILLIS_PER_DAY)); } } catch (Exception e) { sslKeyStore = null; LOG.error( "Could not open keystore or certificate is not valid " + CERT_PATH_ABS + " " + e.getMessage()); } }
From source file:org.apache.jmeter.protocol.http.proxy.JMeterProxyControl.java
/** * Initialise the dynamic domain keystore *///from w w w.java 2 s. c o m private void initDynamicKeyStore() throws IOException, GeneralSecurityException { if (storePassword != null) { // Assume we have already created the store try { sslKeyStore = getKeyStore(storePassword.toCharArray()); for (String alias : KeyToolUtils.getCAaliases()) { X509Certificate caCert = (X509Certificate) sslKeyStore.getCertificate(alias); if (caCert == null) { sslKeyStore = null; // no CA key - probably the wrong store type. break; // cannot continue } else { caCert.checkValidity(new Date(System.currentTimeMillis() + DateUtils.MILLIS_PER_DAY)); LOG.info("Valid alias found for " + alias); } } } catch (IOException e) { // store is faulty, we need to recreate it sslKeyStore = null; // if cert is not valid, flag up to recreate it if (e.getCause() instanceof UnrecoverableKeyException) { LOG.warn( "Could not read key store " + e.getMessage() + "; cause: " + e.getCause().getMessage()); } else { LOG.warn("Could not open/read key store " + e.getMessage()); // message includes the file name } } catch (GeneralSecurityException e) { sslKeyStore = null; // if cert is not valid, flag up to recreate it LOG.warn("Problem reading key store: " + e.getMessage()); } } if (sslKeyStore == null) { // no existing file or not valid storePassword = RandomStringUtils.randomAlphanumeric(20); // Alphanum to avoid issues with command-line quoting keyPassword = storePassword; // we use same password for both setPassword(storePassword); LOG.info("Creating Proxy CA in " + CERT_PATH_ABS); KeyToolUtils.generateProxyCA(CERT_PATH, storePassword, CERT_VALIDITY); LOG.info("Created keystore in " + CERT_PATH_ABS); sslKeyStore = getKeyStore(storePassword.toCharArray()); // This should now work } final String sslDomains = getSslDomains().trim(); if (sslDomains.length() > 0) { final String[] domains = sslDomains.split(","); // The subject may be either a host or a domain for (String subject : domains) { if (isValid(subject)) { if (!sslKeyStore.containsAlias(subject)) { LOG.info("Creating entry " + subject + " in " + CERT_PATH_ABS); KeyToolUtils.generateHostCert(CERT_PATH, storePassword, subject, CERT_VALIDITY); sslKeyStore = getKeyStore(storePassword.toCharArray()); // reload to pick up new aliases // reloading is very quick compared with creating an entry currently } } else { LOG.warn("Attempt to create an invalid domain certificate: " + subject); } } } }
From source file:jproxy.ProxyControl.java
/** * Initialise the single key JMeter keystore (original behaviour) *///from w w w .j a va2 s.c o m private void initJMeterKeyStore() throws IOException, GeneralSecurityException { if (storePassword != null) { // Assume we have already created the store try { keyStore = getKeyStore(storePassword.toCharArray()); X509Certificate caCert = (X509Certificate) keyStore.getCertificate(JMETER_SERVER_ALIAS); caCert.checkValidity(new Date(System.currentTimeMillis() + DateUtils.MILLIS_PER_DAY)); } catch (Exception e) { // store is faulty, we need to recreate it keyStore = null; // if cert is not valid, flag up to recreate it log.warn("Could not open expected file or certificate is not valid " + CERT_PATH_ABS + " " + e.getMessage()); } } if (keyStore == null) { // no existing file or not valid storePassword = RandomStringUtils.randomAlphanumeric(20); // Alphanum to avoid issues with command-line quoting keyPassword = storePassword; // we use same password for both setPassword(storePassword); log.info("Generating standard keypair in " + CERT_PATH_ABS); if (!CERT_PATH.delete()) { // safer to start afresh log.warn("Could not delete " + CERT_PATH.getAbsolutePath() + ", this could create issues, stop jmeter, ensure file is deleted and restart again"); } KeyToolUtils.genkeypair(CERT_PATH, JMETER_SERVER_ALIAS, storePassword, CERT_VALIDITY, null, null); keyStore = getKeyStore(storePassword.toCharArray()); // This should now work } }
From source file:jproxy.ProxyControl.java
/** * Initialise the user-provided keystore *///from w ww. j a v a 2 s .c om private void initUserKeyStore() { try { keyStore = getKeyStore(storePassword.toCharArray()); X509Certificate caCert = (X509Certificate) keyStore.getCertificate(CERT_ALIAS); if (caCert == null) { log.error("Could not find key with alias " + CERT_ALIAS); keyStore = null; } else { caCert.checkValidity(new Date(System.currentTimeMillis() + DateUtils.MILLIS_PER_DAY)); } } catch (Exception e) { keyStore = null; log.error( "Could not open keystore or certificate is not valid " + CERT_PATH_ABS + " " + e.getMessage()); } }
From source file:jproxy.ProxyControl.java
/** * Initialise the dynamic domain keystore *//* w w w. j a va2s. co m*/ private void initDynamicKeyStore() throws IOException, GeneralSecurityException { if (storePassword != null) { // Assume we have already created the store try { keyStore = getKeyStore(storePassword.toCharArray()); for (String alias : KeyToolUtils.getCAaliases()) { X509Certificate caCert = (X509Certificate) keyStore.getCertificate(alias); if (caCert == null) { keyStore = null; // no CA key - probably the wrong store type. break; // cannot continue } else { caCert.checkValidity(new Date(System.currentTimeMillis() + DateUtils.MILLIS_PER_DAY)); log.info("Valid alias found for " + alias); } } } catch (IOException e) { // store is faulty, we need to recreate it keyStore = null; // if cert is not valid, flag up to recreate it if (e.getCause() instanceof UnrecoverableKeyException) { log.warn( "Could not read key store " + e.getMessage() + "; cause: " + e.getCause().getMessage()); } else { log.warn("Could not open/read key store " + e.getMessage()); // message includes the file name } } catch (GeneralSecurityException e) { keyStore = null; // if cert is not valid, flag up to recreate it log.warn("Problem reading key store: " + e.getMessage()); } } if (keyStore == null) { // no existing file or not valid storePassword = RandomStringUtils.randomAlphanumeric(20); // Alphanum to avoid issues with command-line quoting keyPassword = storePassword; // we use same password for both setPassword(storePassword); log.info("Creating Proxy CA in " + CERT_PATH_ABS); KeyToolUtils.generateProxyCA(CERT_PATH, storePassword, CERT_VALIDITY); log.info("Created keystore in " + CERT_PATH_ABS); keyStore = getKeyStore(storePassword.toCharArray()); // This should now work } final String sslDomains = getSslDomains().trim(); if (sslDomains.length() > 0) { final String[] domains = sslDomains.split(","); // The subject may be either a host or a domain for (String subject : domains) { if (isValid(subject)) { if (!keyStore.containsAlias(subject)) { log.info("Creating entry " + subject + " in " + CERT_PATH_ABS); KeyToolUtils.generateHostCert(CERT_PATH, storePassword, subject, CERT_VALIDITY); keyStore = getKeyStore(storePassword.toCharArray()); // reload to pick up new aliases // reloading is very quick compared with creating an entry currently } } else { log.warn("Attempt to create an invalid domain certificate: " + subject); } } } }
From source file:org.ejbca.util.CertTools.java
/** * Checks that the given date is within the certificate's validity period. * In other words, this determines whether the certificate would be valid at the given date/time. * /*w w w .j a v a2s. co m*/ * This utility class is only a helper to get the same behavior as the standard java.security.cert API regardless if using X.509 or CV Certificate. * * @param cert certificate to verify, if null the method returns immediately, null does not have a validity to check. * @param date the Date to check against to see if this certificate is valid at that date/time. * @throws NoSuchFieldException * @throws CertificateExpiredException - if the certificate has expired with respect to the date supplied. * @throws CertificateNotYetValidException - if the certificate is not yet valid with respect to the date supplied. * @see java.security.cert.X509Certificate#checkValidity(Date) */ public static void checkValidity(Certificate cert, Date date) throws CertificateExpiredException, CertificateNotYetValidException { if (cert != null) { if (cert instanceof X509Certificate) { X509Certificate xcert = (X509Certificate) cert; xcert.checkValidity(date); } else if (StringUtils.equals(cert.getType(), "CVC")) { CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cert; try { Date start = cvccert.getCVCertificate().getCertificateBody().getValidFrom(); Date end = cvccert.getCVCertificate().getCertificateBody().getValidTo(); if (start.after(date)) { String msg = "Certificate startDate '" + start + "' is after check date '" + date + "'"; if (log.isTraceEnabled()) { log.trace(msg); } throw new CertificateNotYetValidException(msg); } if (end.before(date)) { String msg = "Certificate endDate '" + end + "' is before check date '" + date + "'"; if (log.isTraceEnabled()) { log.trace(msg); } throw new CertificateExpiredException(msg); } } catch (NoSuchFieldException e) { log.error("NoSuchFieldException: ", e); } } } }
From source file:org.cesecore.util.CertTools.java
/** * Checks that the given date is within the certificate's validity period. In other words, this determines whether the certificate would be valid * at the given date/time./*from w w w.j av a 2 s . c o m*/ * * This utility class is only a helper to get the same behavior as the standard java.security.cert API regardless if using X.509 or CV * Certificate. * * @param cert certificate to verify, if null the method returns immediately, null does not have a validity to check. * @param date the Date to check against to see if this certificate is valid at that date/time. * @throws NoSuchFieldException * @throws CertificateExpiredException - if the certificate has expired with respect to the date supplied. * @throws CertificateNotYetValidException - if the certificate is not yet valid with respect to the date supplied. * @see java.security.cert.X509Certificate#checkValidity(Date) */ public static void checkValidity(final Certificate cert, final Date date) throws CertificateExpiredException, CertificateNotYetValidException { if (cert != null) { if (cert instanceof X509Certificate) { final X509Certificate xcert = (X509Certificate) cert; xcert.checkValidity(date); } else if (StringUtils.equals(cert.getType(), "CVC")) { final CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cert; try { final Date start = cvccert.getCVCertificate().getCertificateBody().getValidFrom(); final Date end = cvccert.getCVCertificate().getCertificateBody().getValidTo(); if (start.after(date)) { String msg = "Certificate startDate '" + start + "' is after check date '" + date + "'"; if (log.isTraceEnabled()) { log.trace(msg); } throw new CertificateNotYetValidException(msg); } if (end.before(date)) { final String msg = "Certificate endDate '" + end + "' is before check date '" + date + "'"; if (log.isTraceEnabled()) { log.trace(msg); } throw new CertificateExpiredException(msg); } } catch (NoSuchFieldException e) { log.error("NoSuchFieldException: ", e); } } } }