Creates a new client certificate PKCS#12 and PEM store.  Any existing
stores are destroyed.

@param clientMetadata a container for dynamic parameters needed for generation
@param caPrivateKey
@param caCert
@param targetFolder
@return
178983
public static X509Certificate newClientCertificate(X509Metadata clientMetadata,
                                                       PrivateKey caPrivateKey, X509Certificate caCert, File targetFolder) {
        try {
            KeyPair pair = newKeyPair();

            X500Name userDN = buildDistinguishedName(clientMetadata);
            X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName());

            // create a new certificate signed by the Fathom CA certificate
            X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(
                    issuerDN,
                    BigInteger.valueOf(System.currentTimeMillis()),
                    clientMetadata.notBefore,
                    clientMetadata.notAfter,
                    userDN,
                    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()));
            certBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.keyEncipherment | KeyUsage.digitalSignature));
            if (!Strings.isNullOrEmpty(clientMetadata.emailAddress)) {
                GeneralNames subjectAltName = new GeneralNames(
                        new GeneralName(GeneralName.rfc822Name, clientMetadata.emailAddress));
                certBuilder.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName);
            }

            ContentSigner signer = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC).build(caPrivateKey);

            X509Certificate userCert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certBuilder.build(signer));
            PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) pair.getPrivate();
            bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                    extUtils.createSubjectKeyIdentifier(pair.getPublic()));

            // confirm the validity of the user certificate
            userCert.checkValidity();
            userCert.verify(caCert.getPublicKey());
            userCert.getIssuerDN().equals(caCert.getSubjectDN());

            // verify user certificate chain
            verifyChain(userCert, caCert);

            targetFolder.mkdirs();

            // save certificate, stamped with unique name
            String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
            String id = date;
            File certFile = new File(targetFolder, id + ".cer");
            int count = 0;
            while (certFile.exists()) {
                id = date + "_" + Character.toString((char) (0x61 + count));
                certFile = new File(targetFolder, id + ".cer");
                count++;
            }

            // save user private key, user certificate and CA certificate to a PKCS#12 store
            File p12File = new File(targetFolder, clientMetadata.commonName + ".p12");
            if (p12File.exists()) {
                p12File.delete();
            }
            KeyStore userStore = openKeyStore(p12File, clientMetadata.password);
            userStore.setKeyEntry(MessageFormat.format("Fathom ({0}) {1} {2}", clientMetadata.serverHostname, clientMetadata.userDisplayname, id), pair.getPrivate(), null, new Certificate[]{userCert});
            userStore.setCertificateEntry(MessageFormat.format("Fathom ({0}) Certificate Authority", clientMetadata.serverHostname), caCert);
            saveKeyStore(p12File, userStore, clientMetadata.password);

            // save user private key, user certificate, and CA certificate to a PEM store
            File pemFile = new File(targetFolder, clientMetadata.commonName + ".pem");
            if (pemFile.exists()) {
                pemFile.delete();
            }
            PEMWriter pemWriter = new PEMWriter(new FileWriter(pemFile));
            pemWriter.writeObject(pair.getPrivate(), "DES-EDE3-CBC", clientMetadata.password.toCharArray(), new SecureRandom());
            pemWriter.writeObject(userCert);
            pemWriter.writeObject(caCert);
            pemWriter.flush();
            pemWriter.close();

            // save certificate after successfully creating the key stores
            saveCertificate(userCert, certFile);

            // update serial number in metadata object
            clientMetadata.serialNumber = userCert.getSerialNumber().toString();

            return userCert;
        } catch (Throwable t) {
            throw new RuntimeException("Failed to generate client certificate!", t);
        }
    }
1029317
private PublicKey createPublicKey(String cert) {
        try {
            CertificateFactory fact = CertificateFactory.getInstance("X.509");
            InputStream stream = new ByteArrayInputStream(cert.getBytes(Charset.forName("UTF-8")));
            X509Certificate cer = (X509Certificate) fact.generateCertificate(stream);
            validateCertificate(cer);
            return cer.getPublicKey();
        } catch (SdkBaseException e) {
            throw e;
        } catch (Exception e) {
            throw new SdkClientException("Could not create public key from certificate", e);
        }
    }
807256
@Override
    public void loadCACertificatesAsBytes(Collection<byte[]> certificatesBytes) throws CryptoException {
        if (certificatesBytes == null || certificatesBytes.size() == 0) {
            throw new CryptoException("List of CA certificates is empty. Nothing to load.");
        }

        ArrayList<Certificate> certList = new ArrayList<>();
        for (byte[] certBytes : certificatesBytes) {
            certList.add(bytesToCertificate(certBytes));
        }
        loadCACertificates(certList);

    }
412378
private Collection<X509Certificate> getMatchingCACerts
        (ReverseState currentState, List<CertStore> certStores)
        throws CertificateException, CertStoreException, IOException {

        /*
         * Compose a CertSelector to filter out
         * certs which do not satisfy requirements.
         */
        X509CertSelector sel = new X509CertSelector();

        /*
         * Match on issuer (subject of previous cert)
         */
        sel.setIssuer(currentState.subjectDN);

        /*
         * Match on certificate validity date.
         */
        sel.setCertificateValid(buildParams.date());

        /*
         * Match on target subject name (checks that current cert's
         * name constraints permit it to certify target).
         * (4 is the integer type for DIRECTORY name).
         */
        byte[] subject = targetCertConstraints.getSubjectAsBytes();
        if (subject != null) {
            sel.addPathToName(4, subject);
        } else {
            X509Certificate cert = targetCertConstraints.getCertificate();
            if (cert != null) {
                sel.addPathToName(4,
                                  cert.getSubjectX500Principal().getEncoded());
            }
        }

        /*
         * Policy processing optimizations
         */
        if (currentState.explicitPolicy == 0)
            sel.setPolicy(getMatchingPolicies());

        /*
         * If previous cert has a subject key identifier extension,
         * use it to match on authority key identifier extension.
         */
        /*if (currentState.subjKeyId != null) {
          AuthorityKeyIdentifierExtension authKeyId = new AuthorityKeyIdentifierExtension(
                (KeyIdentifier) currentState.subjKeyId.get(SubjectKeyIdentifierExtension.KEY_ID),
                                null, null);
          sel.setAuthorityKeyIdentifier(authKeyId.getExtensionValue());
        }*/

        /*
         * Require CA certs
         */
        sel.setBasicConstraints(0);

        /* Retrieve matching certs from CertStores */
        ArrayList<X509Certificate> reverseCerts = new ArrayList<>();
        addMatchingCerts(sel, certStores, reverseCerts, true);

        /* Sort remaining certs using name constraints */
        Collections.sort(reverseCerts, new PKIXCertComparator());

        if (debug != null)
            debug.println("ReverseBuilder.getMatchingCACerts got " +
                          reverseCerts.size() + " certs.");
        return reverseCerts;
    }
249375
public static CloseableHttpClient createKeyMaterialHttpClient(KeyStore keystore,String keyPassword,String[] supportedProtocols,int timeout,int retryExecutionCount) {
		try {
			SSLContext sslContext = SSLContexts.custom().useSSL().loadKeyMaterial(keystore, keyPassword.toCharArray()).build();
			SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext,supportedProtocols,
	                null,SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
			SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(timeout).build();
			return HttpClientBuilder.create()
									.setDefaultSocketConfig(socketConfig)
									.setSSLSocketFactory(sf)
									.setRetryHandler(new HttpRequestRetryHandlerImpl(retryExecutionCount))
									.build();
		} catch (KeyManagementException e) {
			logger.error("", e);
		} catch (NoSuchAlgorithmException e) {
			logger.error("", e);
		} catch (UnrecoverableKeyException e) {
			logger.error("", e);
		} catch (KeyStoreException e) {
			logger.error("", e);
		}
		return null;
	}
357741
public static void newCertificateRevocationList(File caRevocationList, File caKeystoreFile, String caKeystorePassword) {
        try {
            // read the Fathom CA key and certificate
            KeyStore store = openKeyStore(caKeystoreFile, caKeystorePassword);
            PrivateKey caPrivateKey = (PrivateKey) store.getKey(CA_ALIAS, caKeystorePassword.toCharArray());
            X509Certificate caCert = (X509Certificate) store.getCertificate(CA_ALIAS);

            X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName());
            X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuerDN, new Date());

            // build and sign CRL with CA private key
            ContentSigner signer = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC).build(caPrivateKey);
            X509CRLHolder crl = crlBuilder.build(signer);

            File tmpFile = new File(caRevocationList.getParentFile(), Long.toHexString(System.currentTimeMillis()) + ".tmp");
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(tmpFile);
                fos.write(crl.getEncoded());
                fos.flush();
                fos.close();
                if (caRevocationList.exists()) {
                    caRevocationList.delete();
                }
                tmpFile.renameTo(caRevocationList);
            } finally {
                if (fos != null) {
                    fos.close();
                }
                if (tmpFile.exists()) {
                    tmpFile.delete();
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to create new certificate revocation list " + caRevocationList, e);
        }
    }
652011
static CloseableHttpClient buildHttpClient(
      boolean insecureMode, File ocspCacheFile, boolean useOcspCacheServer)
  {
    // set timeout so that we don't wait forever.
    // Setup the default configuration for all requests on this client
    DefaultRequestConfig =
        RequestConfig.custom()
            .setConnectTimeout(DEFAULT_CONNECTION_TIMEOUT)
            .setConnectionRequestTimeout(DEFAULT_CONNECTION_TIMEOUT)
            .setSocketTimeout(DEFAULT_HTTP_CLIENT_SOCKET_TIMEOUT)
            .build();

    TrustManager[] trustManagers = null;
    if (!insecureMode)
    {
      // A custom TrustManager is required only if insecureMode is disabled,
      // which is by default in the production. insecureMode can be enabled
      // 1) OCSP service is down for reasons, 2) PowerMock test tht doesn't
      // care OCSP checks.
      TrustManager[] tm = {
          new SFTrustManager(ocspCacheFile, useOcspCacheServer)};
      trustManagers = tm;
    }
    try
    {
      Registry<ConnectionSocketFactory> registry =
          RegistryBuilder.<ConnectionSocketFactory>create()
              .register("https",
                        new SFSSLConnectionSocketFactory(trustManagers, socksProxyDisabled))
              .register("http",
                        new SFConnectionSocketFactory())
              .build();

      // Build a connection manager with enough connections
      connectionManager = new PoolingHttpClientConnectionManager(registry);
      connectionManager.setMaxTotal(DEFAULT_MAX_CONNECTIONS);
      connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);

      if (useProxy)
      {
        // use the custom proxy properties
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        Credentials credentials =
            new UsernamePasswordCredentials(proxyUser, proxyPassword);
        AuthScope authScope = new AuthScope(proxyHost, proxyPort);
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(authScope, credentials);
        SdkProxyRoutePlanner sdkProxyRoutePlanner = new SdkProxyRoutePlanner(
            proxyHost, proxyPort, nonProxyHosts
        );
        httpClient =
            HttpClientBuilder.create()
                .setDefaultRequestConfig(DefaultRequestConfig)
                .setConnectionManager(connectionManager)
                // Support JVM proxy settings
                .useSystemProperties()
                .setRedirectStrategy(new DefaultRedirectStrategy())
                .setUserAgent("-")     // needed for Okta
                .disableCookieManagement() // SNOW-39748
                .setProxy(proxy)
                .setDefaultCredentialsProvider(credentialsProvider)
                .setRoutePlanner(sdkProxyRoutePlanner)
                .build();
      }
      else
      {
        httpClient =
            HttpClientBuilder.create()
                .setDefaultRequestConfig(DefaultRequestConfig)
                .setConnectionManager(connectionManager)
                // Support JVM proxy settings
                .useSystemProperties()
                .setRedirectStrategy(new DefaultRedirectStrategy())
                .setUserAgent("-")     // needed for Okta
                .disableCookieManagement() // SNOW-39748
                .build();
      }
      return httpClient;
    }
    catch (NoSuchAlgorithmException | KeyManagementException ex)
    {
      throw new SSLInitializationException(ex.getMessage(), ex);
    }
  }
755158
public static void loadX509Cert( Certificate cert, String certAlias, KeyStore keyStore ) throws KeyStoreException
    {
        keyStore.setCertificateEntry( certAlias, cert );
    }
1104018
public static X509Certificate[] copyCertChain(X509Certificate[] certChain) {

        if (certChain == null) {
            return null;
        }

        final int LEN = certChain.length;
        if (LEN == 0) {
            return new X509Certificate[LEN];
        }

        X509Certificate[] newCertChain = new X509Certificate[LEN];
        System.arraycopy(certChain, 0, newCertChain, 0, LEN);

        return newCertChain;
    }
219766
public static KeyManagerFactory getKeyManagerFactory(String keyStoreFilename, StoreProperties storeProperties)
      throws IOException, GeneralSecurityException {
    InputStream is = getResourceAsStream(keyStoreFilename);
    if (is == null) {
      throw new FileNotFoundException("Certificate file not found: " + getFilenameInfo(keyStoreFilename));
    }
    try {
      return getKeyManagerFactory(is, storeProperties);
    }
    finally {
      try {
        is.close();
      }
      catch (IOException ex) {
        // ignore
      }
    }
  }
992616
@Nonnull
  public static ClientCertificateValidationResult createSuccess (@Nonnull @Nonempty final String sClientID)
  {
    ValueEnforcer.notEmpty (sClientID, "ClientID");
    return new ClientCertificateValidationResult (true, sClientID);
  }
476313
def MakeCASignedCert(common_name,
                     private_key,
                     ca_cert,
                     ca_private_key,
                     serial_number=2):
  """"""
  public_key = private_key.GetPublicKey()

  builder = x509.CertificateBuilder()

  builder = builder.issuer_name(ca_cert.GetIssuer())

  subject = x509.Name(
      [x509.NameAttribute(oid.NameOID.COMMON_NAME, common_name)])
  builder = builder.subject_name(subject)

  valid_from = rdfvalue.RDFDatetime.Now() - rdfvalue.Duration("1d")
  valid_until = rdfvalue.RDFDatetime.Now() + rdfvalue.Duration("3650d")
  builder = builder.not_valid_before(valid_from.AsDatetime())
  builder = builder.not_valid_after(valid_until.AsDatetime())

  builder = builder.serial_number(serial_number)
  builder = builder.public_key(public_key.GetRawPublicKey())

  builder = builder.add_extension(
      x509.BasicConstraints(ca=False, path_length=None), critical=True)
  certificate = builder.sign(
      private_key=ca_private_key.GetRawPrivateKey(),
      algorithm=hashes.SHA256(),
      backend=openssl.backend)
  return rdf_crypto.RDFX509Cert(certificate)
583440
public static X509Certificate newCertificateAuthority(X509Metadata metadata, File storeFile, X509Log x509log) {
        try {
            KeyPair caPair = newKeyPair();

            ContentSigner caSigner = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC).build(caPair.getPrivate());

            // clone metadata
            X509Metadata caMetadata = metadata.clone(CA_CN, metadata.password);
            X500Name issuerDN = buildDistinguishedName(caMetadata);

            // Generate self-signed certificate
            X509v3CertificateBuilder caBuilder = new JcaX509v3CertificateBuilder(
                    issuerDN,
                    BigInteger.valueOf(System.currentTimeMillis()),
                    caMetadata.notBefore,
                    caMetadata.notAfter,
                    issuerDN,
                    caPair.getPublic());

            JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
            caBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(caPair.getPublic()));
            caBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caPair.getPublic()));
            caBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(true));
            caBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));

            JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider(BC);
            X509Certificate cert = converter.getCertificate(caBuilder.build(caSigner));

            // confirm the validity of the CA certificate
            cert.checkValidity(new Date());
            cert.verify(cert.getPublicKey());

            // Delete existing keystore
            if (storeFile.exists()) {
                storeFile.delete();
            }

            // Save private key and certificate to new keystore
            KeyStore store = openKeyStore(storeFile, caMetadata.password);
            store.setKeyEntry(CA_ALIAS, caPair.getPrivate(), caMetadata.password.toCharArray(),
                    new Certificate[]{cert});
            saveKeyStore(storeFile, store, caMetadata.password);

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

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

            return cert;
        } catch (Throwable t) {
            throw new RuntimeException("Failed to generate Fathom CA certificate!", t);
        }
    }
442409
public X509Certificate createCertificate(InputStream certRequestInputStream, X509Certificate cert,
        PrivateKey privateKey, int lifetime, int delegationMode, X509ExtensionSet extSet) throws IOException,
        GeneralSecurityException {
        return createCertificate(certRequestInputStream, cert, privateKey, lifetime, delegationMode, extSet, null);
    }
830644
@Override
  public X509Certificate getClientCertificate()
    throws java.security.cert.CertificateException
  {
    TempBuffer tb = TempBuffer.create();
    byte []buffer = tb.buffer();
    int len = getClientCertificate(_socketFd, buffer, 0, buffer.length);
    X509Certificate cert = null;

    if (len > 0 && len < buffer.length) {
      try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream is = new ByteArrayInputStream(buffer, 0, len);
        cert = (X509Certificate) cf.generateCertificate(is);
        is.close();
      } catch (IOException e) {
        return null;
      }
    }

    TempBuffer.free(tb);
    tb = null;

    return cert;
  }
767227
void setCertificateToTruststore(X509Certificate[] chain) throws Exception {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(tc, "setCertificateToTruststore");

        try {

            WSKeyStore wsks = KeyStoreManager.getInstance().getKeyStore(tsCfgAlias);
            if (wsks == null)
                throw (new Exception("Keystore " + tsCfgAlias + " does not exist in the configuration."));
            if (wsks.getReadOnly()) {
                issueMessage("ssl.keystore.readonly.CWPKI0810I",
                             new Object[] { tsCfgAlias },
                             "The "
                                             + tsCfgAlias
                                             + " keystore is read only and the certificate will not be written to the keystore file.  Trust will be accepted only for this connection.");

            } else {
                for (int j = 0; j < chain.length; j++) {
                    String alias = chain[j].getSubjectDN().getName();
                    alias = alias.trim();

                    if (tc.isDebugEnabled())
                        Tr.debug(tc, "Adding alias \"" + alias + "\" to truststore \"" + tsFile + "\".");
                    wsks.setCertificateEntry(alias, chain[chain.length - 1]);
                    String shaDigest = KeyStoreManager.getInstance().generateDigest("SHA-1", chain[chain.length - 1]);

                    issueMessage("ssl.signer.add.to.local.truststore.CWPKI0308I", new Object[] { alias, tsFile, shaDigest }, "CWPKI0308I: Adding signer alias \"" + alias
                                                                                                                             + "\" to local keystore \"" + tsFile
                                                                                                                             + "\" with the following SHA digest: " + shaDigest);

                    //Certificate is set on the truststore now clear the caches, if the file monitor is on let it handle the change.
                    String trigger = wsks.getTrigger();
                    if (!trigger.equalsIgnoreCase("disabled"))
                        clearSSLCachesAndResetDefault();
                }
            }
        } catch (Exception e) {
            if (tc.isDebugEnabled())
                Tr.debug(tc, "Exception while trying to write certificate to the truststore. Exception is " + e.getMessage());
            throw e;
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.exit(tc, "setCertificateToTruststore");
    }
32235
def set_client_cert_file(cert_file, key_file)
    @client_cert = OpenSSL::X509::Certificate.new(File.open(cert_file).read)
    @client_key = OpenSSL::PKey::RSA.new(File.open(key_file).read)
    change_notify
  end