List of usage examples for java.security.cert X509Certificate verify
public abstract void verify(PublicKey key) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException;
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./* w ww . jav a2 s . c om*/ * * @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.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/* w w w . java 2 s. co m*/ */ 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.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.//w ww . ja va 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; }
From source file:org.apache.hadoop.security.ssl.TestCRLValidator.java
@Test public void testValidator() throws Exception { Path caTruststore = Paths.get(BASE_DIR, "ca.truststore.jks"); Path crlPath = Paths.get(BASE_DIR, "crl.pem"); // Generate CA keypair KeyPair cakeyPair = KeyStoreTestUtil.generateKeyPair(keyAlgorithm); X509Certificate caCert = KeyStoreTestUtil.generateCertificate("CN=rootCA", cakeyPair, 60, signatureAlgorithm);// w ww .ja va2 s. c o m // Generate CA truststore KeyStoreTestUtil.createTrustStore(caTruststore.toString(), password, "rootca", caCert); // Generate client keypair KeyPair clientKeyPair = KeyStoreTestUtil.generateKeyPair(keyAlgorithm); X509Certificate clientCert = KeyStoreTestUtil.generateSignedCertificate("CN=client", clientKeyPair, 30, signatureAlgorithm, cakeyPair.getPrivate(), caCert); /*X509Certificate clientCert = KeyStoreTestUtil.generateCertificate("CN=client", clientKeyPair, 30, signatureAlgorithm);*/ // Verify client certificate is signed by CA clientCert.verify(cakeyPair.getPublic()); // Generate CRL X509CRL crl = KeyStoreTestUtil.generateCRL(caCert, cakeyPair.getPrivate(), signatureAlgorithm, null, null); writeCRLToFile(crl, crlPath); // Validate should pass conf.set(FileBasedKeyStoresFactory.resolvePropertyName(SSLFactory.Mode.SERVER, FileBasedKeyStoresFactory.SSL_TRUSTSTORE_LOCATION_TPL_KEY), caTruststore.toString()); conf.set(FileBasedKeyStoresFactory.resolvePropertyName(SSLFactory.Mode.SERVER, FileBasedKeyStoresFactory.SSL_TRUSTSTORE_PASSWORD_TPL_KEY), password); conf.set(CommonConfigurationKeys.HOPS_CRL_OUTPUT_FILE_KEY, crlPath.toString()); CRLValidator validator = CRLValidatorFactory.getInstance().getValidator(CRLValidatorFactory.TYPE.TESTING, conf, conf); Certificate[] chain = new Certificate[2]; chain[0] = clientCert; chain[1] = caCert; // At this point the validation should pass validator.validate(chain); // Revoke client certificate and regenerate CRL crl = KeyStoreTestUtil.generateCRL(caCert, cakeyPair.getPrivate(), signatureAlgorithm, crl, clientCert.getSerialNumber()); TimeUnit.SECONDS.sleep(1); writeCRLToFile(crl, crlPath); TimeUnit.SECONDS.sleep(validator.getReloadInterval() * 2); // This time validation should fail rule.expect(CertificateException.class); validator.validate(chain); }
From source file:org.apache.nifi.toolkit.tls.standalone.TlsToolkitStandalone.java
public void createNifiKeystoresAndTrustStores(StandaloneConfig standaloneConfig) throws GeneralSecurityException, IOException { File baseDir = standaloneConfig.getBaseDir(); if (!baseDir.exists() && !baseDir.mkdirs()) { throw new IOException(baseDir + " doesn't exist and unable to create it."); }/*ww w. j a va 2 s . c om*/ if (!baseDir.isDirectory()) { throw new IOException("Expected directory to output to"); } String signingAlgorithm = standaloneConfig.getSigningAlgorithm(); int days = standaloneConfig.getDays(); String keyPairAlgorithm = standaloneConfig.getKeyPairAlgorithm(); int keySize = standaloneConfig.getKeySize(); File nifiCert = new File(baseDir, NIFI_CERT + ".pem"); File nifiKey = new File(baseDir, NIFI_KEY + ".key"); X509Certificate certificate; KeyPair caKeyPair; if (logger.isInfoEnabled()) { logger.info("Running standalone certificate generation with output directory " + baseDir); } if (nifiCert.exists()) { if (!nifiKey.exists()) { throw new IOException(nifiCert + " exists already, but " + nifiKey + " does not, we need both certificate and key to continue with an existing CA."); } try (FileReader pemEncodedCertificate = new FileReader(nifiCert)) { certificate = TlsHelper.parseCertificate(pemEncodedCertificate); } try (FileReader pemEncodedKeyPair = new FileReader(nifiKey)) { caKeyPair = TlsHelper.parseKeyPair(pemEncodedKeyPair); } certificate.verify(caKeyPair.getPublic()); if (!caKeyPair.getPublic().equals(certificate.getPublicKey())) { throw new IOException("Expected " + nifiKey + " to correspond to CA certificate at " + nifiCert); } if (logger.isInfoEnabled()) { logger.info("Using existing CA certificate " + nifiCert + " and key " + nifiKey); } } else if (nifiKey.exists()) { throw new IOException(nifiKey + " exists already, but " + nifiCert + " does not, we need both certificate and key to continue with an existing CA."); } else { TlsCertificateAuthorityManager tlsCertificateAuthorityManager = new TlsCertificateAuthorityManager( standaloneConfig); KeyStore.PrivateKeyEntry privateKeyEntry = tlsCertificateAuthorityManager .getOrGenerateCertificateAuthority(); certificate = (X509Certificate) privateKeyEntry.getCertificateChain()[0]; caKeyPair = new KeyPair(certificate.getPublicKey(), privateKeyEntry.getPrivateKey()); try (PemWriter pemWriter = new PemWriter( new OutputStreamWriter(outputStreamFactory.create(nifiCert)))) { pemWriter.writeObject(new JcaMiscPEMGenerator(certificate)); } try (PemWriter pemWriter = new PemWriter(new OutputStreamWriter(outputStreamFactory.create(nifiKey)))) { pemWriter.writeObject(new JcaMiscPEMGenerator(caKeyPair)); } if (logger.isInfoEnabled()) { logger.info("Generated new CA certificate " + nifiCert + " and key " + nifiKey); } } NiFiPropertiesWriterFactory niFiPropertiesWriterFactory = standaloneConfig.getNiFiPropertiesWriterFactory(); boolean overwrite = standaloneConfig.isOverwrite(); List<InstanceDefinition> instanceDefinitions = standaloneConfig.getInstanceDefinitions(); if (instanceDefinitions.isEmpty() && logger.isInfoEnabled()) { logger.info("No " + TlsToolkitStandaloneCommandLine.HOSTNAMES_ARG + " specified, not generating any host certificates or configuration."); } for (InstanceDefinition instanceDefinition : instanceDefinitions) { String hostname = instanceDefinition.getHostname(); File hostDir; int hostIdentifierNumber = instanceDefinition.getInstanceIdentifier().getNumber(); if (hostIdentifierNumber == 1) { hostDir = new File(baseDir, hostname); } else { hostDir = new File(baseDir, hostname + "_" + hostIdentifierNumber); } TlsClientConfig tlsClientConfig = new TlsClientConfig(standaloneConfig); File keystore = new File(hostDir, "keystore." + tlsClientConfig.getKeyStoreType().toLowerCase()); File truststore = new File(hostDir, "truststore." + tlsClientConfig.getTrustStoreType().toLowerCase()); if (hostDir.exists()) { if (!hostDir.isDirectory()) { throw new IOException(hostDir + " exists but is not a directory."); } else if (overwrite) { if (logger.isInfoEnabled()) { logger.info("Overwriting any existing ssl configuration in " + hostDir); } keystore.delete(); if (keystore.exists()) { throw new IOException("Keystore " + keystore + " already exists and couldn't be deleted."); } truststore.delete(); if (truststore.exists()) { throw new IOException( "Truststore " + truststore + " already exists and couldn't be deleted."); } } else { throw new IOException(hostDir + " exists and overwrite is not set."); } } else if (!hostDir.mkdirs()) { throw new IOException("Unable to make directory: " + hostDir.getAbsolutePath()); } else if (logger.isInfoEnabled()) { logger.info("Writing new ssl configuration to " + hostDir); } tlsClientConfig.setKeyStore(keystore.getAbsolutePath()); tlsClientConfig.setKeyStorePassword(instanceDefinition.getKeyStorePassword()); tlsClientConfig.setKeyPassword(instanceDefinition.getKeyPassword()); tlsClientConfig.setTrustStore(truststore.getAbsolutePath()); tlsClientConfig.setTrustStorePassword(instanceDefinition.getTrustStorePassword()); TlsClientManager tlsClientManager = new TlsClientManager(tlsClientConfig); KeyPair keyPair = TlsHelper.generateKeyPair(keyPairAlgorithm, keySize); Extensions sanDnsExtensions = StringUtils.isBlank(tlsClientConfig.getDomainAlternativeNames()) ? null : TlsHelper.createDomainAlternativeNamesExtensions(tlsClientConfig.getDomainAlternativeNames()); tlsClientManager.addPrivateKeyToKeyStore(keyPair, NIFI_KEY, CertificateUtils.generateIssuedCertificate(tlsClientConfig.calcDefaultDn(hostname), keyPair.getPublic(), sanDnsExtensions, certificate, caKeyPair, signingAlgorithm, days), certificate); tlsClientManager.setCertificateEntry(NIFI_CERT, certificate); tlsClientManager.addClientConfigurationWriter( new NifiPropertiesTlsClientConfigWriter(niFiPropertiesWriterFactory, new File(hostDir, "nifi.properties"), hostname, instanceDefinition.getNumber())); tlsClientManager.write(outputStreamFactory); if (logger.isInfoEnabled()) { logger.info("Successfully generated TLS configuration for " + hostname + " " + hostIdentifierNumber + " in " + hostDir); } } List<String> clientDns = standaloneConfig.getClientDns(); if (standaloneConfig.getClientDns().isEmpty() && logger.isInfoEnabled()) { logger.info("No " + TlsToolkitStandaloneCommandLine.CLIENT_CERT_DN_ARG + " specified, not generating any client certificates."); } List<String> clientPasswords = standaloneConfig.getClientPasswords(); for (int i = 0; i < clientDns.size(); i++) { String reorderedDn = CertificateUtils.reorderDn(clientDns.get(i)); String clientDnFile = getClientDnFile(reorderedDn); File clientCertFile = new File(baseDir, clientDnFile + ".p12"); if (clientCertFile.exists()) { if (overwrite) { if (logger.isInfoEnabled()) { logger.info("Overwriting existing client cert " + clientCertFile); } } else { throw new IOException(clientCertFile + " exists and overwrite is not set."); } } else if (logger.isInfoEnabled()) { logger.info("Generating new client certificate " + clientCertFile); } KeyPair keyPair = TlsHelper.generateKeyPair(keyPairAlgorithm, keySize); X509Certificate clientCert = CertificateUtils.generateIssuedCertificate(reorderedDn, keyPair.getPublic(), null, certificate, caKeyPair, signingAlgorithm, days); KeyStore keyStore = KeyStoreUtils.getKeyStore(KeystoreType.PKCS12.toString()); keyStore.load(null, null); keyStore.setKeyEntry(NIFI_KEY, keyPair.getPrivate(), null, new Certificate[] { clientCert, certificate }); String password = TlsHelper.writeKeyStore(keyStore, outputStreamFactory, clientCertFile, clientPasswords.get(i), standaloneConfig.isClientPasswordsGenerated()); try (FileWriter fileWriter = new FileWriter(new File(baseDir, clientDnFile + ".password"))) { fileWriter.write(password); } if (logger.isInfoEnabled()) { logger.info("Successfully generated client certificate " + clientCertFile); } } if (logger.isInfoEnabled()) { logger.info("tls-toolkit standalone completed successfully"); } }
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:org.cesecore.certificates.ca.internal.CaCertificateCacheTest.java
@Test public void test01CACertificates() throws Exception { // Prepare the certificate cache with some test certificates Collection<Certificate> certs = new ArrayList<Certificate>(); X509Certificate testrootcert = CertTools.getCertfromByteArray(testroot, X509Certificate.class); certs.add(testrootcert);/* w ww. j ava 2 s.co m*/ X509Certificate testrootnewcert = CertTools.getCertfromByteArray(testrootnew, X509Certificate.class); certs.add(testrootnewcert); X509Certificate testsubcert = CertTools.getCertfromByteArray(testsub, X509Certificate.class); certs.add(testsubcert); Certificate testcvccert = CertTools.getCertfromByteArray(testcvc, Certificate.class); certs.add(testcvccert); X509Certificate testscepcert = CertTools.getCertfromByteArray(testscepca, X509Certificate.class); certs.add(testscepcert); CaCertificateCache cache = CaCertificateCache.INSTANCE; cache.loadCertificates(certs); // Test lookup of not existing cert X509Certificate cert = cache.findLatestBySubjectDN(HashID.getFromDNString("CN=Foo,C=SE")); assertNull(cert); // Old root cert should not be found, we only store the latest to be found by subjectDN X509Certificate rootcert = cache.findLatestBySubjectDN(HashID.getFromSubjectDN(testrootnewcert)); assertNotNull(rootcert); X509Certificate subcert = cache.findLatestBySubjectDN(HashID.getFromSubjectDN(testsubcert)); // This old subcert should not be possible to verify with the new root cert try { subcert.verify(rootcert.getPublicKey()); fail("verification should have failed"); } catch (SignatureException e) { } // NOPMD: BC 1.47 // CVC certificate should not be part of OCSP certificate cache cert = cache.findLatestBySubjectDN(HashID.getFromDNString(CertTools.getSubjectDN(testcvccert))); assertNull(cert); cert = cache.findLatestBySubjectDN(HashID.getFromSubjectDN(testscepcert)); assertEquals(CertTools.getSubjectDN(testscepcert), CertTools.getSubjectDN(cert)); }
From source file:org.cesecore.certificates.ca.X509CA.java
/** * Sequence is ignored by X509CA. The ctParams argument will NOT be kept after the function call returns, * and is allowed to contain references to session beans. * /*from www . ja va 2 s . co m*/ * @throws CAOfflineException if the CA wasn't active * @throws InvalidAlgorithmException if the signing algorithm in the certificate profile (or the CA Token if not found) was invalid. * @throws IllegalValidityException if validity was invalid * @throws IllegalNameException if the name specified in the certificate request was invalid * @throws CertificateExtensionException if any of the certificate extensions were invalid * @throws OperatorCreationException if CA's private key contained an unknown algorithm or provider * @throws CertificateCreateException if an error occurred when trying to create a certificate. * @throws SignatureException if the CA's certificate's and request's certificate's and signature algorithms differ */ private Certificate generateCertificate(final EndEntityInformation subject, final RequestMessage request, final PublicKey publicKey, final int keyusage, final Date notBefore, final Date notAfter, final CertificateProfile certProfile, final Extensions extensions, final String sequence, final PublicKey caPublicKey, final PrivateKey caPrivateKey, final String provider, CertificateGenerationParams certGenParams) throws CAOfflineException, InvalidAlgorithmException, IllegalValidityException, IllegalNameException, CertificateExtensionException, OperatorCreationException, CertificateCreateException, SignatureException { // We must only allow signing to take place if the CA itself is on line, even if the token is on-line. // We have to allow expired as well though, so we can renew expired CAs if ((getStatus() != CAConstants.CA_ACTIVE) && ((getStatus() != CAConstants.CA_EXPIRED))) { final String msg = intres.getLocalizedMessage("error.caoffline", getName(), getStatus()); if (log.isDebugEnabled()) { log.debug(msg); // This is something we handle so no need to log with higher priority } throw new CAOfflineException(msg); } final String sigAlg; if (certProfile.getSignatureAlgorithm() == null) { sigAlg = getCAToken().getSignatureAlgorithm(); } else { sigAlg = certProfile.getSignatureAlgorithm(); } // Check that the signature algorithm is one of the allowed ones if (!ArrayUtils.contains(AlgorithmConstants.AVAILABLE_SIGALGS, sigAlg)) { final String msg = intres.getLocalizedMessage("createcert.invalidsignaturealg", sigAlg); throw new InvalidAlgorithmException(msg); } // Check if this is a root CA we are creating final boolean isRootCA = certProfile.getType() == CertificateConstants.CERTTYPE_ROOTCA; final X509Certificate cacert = (X509Certificate) getCACertificate(); // Check CA certificate PrivateKeyUsagePeriod if it exists (throws CAOfflineException if it exists and is not within this time) CertificateValidity.checkPrivateKeyUsagePeriod(cacert); // Get certificate validity time notBefore and notAfter final CertificateValidity val = new CertificateValidity(subject, certProfile, notBefore, notAfter, cacert, isRootCA); final BigInteger serno; { // Serialnumber is either random bits, where random generator is initialized by the serno generator. // Or a custom serial number defined in the end entity object final ExtendedInformation ei = subject.getExtendedinformation(); if (certProfile.getAllowCertSerialNumberOverride()) { if (ei != null && ei.certificateSerialNumber() != null) { serno = ei.certificateSerialNumber(); } else { serno = SernoGeneratorRandom.instance().getSerno(); } } else { serno = SernoGeneratorRandom.instance().getSerno(); if ((ei != null) && (ei.certificateSerialNumber() != null)) { final String msg = intres.getLocalizedMessage( "createcert.certprof_not_allowing_cert_sn_override_using_normal", ei.certificateSerialNumber().toString(16)); log.info(msg); } } } // Make DNs String dn = subject.getCertificateDN(); if (certProfile.getUseSubjectDNSubSet()) { dn = certProfile.createSubjectDNSubSet(dn); } final X500NameStyle nameStyle; if (getUsePrintableStringSubjectDN()) { nameStyle = PrintableStringNameStyle.INSTANCE; } else { nameStyle = CeSecoreNameStyle.INSTANCE; } if (certProfile.getUseCNPostfix()) { dn = CertTools.insertCNPostfix(dn, certProfile.getCNPostfix(), nameStyle); } // Will we use LDAP DN order (CN first) or X500 DN order (CN last) for the subject DN final boolean ldapdnorder; if ((getUseLdapDNOrder() == false) || (certProfile.getUseLdapDnOrder() == false)) { ldapdnorder = false; } else { ldapdnorder = true; } final X500Name subjectDNName; if (certProfile.getAllowDNOverride() && (request != null) && (request.getRequestX500Name() != null)) { subjectDNName = request.getRequestX500Name(); if (log.isDebugEnabled()) { log.debug("Using X509Name from request instead of user's registered."); } } else { final ExtendedInformation ei = subject.getExtendedinformation(); if (certProfile.getAllowDNOverrideByEndEntityInformation() && ei != null && ei.getRawSubjectDn() != null) { final String stripped = StringTools.strip(ei.getRawSubjectDn()); final String escapedPluses = CertTools.handleUnescapedPlus(stripped); final String emptiesRemoved = DNFieldsUtil.removeAllEmpties(escapedPluses); final X500Name subjectDNNameFromEei = CertTools.stringToUnorderedX500Name(emptiesRemoved, CeSecoreNameStyle.INSTANCE); if (subjectDNNameFromEei.toString().length() > 0) { subjectDNName = subjectDNNameFromEei; if (log.isDebugEnabled()) { log.debug( "Using X500Name from end entity information instead of user's registered subject DN fields."); log.debug("ExtendedInformation.getRawSubjectDn(): " + ei.getRawSubjectDn() + " will use: " + CeSecoreNameStyle.INSTANCE.toString(subjectDNName)); } } else { subjectDNName = CertTools.stringToBcX500Name(dn, nameStyle, ldapdnorder); } } else { subjectDNName = CertTools.stringToBcX500Name(dn, nameStyle, ldapdnorder); } } // Make sure the DN does not contain dangerous characters if (StringTools.hasStripChars(subjectDNName.toString())) { if (log.isTraceEnabled()) { log.trace("DN with illegal name: " + subjectDNName); } final String msg = intres.getLocalizedMessage("createcert.illegalname"); throw new IllegalNameException(msg); } if (log.isDebugEnabled()) { log.debug("Using subjectDN: " + subjectDNName.toString()); } // We must take the issuer DN directly from the CA-certificate otherwise we risk re-ordering the DN // which many applications do not like. X500Name issuerDNName; if (isRootCA) { // This will be an initial root CA, since no CA-certificate exists // Or it is a root CA, since the cert is self signed. If it is a root CA we want to use the same encoding for subject and issuer, // it might have changed over the years. if (log.isDebugEnabled()) { log.debug("Using subject DN also as issuer DN, because it is a root CA"); } issuerDNName = subjectDNName; } else { issuerDNName = X500Name.getInstance(cacert.getSubjectX500Principal().getEncoded()); if (log.isDebugEnabled()) { log.debug("Using issuer DN directly from the CA certificate: " + issuerDNName.toString()); } } SubjectPublicKeyInfo pkinfo; try { pkinfo = new SubjectPublicKeyInfo((ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded())); } catch (IOException e) { throw new IllegalStateException("Caught unexpected IOException.", e); } final X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(issuerDNName, serno, val.getNotBefore(), val.getNotAfter(), subjectDNName, pkinfo); // Only created and used if Certificate Transparency is enabled final X509v3CertificateBuilder precertbuilder = certProfile.isUseCertificateTransparencyInCerts() ? new X509v3CertificateBuilder(issuerDNName, serno, val.getNotBefore(), val.getNotAfter(), subjectDNName, pkinfo) : null; // Check that the certificate fulfills name constraints if (cacert instanceof X509Certificate) { GeneralNames altNameGNs = null; String altName = subject.getSubjectAltName(); if (certProfile.getUseSubjectAltNameSubSet()) { altName = certProfile.createSubjectAltNameSubSet(altName); } if (altName != null && altName.length() > 0) { altNameGNs = CertTools.getGeneralNamesFromAltName(altName); } CertTools.checkNameConstraints((X509Certificate) cacert, subjectDNName, altNameGNs); } // If the subject has Name Constraints, then name constraints must be enabled in the certificate profile! if (subject.getExtendedinformation() != null) { final ExtendedInformation ei = subject.getExtendedinformation(); final List<String> permittedNC = ei.getNameConstraintsPermitted(); final List<String> excludedNC = ei.getNameConstraintsExcluded(); if ((permittedNC != null && !permittedNC.isEmpty()) || (excludedNC != null && !excludedNC.isEmpty())) { if (!certProfile.getUseNameConstraints()) { throw new CertificateCreateException( "Tried to issue a certificate with Name Constraints without having enabled NC in the certificate profile."); } } } // // X509 Certificate Extensions // // Extensions we will add to the certificate, later when we have filled the structure with // everything we want. final ExtensionsGenerator extgen = new ExtensionsGenerator(); // First we check if there is general extension override, and add all extensions from // the request in that case if (certProfile.getAllowExtensionOverride() && extensions != null) { ASN1ObjectIdentifier[] oids = extensions.getExtensionOIDs(); for (ASN1ObjectIdentifier oid : oids) { final Extension ext = extensions.getExtension(oid); if (log.isDebugEnabled()) { log.debug("Overriding extension with oid: " + oid); } try { extgen.addExtension(oid, ext.isCritical(), ext.getParsedValue()); } catch (IOException e) { throw new IllegalStateException("Caught unexpected IOException.", e); } } } // Second we see if there is Key usage override Extensions overridenexts = extgen.generate(); if (certProfile.getAllowKeyUsageOverride() && (keyusage >= 0)) { if (log.isDebugEnabled()) { log.debug("AllowKeyUsageOverride=true. Using KeyUsage from parameter: " + keyusage); } if ((certProfile.getUseKeyUsage() == true) && (keyusage >= 0)) { final KeyUsage ku = new KeyUsage(keyusage); // We don't want to try to add custom extensions with the same oid if we have already added them // from the request, if AllowExtensionOverride is enabled. // Two extensions with the same oid is not allowed in the standard. if (overridenexts.getExtension(Extension.keyUsage) == null) { try { extgen.addExtension(Extension.keyUsage, certProfile.getKeyUsageCritical(), ku); } catch (IOException e) { throw new IllegalStateException("Caught unexpected IOException.", e); } } else { if (log.isDebugEnabled()) { log.debug( "KeyUsage was already overridden by an extension, not using KeyUsage from parameter."); } } } } // Third, check for standard Certificate Extensions that should be added. // Standard certificate extensions are defined in CertificateProfile and CertificateExtensionFactory // and implemented in package org.ejbca.core.model.certextensions.standard final CertificateExtensionFactory fact = CertificateExtensionFactory.getInstance(); final List<String> usedStdCertExt = certProfile.getUsedStandardCertificateExtensions(); final Iterator<String> certStdExtIter = usedStdCertExt.iterator(); overridenexts = extgen.generate(); while (certStdExtIter.hasNext()) { final String oid = certStdExtIter.next(); // We don't want to try to add standard extensions with the same oid if we have already added them // from the request, if AllowExtensionOverride is enabled. // Two extensions with the same oid is not allowed in the standard. if (overridenexts.getExtension(new ASN1ObjectIdentifier(oid)) == null) { final CertificateExtension certExt = fact.getStandardCertificateExtension(oid, certProfile); if (certExt != null) { final byte[] value = certExt.getValueEncoded(subject, this, certProfile, publicKey, caPublicKey, val); if (value != null) { extgen.addExtension(new ASN1ObjectIdentifier(certExt.getOID()), certExt.isCriticalFlag(), value); } } } else { if (log.isDebugEnabled()) { log.debug("Extension with oid " + oid + " has been overridden, standard extension will not be added."); } } } // Fourth, check for custom Certificate Extensions that should be added. // Custom certificate extensions is defined in certextensions.properties final List<Integer> usedCertExt = certProfile.getUsedCertificateExtensions(); final Iterator<Integer> certExtIter = usedCertExt.iterator(); while (certExtIter.hasNext()) { final Integer id = certExtIter.next(); final CertificateExtension certExt = fact.getCertificateExtensions(id); if (certExt != null) { // We don't want to try to add custom extensions with the same oid if we have already added them // from the request, if AllowExtensionOverride is enabled. // Two extensions with the same oid is not allowed in the standard. if (overridenexts.getExtension(new ASN1ObjectIdentifier(certExt.getOID())) == null) { final byte[] value = certExt.getValueEncoded(subject, this, certProfile, publicKey, caPublicKey, val); if (value != null) { extgen.addExtension(new ASN1ObjectIdentifier(certExt.getOID()), certExt.isCriticalFlag(), value); } } else { if (log.isDebugEnabled()) { log.debug("Extension with oid " + certExt.getOID() + " has been overridden, custom extension will not be added."); } } } } // Finally add extensions to certificate generator final Extensions exts = extgen.generate(); ASN1ObjectIdentifier[] oids = exts.getExtensionOIDs(); try { for (ASN1ObjectIdentifier oid : oids) { final Extension extension = exts.getExtension(oid); if (oid.equals(Extension.subjectAlternativeName)) { // subjectAlternativeName extension value needs special handling ExtensionsGenerator sanExtGen = getSubjectAltNameExtensionForCert(extension, precertbuilder != null); Extensions sanExts = sanExtGen.generate(); Extension eext = sanExts.getExtension(oid); certbuilder.addExtension(oid, eext.isCritical(), eext.getParsedValue()); // adding subjetAlternativeName extension to certbuilder if (precertbuilder != null) { // if a pre-certificate is to be published to a CTLog eext = getSubjectAltNameExtensionForCTCert(extension).generate().getExtension(oid); precertbuilder.addExtension(oid, eext.isCritical(), eext.getParsedValue()); // adding subjectAlternativeName extension to precertbuilder eext = sanExts.getExtension(new ASN1ObjectIdentifier("1.3.6.1.4.1.11129.2.4.6")); if (eext != null) { certbuilder.addExtension(eext.getExtnId(), eext.isCritical(), eext.getParsedValue()); // adding nrOfRedactedLabels extension to certbuilder } } } else { // if not a subjectAlternativeName extension, just add it to both certbuilder and precertbuilder final boolean isCritical = extension.isCritical(); // We must get the raw octets here in order to be able to create invalid extensions that is not constructed from proper ASN.1 final byte[] value = extension.getExtnValue().getOctets(); certbuilder.addExtension(extension.getExtnId(), isCritical, value); if (precertbuilder != null) { precertbuilder.addExtension(extension.getExtnId(), isCritical, value); } } } // Add Certificate Transparency extension. It needs to access the certbuilder and // the CA key so it has to be processed here inside X509CA. if (ct != null && certProfile.isUseCertificateTransparencyInCerts() && certGenParams.getConfiguredCTLogs() != null && certGenParams.getCTAuditLogCallback() != null) { // Create pre-certificate // A critical extension is added to prevent this cert from being used ct.addPreCertPoison(precertbuilder); // Sign pre-certificate /* * TODO: Should be able to use a special CT signing certificate. * It should have CA=true and ExtKeyUsage=PRECERTIFICATE_SIGNING_OID, * and should not have any other key usages. */ final ContentSigner signer = new BufferingContentSigner( new JcaContentSignerBuilder(sigAlg).setProvider(provider).build(caPrivateKey), 20480); final X509CertificateHolder certHolder = precertbuilder.build(signer); final X509Certificate cert = (X509Certificate) CertTools .getCertfromByteArray(certHolder.getEncoded()); // Get certificate chain final List<Certificate> chain = new ArrayList<Certificate>(); chain.add(cert); chain.addAll(getCertificateChain()); // Submit to logs and get signed timestamps byte[] sctlist = null; try { sctlist = ct.fetchSCTList(chain, certProfile, certGenParams.getConfiguredCTLogs()); } finally { // Notify that pre-cert has been successfully or unsuccessfully submitted so it can be audit logged. certGenParams.getCTAuditLogCallback().logPreCertSubmission(this, subject, cert, sctlist != null); } if (sctlist != null) { // can be null if the CTLog has been deleted from the configuration ASN1ObjectIdentifier sctOid = new ASN1ObjectIdentifier(CertificateTransparency.SCTLIST_OID); certbuilder.addExtension(sctOid, false, new DEROctetString(sctlist)); } } else { if (log.isDebugEnabled()) { String cause = ""; if (ct == null) { cause += "CT is not available in this version of EJBCA."; } else { if (!certProfile.isUseCertificateTransparencyInCerts()) { cause += "CT is not enabled in the certificate profile. "; } if (certGenParams == null) { cause += "Certificate generation parameters was null."; } else if (certGenParams.getCTAuditLogCallback() == null) { cause += "No CT audit logging callback was passed to X509CA."; } else if (certGenParams.getConfiguredCTLogs() == null) { cause += "There are no CT logs configured in System Configuration."; } } log.debug("Not logging to CT. " + cause); } } } catch (CertificateException e) { throw new CertificateCreateException( "Could not process CA's private key when parsing Certificate Transparency extension.", e); } catch (IOException e) { throw new CertificateCreateException( "IOException was caught when parsing Certificate Transparency extension.", e); } catch (CTLogException e) { throw new CertificateCreateException( "An exception occurred because too many CT servers were down to satisfy the certificate profile.", e); } // // End of extensions // if (log.isTraceEnabled()) { log.trace(">certgen.generate"); } final ContentSigner signer = new BufferingContentSigner( new JcaContentSignerBuilder(sigAlg).setProvider(provider).build(caPrivateKey), 20480); final X509CertificateHolder certHolder = certbuilder.build(signer); X509Certificate cert; try { cert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded()); } catch (IOException e) { throw new IllegalStateException("Unexpected IOException caught when parsing certificate holder.", e); } catch (CertificateException e) { throw new CertificateCreateException("Could not create certificate from CA's private key,", e); } if (log.isTraceEnabled()) { log.trace("<certgen.generate"); } // Verify using the CA certificate before returning // If we can not verify the issued certificate using the CA certificate we don't want to issue this cert // because something is wrong... final PublicKey verifyKey; // We must use the configured public key if this is a rootCA, because then we can renew our own certificate, after changing // the keys. In this case the _new_ key will not match the current CA certificate. if ((cacert != null) && (!isRootCA)) { verifyKey = cacert.getPublicKey(); } else { verifyKey = caPublicKey; } try { cert.verify(verifyKey); } catch (InvalidKeyException e) { throw new CertificateCreateException("CA's public key was invalid,", e); } catch (NoSuchAlgorithmException e) { throw new CertificateCreateException(e); } catch (NoSuchProviderException e) { throw new IllegalStateException("Provider was unknown", e); } catch (CertificateException e) { throw new CertificateCreateException(e); } // If we have a CA-certificate, verify that we have all path verification stuff correct if (cacert != null) { final byte[] aki = CertTools.getAuthorityKeyId(cert); final byte[] ski = CertTools.getSubjectKeyId(isRootCA ? cert : cacert); if ((aki != null) && (ski != null)) { final boolean eq = Arrays.equals(aki, ski); if (!eq) { final String akistr = new String(Hex.encode(aki)); final String skistr = new String(Hex.encode(ski)); final String msg = intres.getLocalizedMessage("createcert.errorpathverifykeyid", akistr, skistr); log.error(msg); // This will differ if we create link certificates, NewWithOld, therefore we can not throw an exception here. } } final Principal issuerDN = cert.getIssuerX500Principal(); final Principal caSubjectDN = cacert.getSubjectX500Principal(); if ((issuerDN != null) && (caSubjectDN != null)) { final boolean eq = issuerDN.equals(caSubjectDN); if (!eq) { final String msg = intres.getLocalizedMessage("createcert.errorpathverifydn", issuerDN.getName(), caSubjectDN.getName()); log.error(msg); throw new CertificateCreateException(msg); } } } // Before returning from this method, we will set the private key and provider in the request message, in case the response message needs to be signed if (request != null) { request.setResponseKeyInfo(caPrivateKey, provider); } if (log.isDebugEnabled()) { log.debug("X509CA: generated certificate, CA " + this.getCAId() + " for DN: " + subject.getCertificateDN()); } return cert; }
From source file:org.cesecore.certificates.ocsp.OcspResponseGeneratorSessionBean.java
/** * Checks the signature on an OCSP request. Does not check for revocation of the signer certificate * // w w w.j a va 2 s . co m * @param clientRemoteAddr The IP address or host name of the remote client that sent the request, can be null. * @param req The signed OCSPReq * @return X509Certificate which is the certificate that signed the OCSP request * @throws SignRequestSignatureException if signature verification fail, or if the signing certificate is not authorized * @throws SignRequestException if there is no signature on the OCSPReq * @throws OCSPException if the request can not be parsed to retrieve certificates * @throws NoSuchProviderException if the BC provider is not installed * @throws CertificateException if the certificate can not be parsed * @throws NoSuchAlgorithmException if the certificate contains an unsupported algorithm * @throws InvalidKeyException if the certificate, or CA key is invalid */ private X509Certificate checkRequestSignature(String clientRemoteAddr, OCSPReq req) throws SignRequestException, SignRequestSignatureException, CertificateException, NoSuchAlgorithmException { X509Certificate signercert = null; // Get all certificates embedded in the request (probably a certificate chain) try { final X509CertificateHolder[] certs = req.getCerts(); String signerSubjectDn = null; // We must find a certificate to verify the signature with... boolean verifyOK = false; for (int i = 0; i < certs.length; i++) { final X509Certificate certificate = certificateConverter.getCertificate(certs[i]); try { if (req.isSignatureValid( new JcaContentVerifierProviderBuilder().build(certificate.getPublicKey()))) { signercert = certificate; // if the request signature verifies by this certificate, this is the signer cert signerSubjectDn = CertTools.getSubjectDN(signercert); log.info(intres.getLocalizedMessage("ocsp.infosigner", signerSubjectDn)); verifyOK = true; // Check that the signer certificate can be verified by one of the CA-certificates that we answer for final X509Certificate signerca = CaCertificateCache.INSTANCE .findLatestBySubjectDN(HashID.getFromIssuerDN(signercert)); if (signerca != null) { try { signercert.verify(signerca.getPublicKey()); final Date now = new Date(); if (log.isDebugEnabled()) { log.debug("Checking validity. Now: " + now + ", signerNotAfter: " + signercert.getNotAfter()); } try { // Check validity of the request signing certificate CertTools.checkValidity(signercert, now); } catch (CertificateNotYetValidException e) { log.info(intres.getLocalizedMessage("ocsp.infosigner.certnotyetvalid", signerSubjectDn, CertTools.getIssuerDN(signercert), e.getMessage())); verifyOK = false; } catch (CertificateExpiredException e) { log.info(intres.getLocalizedMessage("ocsp.infosigner.certexpired", signerSubjectDn, CertTools.getIssuerDN(signercert), e.getMessage())); verifyOK = false; } try { // Check validity of the CA certificate CertTools.checkValidity(signerca, now); } catch (CertificateNotYetValidException e) { log.info(intres.getLocalizedMessage("ocsp.infosigner.certnotyetvalid", CertTools.getSubjectDN(signerca), CertTools.getIssuerDN(signerca), e.getMessage())); verifyOK = false; } catch (CertificateExpiredException e) { log.info(intres.getLocalizedMessage("ocsp.infosigner.certexpired", CertTools.getSubjectDN(signerca), CertTools.getIssuerDN(signerca), e.getMessage())); verifyOK = false; } } catch (SignatureException e) { log.info(intres.getLocalizedMessage("ocsp.infosigner.invalidcertsignature", signerSubjectDn, CertTools.getIssuerDN(signercert), e.getMessage())); verifyOK = false; } catch (InvalidKeyException e) { log.info(intres.getLocalizedMessage("ocsp.infosigner.invalidcertsignature", signerSubjectDn, CertTools.getIssuerDN(signercert), e.getMessage())); verifyOK = false; } } else { log.info(intres.getLocalizedMessage("ocsp.infosigner.nocacert", signerSubjectDn, CertTools.getIssuerDN(signercert))); verifyOK = false; } break; } } catch (OperatorCreationException e) { // Very fatal error throw new EJBException("Can not create Jca content signer: ", e); } } if (!verifyOK) { if (signerSubjectDn == null && certs.length > 0) { signerSubjectDn = CertTools.getSubjectDN(certificateConverter.getCertificate(certs[0])); } String errMsg = intres.getLocalizedMessage("ocsp.errorinvalidsignature", signerSubjectDn); log.info(errMsg); throw new SignRequestSignatureException(errMsg); } } catch (OCSPException e) { throw new CryptoProviderException("BouncyCastle was not initialized properly.", e); } catch (NoSuchProviderException e) { throw new CryptoProviderException("BouncyCastle was not found as a provider.", e); } return signercert; }
From source file:org.cesecore.certificates.ocsp.CanLogCache.java
/** * Checks the signature on an OCSP request and checks that it is signed by an allowed CA. Does not check for revocation of the signer certificate * /*from www . ja va 2s . c o m*/ * @param clientRemoteAddr The IP address or host name of the remote client that sent the request, can be null. * @param req The signed OCSPReq * @return X509Certificate which is the certificate that signed the OCSP request * @throws SignRequestSignatureException if signature verification fail, or if the signing certificate is not authorized * @throws SignRequestException if there is no signature on the OCSPReq * @throws OCSPException if the request can not be parsed to retrieve certificates * @throws NoSuchProviderException if the BC provider is not installed * @throws CertificateException if the certificate can not be parsed * @throws NoSuchAlgorithmException if the certificate contains an unsupported algorithm * @throws InvalidKeyException if the certificate, or CA key is invalid */ private X509Certificate checkRequestSignature(String clientRemoteAddr, OCSPReq req) throws SignRequestException, SignRequestSignatureException, CertificateException, NoSuchAlgorithmException { X509Certificate signercert = null; if (!req.isSigned()) { String infoMsg = intres.getLocalizedMessage("ocsp.errorunsignedreq", clientRemoteAddr); log.info(infoMsg); throw new SignRequestException(infoMsg); } // Get all certificates embedded in the request (probably a certificate chain) try { X509Certificate[] certs = req.getCerts("BC"); // Set, as a try, the signer to be the first certificate, so we have a name to log... String signer = null; if (certs.length > 0) { signer = CertTools.getSubjectDN(certs[0]); } // We must find a certificate to verify the signature with... boolean verifyOK = false; for (int i = 0; i < certs.length; i++) { if (req.verify(certs[i].getPublicKey(), "BC") == true) { signercert = certs[i]; signer = CertTools.getSubjectDN(signercert); Date now = new Date(); String signerissuer = CertTools.getIssuerDN(signercert); String infoMsg = intres.getLocalizedMessage("ocsp.infosigner", signer); log.info(infoMsg); verifyOK = true; /* * Also check that the signer certificate can be verified by one of the CA-certificates that we answer for */ X509Certificate signerca = certificateStoreSession .findLatestX509CertificateBySubject(CertTools.getIssuerDN(certs[i])); String subject = signer; String issuer = signerissuer; if (signerca != null) { try { signercert.verify(signerca.getPublicKey()); if (log.isDebugEnabled()) { log.debug("Checking validity. Now: " + now + ", signerNotAfter: " + signercert.getNotAfter()); } CertTools.checkValidity(signercert, now); // Move the error message string to the CA cert subject = CertTools.getSubjectDN(signerca); issuer = CertTools.getIssuerDN(signerca); CertTools.checkValidity(signerca, now); } catch (SignatureException e) { infoMsg = intres.getLocalizedMessage("ocsp.infosigner.invalidcertsignature", subject, issuer, e.getMessage()); log.info(infoMsg); verifyOK = false; } catch (InvalidKeyException e) { infoMsg = intres.getLocalizedMessage("ocsp.infosigner.invalidcertsignature", subject, issuer, e.getMessage()); log.info(infoMsg); verifyOK = false; } catch (CertificateNotYetValidException e) { infoMsg = intres.getLocalizedMessage("ocsp.infosigner.certnotyetvalid", subject, issuer, e.getMessage()); log.info(infoMsg); verifyOK = false; } catch (CertificateExpiredException e) { infoMsg = intres.getLocalizedMessage("ocsp.infosigner.certexpired", subject, issuer, e.getMessage()); log.info(infoMsg); verifyOK = false; } } else { infoMsg = intres.getLocalizedMessage("ocsp.infosigner.nocacert", signer, signerissuer); log.info(infoMsg); verifyOK = false; } break; } } if (!verifyOK) { String errMsg = intres.getLocalizedMessage("ocsp.errorinvalidsignature", signer); log.info(errMsg); throw new SignRequestSignatureException(errMsg); } } catch (OCSPException e) { throw new CryptoProviderException("BouncyCastle was not initialized properly.", e); } catch (NoSuchProviderException e) { throw new CryptoProviderException("BouncyCastle was not found as a provider.", e); } return signercert; }