Creates a builder for new server-side {@link SslContext}.

@param keyCertChainFile an X.509 certificate chain file in PEM format
@param keyFile a PKCS#8 private key file in PEM format
@see #keyManager(File, File)
556897
public static SslContextBuilder forServer(File keyCertChainFile, File keyFile) {
        return new SslContextBuilder(true).keyManager(keyCertChainFile, keyFile);
    }
99225
public B tls(File keyCertChainFile, File keyFile) throws SSLException {
        tls(keyCertChainFile, keyFile, null, sslContextBuilder -> { /* noop */ });
        return self();
    }
422526
public static X509Certificate newSSLCertificate(X509Metadata sslMetadata, PrivateKey caPrivateKey, X509Certificate caCert, File targetStoreFile, X509Log x509log) {
        try {
            KeyPair pair = newKeyPair();

            X500Name webDN = buildDistinguishedName(sslMetadata);
            X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName());

            X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(
                    issuerDN,
                    BigInteger.valueOf(System.currentTimeMillis()),
                    sslMetadata.notBefore,
                    sslMetadata.notAfter,
                    webDN,
                    pair.getPublic());

            JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
            certBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(pair.getPublic()));
            certBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false));
            certBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert.getPublicKey()));

            // support alternateSubjectNames for SSL certificates
            List<GeneralName> altNames = new ArrayList<GeneralName>();
            if (isIpAddress(sslMetadata.commonName)) {
                altNames.add(new GeneralName(GeneralName.iPAddress, sslMetadata.commonName));
            }
            if (altNames.size() > 0) {
                GeneralNames subjectAltName = new GeneralNames(altNames.toArray(new GeneralName[altNames.size()]));
                certBuilder.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName);
            }

            ContentSigner caSigner = new JcaContentSignerBuilder(SIGNING_ALGORITHM)
                    .setProvider(BC).build(caPrivateKey);
            X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC)
                    .getCertificate(certBuilder.build(caSigner));

            cert.checkValidity(new Date());
            cert.verify(caCert.getPublicKey());

            // Save to keystore
            KeyStore serverStore = openKeyStore(targetStoreFile, sslMetadata.password);
            serverStore.setKeyEntry(sslMetadata.commonName, pair.getPrivate(), sslMetadata.password.toCharArray(),
                    new Certificate[]{cert, caCert});
            saveKeyStore(targetStoreFile, serverStore, sslMetadata.password);

            x509log.log(MessageFormat.format("New SSL certificate {0,number,0} [{1}]", cert.getSerialNumber(), cert.getSubjectDN().getName()));

            // update serial number in metadata object
            sslMetadata.serialNumber = cert.getSerialNumber().toString();

            return cert;
        } catch (Throwable t) {
            throw new RuntimeException("Failed to generate SSL certificate!", t);
        }
    }
891837
public void installCertificates(final String key, final String cert, final String chain)
	{
		try
		{
			final File keyFile = File.createTempFile("key", ".pem");
			final File certFile = File.createTempFile("cert", ".pem");
			final File chainFile = File.createTempFile("chain", ".pem");

			try
			{
				FileHelper.write(keyFile, key);
				FileHelper.write(certFile, cert);
				FileHelper.write(chainFile, chain);

				final Execed process = Exec.rootUtility(new File(binPath, "cert-update").getAbsolutePath(),
				                                        keyFile.getAbsolutePath(),
				                                        certFile.getAbsolutePath(),
				                                        chainFile.getAbsolutePath());

				process.waitForExit(new Timeout(30, TimeUnit.SECONDS).start(), 0);
			}
			finally
			{
				FileUtils.deleteQuietly(keyFile);
				FileUtils.deleteQuietly(certFile);
				FileUtils.deleteQuietly(chainFile);
			}
		}
		catch (IOException e)
		{
			throw new RuntimeException("Error executing cert-update command", e);
		}
	}
224434
public void setCertificateChainFile(Path certificateChainFile)
  {
    try {
      _certificateChainFile = certificateChainFile.toRealPath().toString();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
935979
public SSLEngine initSslEngine(boolean client) throws Exception {
    // Load the keystore
    KeyStore keyStore = loadKeystore(properties.sslKeyStorePath(), properties.sslKeyStorePassword());

    // Setup the keyManager to use our keystore
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, keyStoreKeyPass(properties));

    // Setup the Trust keystore
    KeyStore trustStore;
    if (properties.sslTrustStorePath() != null) {
      // Use the separate Trust keystore
      LOGGER.debug("Using separate trust store");
      trustStore = loadKeystore(properties.sslTrustStorePath(), properties.sslTrustStorePassword());
    } else {
      // Reuse the existing keystore
      trustStore = keyStore;
      LOGGER.debug("Using key store as trust store");
    }

    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);

    KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagers, trustManagers, null);
    SSLEngine sslEngine = sslContext.createSSLEngine();
    sslEngine.setUseClientMode(client);
    sslEngine.setWantClientAuth(true);
    sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols());
    sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites());
    sslEngine.setEnableSessionCreation(true);

    return sslEngine;
  }
825831
public static void convertFile(File keyFile, int toFormat, File toFile)
			throws IOException {

		SshPublicKeyFile pub = parse(new FileInputStream(keyFile));
		createFile(pub.toPublicKey(), pub.getComment(), toFormat, toFile);
	}
772850
protected SSLServerSocketFactory createFactory() 
    	throws Exception
    {
        SSLContext context;
        if (_provider == null) {
			context = SSLContext.getInstance(_protocol);
		} else {
			context = SSLContext.getInstance(_protocol, _provider);
		}

        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(_algorithm);        
        KeyStore keyStore = KeyStore.getInstance(_keystoreType);
        keyStore.load(Resource.newResource(_keystore).getInputStream(), _password.toString().toCharArray());
        keyManagerFactory.init(keyStore,_keypassword.toString().toCharArray());
        
        context.init(keyManagerFactory.getKeyManagers(), null, new java.security.SecureRandom());

        return context.getServerSocketFactory();
    }
1331927
public SslContextBuilder trustManager(File trustCertCollectionFile) {
        try {
            return trustManager(SslContext.toX509Certificates(trustCertCollectionFile));
        } catch (Exception e) {
            throw new IllegalArgumentException("File does not contain valid certificates: "
                    + trustCertCollectionFile, e);
        }
    }
1011954
public static InternalProtocolNegotiator.ProtocolNegotiator tls(SslContext sslContext) {
    final io.grpc.netty.ProtocolNegotiator negotiator = ProtocolNegotiators.tls(sslContext);
    final class TlsNegotiator implements InternalProtocolNegotiator.ProtocolNegotiator {

      @Override
      public AsciiString scheme() {
        return negotiator.scheme();
      }

      @Override
      public ChannelHandler newHandler(GrpcHttp2ConnectionHandler grpcHandler) {
        return negotiator.newHandler(grpcHandler);
      }

      @Override
      public void close() {
        negotiator.close();
      }
    }
    
    return new TlsNegotiator();
  }
268394
public SSLContext createSSLContextFromKeystores(boolean isServer) {
        String protocol = sslConfig.getSSLProtocol();
        try {
            KeyManager[] keyManagers = null;
            if (sslConfig.getKeyStore() != null) {
                KeyStore ks = getKeyStore(sslConfig.getKeyStore(), sslConfig.getKeyStorePass());
                // Set up key manager factory to use our key store
                kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                if (ks != null) {
                    kmf.init(ks, sslConfig.getCertPass() != null ?
                            sslConfig.getCertPass().toCharArray() :
                            sslConfig.getKeyStorePass().toCharArray());
                    keyManagers = kmf.getKeyManagers();
                }
            }
            TrustManager[] trustManagers = null;
            if (sslConfig.getTrustStore() != null) {
                KeyStore tks = getKeyStore(sslConfig.getTrustStore(), sslConfig.getTrustStorePass());
                tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                tmf.init(tks);
                trustManagers = tmf.getTrustManagers();
            }
            sslContext = SSLContext.getInstance(protocol);
            sslContext.init(keyManagers, trustManagers, null);
            int sessionTimeout = sslConfig.getSessionTimeOut();
            if (isServer) {
                if (sessionTimeout > 0) {
                    sslContext.getServerSessionContext().setSessionTimeout(sessionTimeout);
                }
            } else {
                if (sessionTimeout > 0) {
                    sslContext.getClientSessionContext().setSessionTimeout(sessionTimeout);
                }
            }
            return sslContext;

        } catch (UnrecoverableKeyException | KeyManagementException |
                NoSuchAlgorithmException | KeyStoreException | IOException e) {
            throw new IllegalArgumentException("Failed to initialize the SSLContext", e);
        }
    }
289363
public void readFrom(File keyFile) throws IOException, GeneralSecurityException {
        final String password = isPemEncrypted(keyFile)
                ? askForPasswd(keyFile.getCanonicalPath())
                : null
        ;
        privateKeys.add(loadKey(keyFile, password));
    }
873131
public void setCertificateEntry(String alias, Certificate cert) throws KeyStoreException, KeyException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(this, tc, "setCertificateEntry", new Object[] { alias, cert });
        }
        if (Boolean.parseBoolean(getProperty(Constants.SSLPROP_KEY_STORE_READ_ONLY))) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(this, tc, "Unable to update readonly store");
            }
            throw new KeyStoreException("Unable to add to read-only store");
        }
        final KeyStoreManager mgr = KeyStoreManager.getInstance();

        try {
            KeyStore jKeyStore = getKeyStore(false, false);
            if (null == jKeyStore) {
                final String keyStoreLocation = getProperty(Constants.SSLPROP_KEY_STORE);
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Cannot load the Java keystore at location \"" + keyStoreLocation + "\"");
                }
                throw new KeyStoreException("Cannot load the Java keystore at location \"" + keyStoreLocation + "\"");
            }

            // store the cert... errors are thrown if conflicts or errors occur
            jKeyStore.setCertificateEntry(alias, cert);

            try {
                store();
            } catch (IOException e) {
                // Note: debug + ffdc in store() itself

                // on z/OS we have an issue where the certificate may be stored but the
                // alias
                // already exists in RACF so the keystore API will through an
                // IOException
                // we need to catch this condition on z/OS and if the certs is in the
                // keystore
                // prior after adding the certificate then we know the cert was actually
                // added and its not
                // a true failure. If the cert was not added then we need to rethrow the
                // exception.
                final String ksType = getProperty(Constants.SSLPROP_KEY_STORE_TYPE);
                if ((ksType.equals(Constants.KEYSTORE_TYPE_JCERACFKS) || ksType.equals(Constants.KEYSTORE_TYPE_JCECCARACFKS)
                     || ksType.equals(Constants.KEYSTORE_TYPE_JCEHYBRIDRACFKS))) {
                    KeyStore ks = getKeyStore(true, false);

                    if (mgr.checkIfSignerAlreadyExistsInTrustStore((X509Certificate) cert, ks)) {
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "Certificate already exists in RACF: " + e.getMessage());
                        }
                    } else {
                        throw new KeyException(e.getMessage(), e);
                    }
                } else {
                    throw new KeyException(e.getMessage(), e);
                }
            }
        } catch (KeyStoreException kse) {
            throw kse;
        } catch (KeyException ke) {
            throw ke;
        } catch (Exception e) {
            throw new KeyException(e.getMessage(), e);
        }

        // after adding the certificate, clear the keystore and SSL caches so it
        // reloads it.
        AbstractJSSEProvider.clearSSLContextCache();
        mgr.clearJavaKeyStoresFromKeyStoreMap();

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(this, tc, "setCertificateEntry");
        }
    }
669392
static public void genCertificateRequest(String dname,
                                             String emailAddressOfCA,
                                             String password,
                                             File keyFile,
                                             File certFile,
                                             File certReqFile)
        throws Exception {

        String sigAlgName = "MD5WithRSA";
        String keyAlgName = "RSA";

	CertUtil.init();

	X509Name name = new X509Name(dname);

	String certSubject = X509NameHelper.toString(name);

	System.out.println("Generating a 1024 bit RSA private key");

        // Generate a new key pair.
        KeyPairGenerator keygen = KeyPairGenerator.getInstance(keyAlgName);
	keygen.initialize(1024);
        KeyPair keyPair = keygen.genKeyPair();
        PrivateKey privKey = keyPair.getPrivate();
        PublicKey pubKey = keyPair.getPublic();

        // Generate the certificate request.
        DERSet derSet = new DERSet();
        PKCS10CertificationRequest request =
            new PKCS10CertificationRequest(
                sigAlgName,
                name,
                pubKey,
                derSet,
                privKey);

        // Save the certificate request to a .pem file.
        byte[] data = request.getEncoded();
	byte[] encodedData = Base64.encode(data);

        PrintStream ps = null;

	try {
	    ps = new PrintStream(new FileOutputStream(certReqFile));

            boolean caEmail = false;

            if ((emailAddressOfCA != null) &&
                (emailAddressOfCA.length() > 0)) {
                caEmail = true;
                ps.print("\n\n" + "Please mail the following certificate request to " + emailAddressOfCA);
            } else {
                ps.print("\n\n" + "Please send the following certificate request to the Certificate Authority (CA). Refer to CA instructions for details on to send the request.");
            }
            ps.print("\n\n"
                     + "==================================================================\n"
                     + "\n"
                     + "Certificate Subject:\n"
                     + "\n"
                     + certSubject
                     + "\n"
                     + "\n"
                     + "The above string is known as your user certificate subject, and it \n"
                     + "uniquely identifies this user.\n"
                     + "\n"
                     + "To install this user certificate, please save this e-mail message\n"
                     + "into the following file.\n"
                     + "\n"
                     + "\n"
                     + certReqFile.getAbsolutePath()
                     + "\n"
                     + "\n"
                     + "\n"
                     + "      You need not edit this message in any way. Simply \n"
                     + "      save this e-mail message to the file.\n"
                     + "\n"
                     + "\n"
                     + "If you have any questions about the certificate contact\n"
                     + "the Certificate Authority");
            if (caEmail) {
                ps.print("at " + emailAddressOfCA);
            }
            ps.print("\n\n");
	    PEMUtils.writeBase64(ps,
				 "-----BEGIN CERTIFICATE REQUEST-----",
				 encodedData,
				 "-----END CERTIFICATE REQUEST-----");
	} finally {
	    if (ps != null) {
		ps.close();
	    }
	}

        // Save private key to a .pem file.
        OpenSSLKey key = new BouncyCastleOpenSSLKey(privKey);
        if (password != null) {
            key.encrypt(password);
        }
	// this will set the permissions correctly already
        key.writeTo(keyFile.getAbsolutePath());

        // Create an empty cert file.
        certFile.createNewFile();

	System.out.println("A private key and a certificate request has been generated with the subject:");
	System.out.println();
	System.out.println(certSubject);
	System.out.println();

	System.out.println("The private key is stored in " +
			   keyFile.getAbsolutePath());
	System.out.println("The request is stored in " +
			   certReqFile.getAbsolutePath());

    }
272252
public static KeyStore createTrustStore(final Reader certReader) throws IOException, CertificateException,
            KeyStoreException, NoSuchAlgorithmException {
        try (PEMParser pemParser = new PEMParser(certReader)) {

            KeyStore trustStore = KeyStore.getInstance("JKS");
            trustStore.load(null);

            int index = 1;
            Object pemCert;

            while ((pemCert = pemParser.readObject()) != null) {
                Certificate caCertificate = new JcaX509CertificateConverter()
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME)
                        .getCertificate((X509CertificateHolder) pemCert);
                trustStore.setCertificateEntry("ca-" + index, caCertificate);
                index++;
            }

            return trustStore;
        }
    }
796984
public SSLEngine buildServerSSLEngine(SSLContext sslContext) {
        SSLEngine engine = sslContext.createSSLEngine();
        engine.setUseClientMode(false);
        if (needClientAuth) {
            engine.setNeedClientAuth(true);
        } else if (wantClientAuth) {
            engine.setWantClientAuth(true);
        }
        return addCommonConfigs(engine);
    }
1190378
private SSLContext getSSLContext(String truststorePath,
                                     String truststorePassword,
                                     String keystorePath, 
                                     String keystorePassword) throws Exception {

        FileInputStream tsf = new FileInputStream(truststorePath);
        KeyStore ts = KeyStore.getInstance("JKS");
        ts.load(tsf, truststorePassword.toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ts);

        FileInputStream ksf = new FileInputStream(keystorePath);
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(ksf, keystorePassword.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, keystorePassword.toCharArray());

        SSLContext ctx = SSLContext.getInstance("SSL");
        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
        return ctx;
    }