/*
Method adds the certificate entry to the truststore.
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");
    }
442768
public void updateState(TrustAnchor anchor, BuilderParams buildParams)
        throws CertificateException, IOException, CertPathValidatorException
    {
        trustAnchor = anchor;
        X509Certificate trustedCert = anchor.getTrustedCert();
        if (trustedCert != null) {
            updateState(trustedCert);
        } else {
            X500Principal caName = anchor.getCA();
            updateState(anchor.getCAPublicKey(), caName);
        }

        // The user specified AlgorithmChecker and RevocationChecker may not be
        // able to set the trust anchor until now.
        boolean revCheckerAdded = false;
        for (PKIXCertPathChecker checker : userCheckers) {
            if (checker instanceof AlgorithmChecker) {
                ((AlgorithmChecker)checker).trySetTrustAnchor(anchor);
            } else if (checker instanceof PKIXRevocationChecker) {
                if (revCheckerAdded) {
                    throw new CertPathValidatorException(
                        "Only one PKIXRevocationChecker can be specified");
                }
                // if it's our own, initialize it
                if (checker instanceof RevocationChecker) {
                    ((RevocationChecker)checker).init(anchor, buildParams);
                }
                ((PKIXRevocationChecker)checker).init(false);
                revCheckerAdded = true;
            }
        }

        // only create a RevocationChecker if revocation is enabled and
        // a PKIXRevocationChecker has not already been added
        if (buildParams.revocationEnabled() && !revCheckerAdded) {
            revChecker = new RevocationChecker(anchor, buildParams);
            revChecker.init(false);
        }

        init = false;
    }
767959
public void addKeyStoreToMap(String keyStoreName, WSKeyStore ks) throws Exception {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(tc, "addKeyStoreToMap: " + keyStoreName + ", ks=" + ks);

        if (keyStoreMap.containsKey(keyStoreName))
            keyStoreMap.remove(keyStoreName);
        keyStoreMap.put(keyStoreName, ks);

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.exit(tc, "addKeyStoreToMap");
    }
1266648
public static CertStore createCertStore(TrustedCertificates tc) throws Exception {

        CertStore store = null;
        if (tc == null) {
            String caCertPattern = "file:" + CoGProperties.getDefault().getCaCertLocations() + "/*.0";
            store = Stores.getCACertStore(caCertPattern);
        } else {
            SimpleMemoryCertStoreParams params = new SimpleMemoryCertStoreParams(tc.getCertificates(), null);
            params.setCerts(tc.getCertificates());
            store = CertStore.getInstance(SimpleMemoryProvider.CERTSTORE_TYPE, params, SimpleMemoryProvider.PROVIDER_NAME);
        }
        return store;
    }
1077956
public void validate( KeyStore keyStore ) throws CertificateException
{
    try
    {
        Enumeration<String> aliases = keyStore.aliases();
        
        for ( ; aliases.hasMoreElements(); )
        {
            String alias = aliases.nextElement();
            
            validate(keyStore,alias);
        }
        
    }
    catch ( KeyStoreException kse )
    {
        throw new CertificateException("Unable to retrieve aliases from keystore", kse);
    }
}
220363
public void checkKeyStore() {
        if (sslContext != null)
            return; //nothing to check if using preconfigured context
        
        if (keyStoreInputStream == null &&
	    sslConfig.getKeyStorePath() == null) {
            throw new IllegalStateException("SSL doesn't have a valid keystore");
        }
        // if the keystore has been configured but there is no
        // truststore configured, use the keystore as the truststore
        if (trustStoreInputStream == null && sslConfig.getTrustStorePath() == null) {
            trustStoreInputStream = keyStoreInputStream;
            sslConfig.setTrustStorePath(sslConfig.getKeyStorePath());
            sslConfig.setTrustStoreType(sslConfig.getKeyStoreType());
            sslConfig.setTrustStoreProvider(sslConfig.getKeyStoreProvider());
            sslConfig.setTrustStorePassword(sslConfig.getKeyStorePassword());
            sslConfig.setTrustManagerFactoryAlgorithm(sslConfig.getKeyManagerFactoryAlgorithm());
        }

        // It's the same stream we cannot read it twice, so read it once in memory
        if (keyStoreInputStream != null && keyStoreInputStream == trustStoreInputStream) {
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
		streamCopy(keyStoreInputStream, baos, null, false);
                keyStoreInputStream.close();
                keyStoreInputStream = new ByteArrayInputStream(baos.toByteArray());
                trustStoreInputStream = new ByteArrayInputStream(baos.toByteArray());
            } catch (Exception ex) {
                throw new IllegalStateException(ex);
            }
        }
    }
870990
private static SSLContextBuilder loadTrustMaterial(SSLContextBuilder builder, final File file,
            final char[] tsp, final TrustStrategy trustStrategy)
                    throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
        Args.notNull(file, "Truststore file"); //$NON-NLS-1$
        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        final FileInputStream instream = new FileInputStream(file);
        try {
            trustStore.load(instream, tsp);
        } finally {
            instream.close();
        }
        return builder.loadTrustMaterial(trustStore, trustStrategy);
    }
400898
private static void setupSsl(Configuration conf) {
    Configuration sslConf = new Configuration(false);
    sslConf.addResource(conf.get("dfs.https.client.keystore.resource",
        "ssl-client.xml"));
    System.setProperty("javax.net.ssl.trustStore", sslConf.get(
        "ssl.client.truststore.location", ""));
    System.setProperty("javax.net.ssl.trustStorePassword", sslConf.get(
        "ssl.client.truststore.password", ""));
    System.setProperty("javax.net.ssl.trustStoreType", sslConf.get(
        "ssl.client.truststore.type", "jks"));
    System.setProperty("javax.net.ssl.keyStore", sslConf.get(
        "ssl.client.keystore.location", ""));
    System.setProperty("javax.net.ssl.keyStorePassword", sslConf.get(
        "ssl.client.keystore.password", ""));
    System.setProperty("javax.net.ssl.keyPassword", sslConf.get(
        "ssl.client.keystore.keypassword", ""));
    System.setProperty("javax.net.ssl.keyStoreType", sslConf.get(
        "ssl.client.keystore.type", "jks"));
  }
979858
def add_cert(self, cert):
        
        if not isinstance(cert, X509):
            raise TypeError("cert should be X509")
        libcrypto.X509_STORE_add_cert(self.store, cert.cert)
377030
public static synchronized KeyStore getCertificateTrustStore()
      throws IOException, GeneralSecurityException {
    if (certTrustStore == null) {
      certTrustStore = SecurityUtils.getJavaKeyStore();
      InputStream keyStoreStream = GoogleUtils.class.getResourceAsStream("google.jks");
      SecurityUtils.loadKeyStore(certTrustStore, keyStoreStream, "notasecret");
    }
    return certTrustStore;
  }
424732
protected function wizardAddStore()
    {
        $this->validatePrompt('name', $this->text('Name'), 'store');
        $this->validatePrompt('domain', $this->text('Domain or IP'), 'store');
        $this->validatePrompt('basepath', $this->text('Path'), 'store', '');
        $this->validatePrompt('status', $this->text('Status'), 'store', 0);
        $this->setSubmittedJson('data');

        $this->validateComponent('store');
        $this->addStore();
    }
36844
public void addStoreDefinition(StoreDefinition storeDef) {
        // acquire write lock
        writeLock.lock();

        try {
            // Check if store already exists
            if(this.storeNames.contains(storeDef.getName())) {
                throw new VoldemortException("Store already exists !");
            }

            // Check for backwards compatibility
            StoreDefinitionUtils.validateSchemaAsNeeded(storeDef);

            // Otherwise add to the STORES directory
            StoreDefinitionsMapper mapper = new StoreDefinitionsMapper();
            String storeDefStr = mapper.writeStore(storeDef);
            Versioned<String> versionedValueStr = new Versioned<String>(storeDefStr);
            this.storeDefinitionsStorageEngine.put(storeDef.getName(), versionedValueStr, null);

            // Update the metadata cache
            this.metadataCache.put(storeDef.getName(), new Versioned<Object>(storeDefStr));

            // Re-initialize the store definitions. This is primarily required
            // to re-create the value for key: 'stores.xml'. This is necessary
            // for backwards compatibility.
            initStoreDefinitions(null);

            updateRoutingStrategies(getCluster(), getStoreDefList());
        } finally {
            writeLock.unlock();
        }
    }
709042
public static KeyStore load(InputStream in, char[] password) {

        try {
            KeyStore myTrustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            myTrustStore.load(in, password);
            return myTrustStore;
        } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException | IOException e) {
            throw new TrustManagerLoadFailedException(e);
        } finally {
            Closeables.closeQuietly(in);
        }
    }
770752
public void installSmartCardTrustAnchor(String cert) throws HostConfigFault, RuntimeFault, RemoteException {
        getVimService().installSmartCardTrustAnchor(getMOR(), cert);
    }
504480
public void validate(KeyStore keyStore, Certificate cert) throws CertificateException
{
    Certificate[] certChain = null;
    
    if (cert != null && cert instanceof X509Certificate)
    {
        ((X509Certificate)cert).checkValidity();
        
        String certAlias = null;
        try
        {
            if (keyStore == null)
            {
                throw new InvalidParameterException("Keystore cannot be null");
            }

            certAlias = keyStore.getCertificateAlias((X509Certificate)cert);
            if (certAlias == null)
            {
                certAlias = "JETTY" + String.format("%016X",__aliasCount.incrementAndGet());
                keyStore.setCertificateEntry(certAlias, cert);
            }
            
            certChain = keyStore.getCertificateChain(certAlias);
            if (certChain == null || certChain.length == 0)
            {
                throw new IllegalStateException("Unable to retrieve certificate chain");
            }
        }
        catch (KeyStoreException kse)
        {
            LOG.error("Error while valid keystore", kse);
            throw new CertificateException("Unable to validate certificate" +
                    (certAlias == null ? "":" for alias [" +certAlias + "]") + ": " + kse.getMessage(), kse);
        }
        
        validate(certChain);
    } 
}
82759
@SuppressWarnings("unchecked")
	public static SSLContext createSSLContext(String trustedNamesGroupKey) throws IOException {
        SSLContext sslContext = null;
        KeyManager[] keyManagers = null;
        Map<String, Object> tlsMap = (Map<String, Object>)ClientConfig.get().getMappedConfig().get(TLS);
        if(tlsMap != null) {
            try {
                // load key store for client certificate if two way ssl is used.
                Boolean loadKeyStore = (Boolean) tlsMap.get(LOAD_KEY_STORE);
                if (loadKeyStore != null && loadKeyStore) {
                    String keyStoreName = (String)tlsMap.get(KEY_STORE);
                    String keyStorePass = (String)ClientConfig.get().getSecretConfig().get(SecretConstants.CLIENT_KEYSTORE_PASS);
                    String keyPass = (String)ClientConfig.get().getSecretConfig().get(SecretConstants.CLIENT_KEY_PASS);
                    KeyStore keyStore = loadKeyStore(keyStoreName, keyStorePass.toCharArray());
                    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    keyManagerFactory.init(keyStore, keyPass.toCharArray());
                    keyManagers = keyManagerFactory.getKeyManagers();
                }
            } catch (NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException e) {
                throw new IOException("Unable to initialise KeyManager[]", e);
            }

            TrustManager[] trustManagers = null;
            try {
                // load trust store, this is the server public key certificate
                // first check if javax.net.ssl.trustStore system properties is set. It is only necessary if the server
                // certificate doesn't have the entire chain.
                Boolean loadTrustStore = (Boolean) tlsMap.get(LOAD_TRUST_STORE);
                if (loadTrustStore != null && loadTrustStore) {
                    String trustStoreName = System.getProperty(TRUST_STORE_PROPERTY);
                    String trustStorePass = System.getProperty(TRUST_STORE_PASSWORD_PROPERTY);
                    if (trustStoreName != null && trustStorePass != null) {
                        if(logger.isInfoEnabled()) logger.info("Loading trust store from system property at " + Encode.forJava(trustStoreName));
                    } else {
                        trustStoreName = (String) tlsMap.get(TRUST_STORE);
                        trustStorePass = (String)ClientConfig.get().getSecretConfig().get(SecretConstants.CLIENT_TRUSTSTORE_PASS);
                        if(logger.isInfoEnabled()) logger.info("Loading trust store from config at " + Encode.forJava(trustStoreName));
                    }
                    if (trustStoreName != null && trustStorePass != null) {
                        KeyStore trustStore = loadKeyStore(trustStoreName, trustStorePass.toCharArray());
                        TLSConfig tlsConfig = TLSConfig.create(tlsMap, trustedNamesGroupKey);

                        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                        trustManagerFactory.init(trustStore);
                        trustManagers = ClientX509ExtendedTrustManager.decorate(trustManagerFactory.getTrustManagers(), tlsConfig);
                    }
                }
            } catch (NoSuchAlgorithmException | KeyStoreException e) {
                throw new IOException("Unable to initialise TrustManager[]", e);
            }

            try {
                sslContext = SSLContext.getInstance("TLS");
                sslContext.init(keyManagers, trustManagers, null);
            } catch (NoSuchAlgorithmException | KeyManagementException e) {
                throw new IOException("Unable to create and initialise the SSLContext", e);
            }
        } else {
            logger.error("TLS configuration section is missing in client.yml");
        }

        return sslContext;
    }
183613
@Override
	public void engineSetCertificateEntry(String alias, Certificate certificate)
			throws KeyStoreException {

		if (!(certificate instanceof X509Certificate)) {
			throw new KeyStoreException(
					"Certificate must be instance of X509Certificate");
		}
		File file;
		ResourceTrustAnchor trustAnchor = getCertificateEntry(alias);
		if (trustAnchor != null) {
			file = trustAnchor.getFile();
		} else {
			file = new File(defaultDirectory, alias);
		}
		X509Certificate x509Cert = (X509Certificate) certificate;
		try {
			if(!inMemoryOnly){
				writeCertificate(x509Cert, file);
			}
			ResourceTrustAnchor anchor = new ResourceTrustAnchor(inMemoryOnly,
					new GlobusResource(file.getAbsolutePath()), new TrustAnchor(x509Cert,
							null));
			this.aliasObjectMap.put(alias, anchor);
			this.certFilenameMap.put(x509Cert, alias);
		} catch (ResourceStoreException e) {
			throw new KeyStoreException(e);
		} catch (IOException e) {
			throw new KeyStoreException(e);
		} catch (CertificateEncodingException e) {
			throw new KeyStoreException(e);
		}
	}