List of usage examples for java.security.cert X509Certificate getPublicKey
public abstract PublicKey getPublicKey();
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 w w w . j av a2 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.yarn.server.resourcemanager.security.MockX509SecurityHandler.java
@Override public X509SecurityManagerMaterial generateMaterial(X509MaterialParameter materialParameter) throws Exception { ApplicationId appId = materialParameter.getApplicationId(); String appUser = materialParameter.getAppUser(); Integer cryptoMaterialVersion = materialParameter.getCryptoMaterialVersion(); KeyPair keyPair = generateKeyPair(); PKCS10CertificationRequest csr = generateCSR(appId, appUser, keyPair, cryptoMaterialVersion); assertEquals(appUser, HopsUtil.extractCNFromSubject(csr.getSubject().toString())); assertEquals(appId.toString(), HopsUtil.extractOFromSubject(csr.getSubject().toString())); assertEquals(String.valueOf(cryptoMaterialVersion), HopsUtil.extractOUFromSubject(csr.getSubject().toString())); // Sign CSR//from w ww.j a v a2 s . c o m CertificateBundle certificateBundle = sendCSRAndGetSigned(csr); certificateBundle.getCertificate().checkValidity(); long expiration = certificateBundle.getCertificate().getNotAfter().getTime(); long epochNow = DateUtils.localDateTime2UnixEpoch(DateUtils.getNow()); assertTrue(expiration >= epochNow); assertNotNull(certificateBundle.getIssuer()); RMAppSecurityActions actor = getRmAppSecurityActions(); if (actor instanceof TestingRMAppSecurityActions) { X509Certificate caCert = ((TestingRMAppSecurityActions) actor).getCaCert(); certificateBundle.getCertificate().verify(caCert.getPublicKey(), "BC"); } certificateBundle.getCertificate().verify(certificateBundle.getIssuer().getPublicKey(), "BC"); KeyStoresWrapper appKeystores = createApplicationStores(certificateBundle, keyPair.getPrivate(), appUser, appId); X509Certificate extractedCert = (X509Certificate) appKeystores.getKeystore().getCertificate(appUser); byte[] rawKeystore = appKeystores.getRawKeyStore(TYPE.KEYSTORE); assertNotNull(rawKeystore); assertNotEquals(0, rawKeystore.length); File keystoreFile = Paths.get(systemTMP, appUser + "-" + appId.toString() + "_kstore.jks").toFile(); // Keystore should have been deleted assertFalse(keystoreFile.exists()); char[] keyStorePassword = appKeystores.getKeyStorePassword(); assertNotNull(keyStorePassword); assertNotEquals(0, keyStorePassword.length); byte[] rawTrustStore = appKeystores.getRawKeyStore(TYPE.TRUSTSTORE); File trustStoreFile = Paths.get(systemTMP, appUser + "-" + appId.toString() + "_tstore.jks").toFile(); // Truststore should have been deleted assertFalse(trustStoreFile.exists()); char[] trustStorePassword = appKeystores.getTrustStorePassword(); assertNotNull(trustStorePassword); assertNotEquals(0, trustStorePassword.length); verifyContentOfAppTrustStore(rawTrustStore, trustStorePassword, appUser, appId); if (actor instanceof TestingRMAppSecurityActions) { X509Certificate caCert = ((TestingRMAppSecurityActions) actor).getCaCert(); extractedCert.verify(caCert.getPublicKey(), "BC"); } assertEquals(appUser, HopsUtil.extractCNFromSubject(extractedCert.getSubjectX500Principal().getName())); assertEquals(appId.toString(), HopsUtil.extractOFromSubject(extractedCert.getSubjectX500Principal().getName())); assertEquals(String.valueOf(cryptoMaterialVersion), HopsUtil.extractOUFromSubject(extractedCert.getSubjectX500Principal().getName())); return new X509SecurityManagerMaterial(appId, rawKeystore, appKeystores.getKeyStorePassword(), rawTrustStore, appKeystores.getTrustStorePassword(), expiration); }
From source file:org.apache.juddi.v3.client.cryptor.DigSigUtil.java
/** * Verifies the signature on an enveloped digital signature on a UDDI * entity, such as a business, service, tmodel or binding template. * <br><Br>/* ww w . jav a 2 s. c o m*/ * It is expected that either the public key of the signing certificate * is included within the signature keyinfo section OR that sufficient * information is provided in the signature to reference a public key * located within the Trust Store provided<br><Br> Optionally, this * function also validate the signing certificate using the options * provided to the configuration map. * * @param obj an enveloped signed JAXB object * @param OutErrorMessage a human readable error message explaining the * reason for failure * @return true if the validation passes the signature validation test, * and optionally any certificate validation or trust chain validation * @throws IllegalArgumentException for null input */ public boolean verifySignedUddiEntity(Object obj, AtomicReference<String> OutErrorMessage) throws IllegalArgumentException { if (OutErrorMessage == null) { OutErrorMessage = new AtomicReference<String>(); OutErrorMessage.set(""); } if (obj == null) { throw new IllegalArgumentException("obj"); } try { DOMResult domResult = new DOMResult(); JAXB.marshal(obj, domResult); Document doc = ((Document) domResult.getNode()); Element docElement = doc.getDocumentElement(); //this is our signed node X509Certificate signingcert = getSigningCertificatePublicKey(docElement); if (signingcert != null) { logger.info( "verifying signature based on X509 public key " + signingcert.getSubjectDN().toString()); if (map.containsKey(CHECK_TIMESTAMPS) && Boolean.parseBoolean(map.getProperty(CHECK_TIMESTAMPS))) { signingcert.checkValidity(); } if (map.containsKey(CHECK_REVOCATION_STATUS_OCSP) && Boolean.parseBoolean(map.getProperty(CHECK_REVOCATION_STATUS_OCSP))) { logger.info("verifying revocation status via OSCP for X509 public key " + signingcert.getSubjectDN().toString()); X500Principal issuerX500Principal = signingcert.getIssuerX500Principal(); logger.info("certificate " + signingcert.getSubjectDN().toString() + " was issued by " + issuerX500Principal.getName() + ", attempting to retrieve certificate"); Security.setProperty("ocsp.enable", "false"); X509Certificate issuer = FindCertByDN(issuerX500Principal); if (issuer == null) { OutErrorMessage.set( "Unable to verify certificate status from OCSP because the issuer of the certificate is not in the trust store. " + OutErrorMessage.get()); //throw new CertificateException("unable to locate the issuers certificate in the trust store"); } else { RevocationStatus check = OCSP.check(signingcert, issuer); logger.info("certificate " + signingcert.getSubjectDN().toString() + " revocation status is " + check.getCertStatus().toString() + " reason " + check.getRevocationReason().toString()); if (check.getCertStatus() != RevocationStatus.CertStatus.GOOD) { OutErrorMessage .set("Certificate status is " + check.getCertStatus().toString() + " reason " + check.getRevocationReason().toString() + "." + OutErrorMessage.get()); //throw new CertificateException("Certificate status is " + check.getCertStatus().toString() + " reason " + check.getRevocationReason().toString()); } } } if (map.containsKey(CHECK_REVOCATION_STATUS_CRL) && Boolean.parseBoolean(map.getProperty(CHECK_REVOCATION_STATUS_CRL))) { logger.info("verifying revokation status via CRL for X509 public key " + signingcert.getSubjectDN().toString()); Security.setProperty("ocsp.enable", "false"); System.setProperty("com.sun.security.enableCRLDP", "true"); X509CertSelector targetConstraints = new X509CertSelector(); targetConstraints.setCertificate(signingcert); PKIXParameters params = new PKIXParameters(GetTrustStore()); params.setRevocationEnabled(true); CertPath certPath = cf.generateCertPath(Arrays.asList(signingcert)); CertPathValidator certPathValidator = CertPathValidator .getInstance(CertPathValidator.getDefaultType()); CertPathValidatorResult result = certPathValidator.validate(certPath, params); try { PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result; logger.info("revokation status via CRL PASSED for X509 public key " + signingcert.getSubjectDN().toString()); } catch (Exception ex) { OutErrorMessage.set("Certificate status is via CRL Failed: " + ex.getMessage() + "." + OutErrorMessage.get()); } } if (map.containsKey(CHECK_TRUST_CHAIN) && Boolean.parseBoolean(map.getProperty(CHECK_TRUST_CHAIN))) { logger.info("verifying trust chain X509 public key " + signingcert.getSubjectDN().toString()); try { PKIXParameters params = new PKIXParameters(GetTrustStore()); params.setRevocationEnabled(false); CertPath certPath = cf.generateCertPath(Arrays.asList(signingcert)); CertPathValidator certPathValidator = CertPathValidator .getInstance(CertPathValidator.getDefaultType()); CertPathValidatorResult result = certPathValidator.validate(certPath, params); PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result; TrustAnchor ta = pkixResult.getTrustAnchor(); X509Certificate cert = ta.getTrustedCert(); logger.info( "trust chain validated X509 public key " + signingcert.getSubjectDN().toString()); } catch (Exception ex) { OutErrorMessage.set("Certificate status Trust validation failed: " + ex.getMessage() + "." + OutErrorMessage.get()); } } boolean b = verifySignature(docElement, signingcert.getPublicKey(), OutErrorMessage); if ((OutErrorMessage.get() == null || OutErrorMessage.get().length() == 0) && b) { //no error message and its cryptographically valid return true; } return false; } //last chance validation logger.info( "signature did not have an embedded X509 public key. reverting to user specified certificate"); //cert wasn't included in the signature, revert to some other means KeyStore ks = KeyStore.getInstance(map.getProperty(SIGNATURE_KEYSTORE_FILETYPE)); URL url = Thread.currentThread().getContextClassLoader() .getResource(map.getProperty(SIGNATURE_KEYSTORE_FILE)); if (url == null) { try { url = new File(map.getProperty(SIGNATURE_KEYSTORE_FILE)).toURI().toURL(); } catch (Exception x) { } } if (url == null) { try { url = this.getClass().getClassLoader().getResource(map.getProperty(SIGNATURE_KEYSTORE_FILE)); } catch (Exception x) { } } if (url == null) { logger.error(""); OutErrorMessage.set("The signed entity is signed but does not have a certificate attached and" + "you didn't specify a keystore for me to look it up in. " + OutErrorMessage.get()); return false; } KeyStore.PrivateKeyEntry keyEntry = null; ks.load(url.openStream(), map.getProperty(SIGNATURE_KEYSTORE_FILE_PASSWORD).toCharArray()); if (map.getProperty(SIGNATURE_KEYSTORE_KEY_PASSWORD) == null) { keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(map.getProperty(SIGNATURE_KEYSTORE_KEY_ALIAS), new KeyStore.PasswordProtection( map.getProperty(SIGNATURE_KEYSTORE_FILE_PASSWORD).toCharArray())); } else { keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(map.getProperty(SIGNATURE_KEYSTORE_KEY_ALIAS), new KeyStore.PasswordProtection( map.getProperty(SIGNATURE_KEYSTORE_KEY_PASSWORD).toCharArray())); } Certificate origCert = keyEntry.getCertificate(); if (map.containsKey(CHECK_TIMESTAMPS)) { if (origCert.getPublicKey() instanceof X509Certificate) { X509Certificate x = (X509Certificate) origCert.getPublicKey(); x.checkValidity(); } } PublicKey validatingKey = origCert.getPublicKey(); return verifySignature(docElement, validatingKey, OutErrorMessage); } catch (Exception e) { //throw new RuntimeException(e); logger.error("Error caught validating signature", e); OutErrorMessage.set(e.getMessage()); return false; } }
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."); }//from w w w .j a v a2s. com 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.standalone.TlsToolkitStandaloneTest.java
private X509Certificate checkLoadCertPrivateKey(String algorithm) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException { KeyPair keyPair = TlsHelperTest.loadKeyPair(new File(tempDir, TlsToolkitStandalone.NIFI_KEY + ".key")); assertEquals(algorithm, keyPair.getPrivate().getAlgorithm()); assertEquals(algorithm, keyPair.getPublic().getAlgorithm()); X509Certificate x509Certificate = TlsHelperTest .loadCertificate(new File(tempDir, TlsToolkitStandalone.NIFI_CERT + ".pem")); assertEquals(keyPair.getPublic(), x509Certificate.getPublicKey()); return x509Certificate; }
From source file:org.apache.nifi.toolkit.tls.standalone.TlsToolkitStandaloneTest.java
private Properties checkHostDirAndReturnNifiProperties(String hostname, String dnPrefix, String dnSuffix, X509Certificate rootCert) throws Exception { File hostDir = new File(tempDir, hostname); Properties nifiProperties = new Properties(); try (InputStream inputStream = new FileInputStream( new File(hostDir, TlsToolkitStandalone.NIFI_PROPERTIES))) { nifiProperties.load(inputStream); }/* www .j av a 2 s . c o m*/ String trustStoreType = nifiProperties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_TYPE); assertEquals(KeystoreType.JKS.toString().toLowerCase(), trustStoreType.toLowerCase()); KeyStore trustStore = KeyStoreUtils.getTrustStore(trustStoreType); try (InputStream inputStream = new FileInputStream(new File(hostDir, "truststore." + trustStoreType))) { trustStore.load(inputStream, nifiProperties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD).toCharArray()); } String trustStoreFilename = BaseCommandLine.TRUSTSTORE + trustStoreType; assertEquals("./conf/" + trustStoreFilename, nifiProperties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE)); Certificate certificate = trustStore.getCertificate(TlsToolkitStandalone.NIFI_CERT); assertEquals(rootCert, certificate); String keyStoreType = nifiProperties.getProperty(NiFiProperties.SECURITY_KEYSTORE_TYPE); String keyStoreFilename = BaseCommandLine.KEYSTORE + keyStoreType; File keyStoreFile = new File(hostDir, keyStoreFilename); assertEquals("./conf/" + keyStoreFilename, nifiProperties.getProperty(NiFiProperties.SECURITY_KEYSTORE)); KeyStore keyStore = KeyStoreUtils.getKeyStore(keyStoreType); char[] keyStorePassword = nifiProperties.getProperty(NiFiProperties.SECURITY_KEYSTORE_PASSWD).toCharArray(); try (InputStream inputStream = new FileInputStream(keyStoreFile)) { keyStore.load(inputStream, keyStorePassword); } char[] keyPassword = nifiProperties.getProperty(NiFiProperties.SECURITY_KEY_PASSWD).toCharArray(); if (keyPassword == null || keyPassword.length == 0) { keyPassword = keyStorePassword; } KeyStore.Entry entry = keyStore.getEntry(TlsToolkitStandalone.NIFI_KEY, new KeyStore.PasswordProtection(keyPassword)); assertEquals(KeyStore.PrivateKeyEntry.class, entry.getClass()); KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) entry; Certificate[] certificateChain = privateKeyEntry.getCertificateChain(); assertEquals(2, certificateChain.length); assertEquals(rootCert, certificateChain[1]); certificateChain[1].verify(rootCert.getPublicKey()); certificateChain[0].verify(rootCert.getPublicKey()); TlsConfig tlsConfig = new TlsConfig(); tlsConfig.setDnPrefix(dnPrefix); tlsConfig.setDnSuffix(dnSuffix); assertEquals(tlsConfig.calcDefaultDn(hostname), CertificateUtils .convertAbstractX509Certificate(certificateChain[0]).getSubjectX500Principal().getName()); TlsCertificateAuthorityTest.assertPrivateAndPublicKeyMatch(privateKeyEntry.getPrivateKey(), certificateChain[0].getPublicKey()); return nifiProperties; }
From source file:org.apache.nifi.toolkit.tls.standalone.TlsToolkitStandaloneTest.java
private void checkClientCert(String clientDn, X509Certificate rootCert) throws Exception { String clientDnFile = TlsToolkitStandalone.getClientDnFile(CertificateUtils.reorderDn(clientDn)); String password;//from ww w . j a va 2s .com try (FileReader fileReader = new FileReader(new File(tempDir, clientDnFile + ".password"))) { List<String> lines = IOUtils.readLines(fileReader); assertEquals(1, lines.size()); password = lines.get(0); } KeyStore keyStore = KeyStoreUtils.getKeyStore(KeystoreType.PKCS12.toString()); try (FileInputStream fileInputStream = new FileInputStream(new File(tempDir, clientDnFile + ".p12"))) { keyStore.load(fileInputStream, password.toCharArray()); } PrivateKey privateKey = (PrivateKey) keyStore.getKey(TlsToolkitStandalone.NIFI_KEY, new char[0]); Certificate[] certificateChain = keyStore.getCertificateChain(TlsToolkitStandalone.NIFI_KEY); assertEquals(2, certificateChain.length); assertEquals(rootCert, certificateChain[1]); certificateChain[1].verify(rootCert.getPublicKey()); certificateChain[0].verify(rootCert.getPublicKey()); PublicKey publicKey = certificateChain[0].getPublicKey(); TlsCertificateAuthorityTest.assertPrivateAndPublicKeyMatch(privateKey, publicKey); }
From source file:org.apache.nifi.toolkit.tls.util.TlsHelperTest.java
@Test public void testGenerateSelfSignedCert() throws GeneralSecurityException, IOException, OperatorCreationException { String dn = "CN=testDN,O=testOrg"; X509Certificate x509Certificate = CertificateUtils.generateSelfSignedX509Certificate( TlsHelper.generateKeyPair(keyPairAlgorithm, keySize), dn, signingAlgorithm, days); 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(dn, x509Certificate.getIssuerX500Principal().getName()); assertEquals(signingAlgorithm, x509Certificate.getSigAlgName()); assertEquals(keyPairAlgorithm, x509Certificate.getPublicKey().getAlgorithm()); x509Certificate.checkValidity(); }
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.apache.nifi.web.security.x509.ocsp.OcspCertificateValidator.java
/** * Gets the OCSP status for the specified subject and issuer certificates. * * @param ocspStatusKey status key//from w w w . java 2s . c o m * @return ocsp status */ private OcspStatus getOcspStatus(final OcspRequest ocspStatusKey) { final X509Certificate subjectCertificate = ocspStatusKey.getSubjectCertificate(); final X509Certificate issuerCertificate = ocspStatusKey.getIssuerCertificate(); // initialize the default status final OcspStatus ocspStatus = new OcspStatus(); ocspStatus.setVerificationStatus(VerificationStatus.Unknown); ocspStatus.setValidationStatus(ValidationStatus.Unknown); try { // prepare the request final BigInteger subjectSerialNumber = subjectCertificate.getSerialNumber(); final DigestCalculatorProvider calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder() .setProvider("BC").build(); final CertificateID certificateId = new CertificateID( calculatorProviderBuilder.get(CertificateID.HASH_SHA1), new X509CertificateHolder(issuerCertificate.getEncoded()), subjectSerialNumber); // generate the request final OCSPReqBuilder requestGenerator = new OCSPReqBuilder(); requestGenerator.addRequest(certificateId); // Create a nonce to avoid replay attack BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis()); Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true, new DEROctetString(nonce.toByteArray())); requestGenerator.setRequestExtensions(new Extensions(new Extension[] { ext })); final OCSPReq ocspRequest = requestGenerator.build(); // perform the request final ClientResponse response = getClientResponse(ocspRequest); // ensure the request was completed successfully if (ClientResponse.Status.OK.getStatusCode() != response.getStatusInfo().getStatusCode()) { logger.warn(String.format("OCSP request was unsuccessful (%s).", response.getStatus())); return ocspStatus; } // interpret the response OCSPResp ocspResponse = new OCSPResp(response.getEntityInputStream()); // verify the response status switch (ocspResponse.getStatus()) { case OCSPRespBuilder.SUCCESSFUL: ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Successful); break; case OCSPRespBuilder.INTERNAL_ERROR: ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.InternalError); break; case OCSPRespBuilder.MALFORMED_REQUEST: ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.MalformedRequest); break; case OCSPRespBuilder.SIG_REQUIRED: ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.SignatureRequired); break; case OCSPRespBuilder.TRY_LATER: ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.TryLater); break; case OCSPRespBuilder.UNAUTHORIZED: ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Unauthorized); break; default: ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Unknown); break; } // only proceed if the response was successful if (ocspResponse.getStatus() != OCSPRespBuilder.SUCCESSFUL) { logger.warn(String.format("OCSP request was unsuccessful (%s).", ocspStatus.getResponseStatus().toString())); return ocspStatus; } // ensure the appropriate response object final Object ocspResponseObject = ocspResponse.getResponseObject(); if (ocspResponseObject == null || !(ocspResponseObject instanceof BasicOCSPResp)) { logger.warn(String.format("Unexpected OCSP response object: %s", ocspResponseObject)); return ocspStatus; } // get the response object final BasicOCSPResp basicOcspResponse = (BasicOCSPResp) ocspResponse.getResponseObject(); // attempt to locate the responder certificate final X509CertificateHolder[] responderCertificates = basicOcspResponse.getCerts(); if (responderCertificates.length != 1) { logger.warn(String.format("Unexpected number of OCSP responder certificates: %s", responderCertificates.length)); return ocspStatus; } // get the responder certificate final X509Certificate trustedResponderCertificate = getTrustedResponderCertificate( responderCertificates[0], issuerCertificate); if (trustedResponderCertificate != null) { // verify the response if (basicOcspResponse.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC") .build(trustedResponderCertificate.getPublicKey()))) { ocspStatus.setVerificationStatus(VerificationStatus.Verified); } else { ocspStatus.setVerificationStatus(VerificationStatus.Unverified); } } else { ocspStatus.setVerificationStatus(VerificationStatus.Unverified); } // validate the response final SingleResp[] responses = basicOcspResponse.getResponses(); for (SingleResp singleResponse : responses) { final CertificateID responseCertificateId = singleResponse.getCertID(); final BigInteger responseSerialNumber = responseCertificateId.getSerialNumber(); if (responseSerialNumber.equals(subjectSerialNumber)) { Object certStatus = singleResponse.getCertStatus(); // interpret the certificate status if (CertificateStatus.GOOD == certStatus) { ocspStatus.setValidationStatus(ValidationStatus.Good); } else if (certStatus instanceof RevokedStatus) { ocspStatus.setValidationStatus(ValidationStatus.Revoked); } else { ocspStatus.setValidationStatus(ValidationStatus.Unknown); } } } } catch (final OCSPException | IOException | UniformInterfaceException | ClientHandlerException | OperatorCreationException e) { logger.error(e.getMessage(), e); } catch (CertificateException e) { e.printStackTrace(); } return ocspStatus; }