Explicitely adds certificate to set of trusted in the store
        @param cert - X509 object to add
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)
937106
@Override
    void addCertToPath(X509Certificate cert,
                       LinkedList<X509Certificate> certPathList)
    {
        certPathList.addFirst(cert);
    }
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;
    }
689109
public static void saveX509Cert( Certificate[] certs, File certFile ) throws GeneralSecurityException, IOException
    {
        try ( BufferedWriter writer = new BufferedWriter( new FileWriter( certFile ) ) )
        {
            for ( Certificate cert : certs )
            {
                String certStr = Base64.getEncoder().encodeToString( cert.getEncoded() ).replaceAll( "(.{64})", "$1\n" );

                writer.write( BEGIN_CERT );
                writer.newLine();

                writer.write( certStr );
                writer.newLine();

                writer.write( END_CERT );
                writer.newLine();
            }
        }
    }
482251
private void doCustomServerIdentityCheck(X509Certificate cert) throws CertificateException{
		if (EndpointIdentificationAlgorithm.APIS == identityAlg) {
			APINameChecker.verifyAndThrow(trustedNameSet, cert);
		}
	}
1175192
def _add_default_options(self) -> None:
        
        # Updating the trust stores
        update_stores_group = OptionGroup(self._parser, 'Trust stores options', '')
        update_stores_group.add_option(
            '--update_trust_stores',
            help='Update the default trust stores used by SSLyze. The latest stores will be downloaded from '
                 'https://github.com/nabla-c0d3/trust_stores_observatory. This option is meant to be used separately, '
                 'and will silence any other command line option supplied to SSLyze.',
            dest='update_trust_stores',
            action='store_true',
        )
        self._parser.add_option_group(update_stores_group)

        # Client certificate options
        clientcert_group = OptionGroup(self._parser, 'Client certificate options', '')
        clientcert_group.add_option(
            '--cert',
            help='Client certificate chain filename. The certificates must be in PEM format and must be sorted '
                 'starting with the subject\'s client certificate, followed by intermediate CA certificates if '
                 'applicable.',
            dest='cert'
        )
        clientcert_group.add_option(
            '--key',
            help='Client private key filename.',
            dest='key'
        )
        clientcert_group.add_option(
            '--keyform',
            help='Client private key format. DER or PEM (default).',
            dest='keyform',
            default='PEM'
        )
        clientcert_group.add_option(
            '--pass',
            help='Client private key passphrase.',
            dest='keypass',
            default=''
        )
        self._parser.add_option_group(clientcert_group)

        # Input / output
        output_group = OptionGroup(self._parser, 'Input and output options', '')
        # XML output
        output_group.add_option(
            '--xml_out',
            help='Write the scan results as an XML document to the file XML_FILE. If XML_FILE is set to "-", the XML '
                 'output will instead be printed to stdout. The corresponding XML Schema Definition is available at '
                 './docs/xml_out.xsd',
            dest='xml_file',
            default=None
        )
        # JSON output
        output_group.add_option(
            '--json_out',
            help='Write the scan results as a JSON document to the file JSON_FILE. If JSON_FILE is set to "-", the '
                 'JSON output will instead be printed to stdout. The resulting JSON file is a serialized version of '
                 'the ScanResult objects described in SSLyze\'s Python API: the nodes and attributes will be the same. '
                 'See https://nabla-c0d3.github.io/sslyze/documentation/available-scan-commands.html for more details.',
            dest='json_file',
            default=None
        )
        # Read targets from input file
        output_group.add_option(
            '--targets_in',
            help='Read the list of targets to scan from the file TARGETS_IN. It should contain one host:port per '
                 'line.',
            dest='targets_in',
            default=None
        )
        # No text output
        output_group.add_option(
            '--quiet',
            action='store_true',
            dest='quiet',
            help='Do not output anything to stdout; useful when using --xml_out or --json_out.'
        )
        self._parser.add_option_group(output_group)

        # Connectivity option group
        connect_group = OptionGroup(self._parser, 'Connectivity options', '')
        # Connection speed
        connect_group.add_option(
            '--slow_connection',
            help='Greatly reduce the number of concurrent connections initiated by SSLyze. This will make the scans '
                 'slower but more reliable if the connection between your host and the server is slow, or if the '
                 'server cannot handle many concurrent connections. Enable this option if you are getting a lot of '
                 'timeouts or errors.',
            action='store_true',
            dest='slow_connection',
        )
        # HTTP CONNECT Proxy
        connect_group.add_option(
            '--https_tunnel',
            help='Tunnel all traffic to the target server(s) through an HTTP CONNECT proxy. HTTP_TUNNEL should be the '
                 'proxy\'s URL: \'http://USER:PW@HOST:PORT/\'. For proxies requiring authentication, only Basic '
                 'Authentication is supported.',
            dest='https_tunnel',
            default=None
        )
        # STARTTLS
        connect_group.add_option(
            '--starttls',
            help='Perform a StartTLS handshake when connecting to the target server(s). '
                 '{}'.format(self.START_TLS_USAGE),
            dest='starttls',
            default=None
        )
        connect_group.add_option(
            '--xmpp_to',
            help='Optional setting for STARTTLS XMPP. XMPP_TO should be the hostname to be put in the \'to\' '
                 'attribute of the XMPP stream. Default is the server\'s hostname.',
            dest='xmpp_to',
            default=None
        )
        # Server Name Indication
        connect_group.add_option(
            '--sni',
            help='Use Server Name Indication to specify the hostname to connect to.  Will only affect TLS 1.0+ '
                 'connections.',
            dest='sni',
            default=None
        )
        self._parser.add_option_group(connect_group)
1064754
private static List<Vertex> addVertices(Collection<X509Certificate> certs,
                                            List<List<Vertex>> adjList)
    {
        List<Vertex> l = adjList.get(adjList.size() - 1);

        for (X509Certificate cert : certs) {
            Vertex v = new Vertex(cert);
            l.add(v);
        }

        return l;
    }
588806
private static void disableSSLCertificateChecking() {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                // Not implemented
            }

            @Override
            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                // Not implemented
            }
        } };

        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());

            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

            // Create all-trusting host name verifier
            HostnameVerifier allHostsValid = new HostnameVerifier() {
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };

            // Install the all-trusting host verifier
            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        } catch (KeyManagementException e) {
            throw new IllegalArgumentException("Disabling SSL certificate failed: " + e,e);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException("Disabling SSL certificate failed: " + e,e);
        }
    }
212793
public CertifiedPublicKey convert(X509CertificateHolder cert)
    {
        if (cert == null) {
            return null;
        }
        return new BcX509CertifiedPublicKey(cert, this.factory);
    }
144621
public static PKIXCertPathBuilderResult verifyChain(X509Certificate testCert, X509Certificate... additionalCerts) {
        try {
            // Check for self-signed certificate
            if (isSelfSigned(testCert)) {
                throw new RuntimeException("The certificate is self-signed.  Nothing to verify.");
            }

            // Prepare a set of all certificates
            // chain builder must have all certs, including cert to validate
            // http://stackoverflow.com/a/10788392
            Set<X509Certificate> certs = new HashSet<X509Certificate>();
            certs.add(testCert);
            certs.addAll(Arrays.asList(additionalCerts));

            // Attempt to build the certification chain and verify it
            // Create the selector that specifies the starting certificate
            X509CertSelector selector = new X509CertSelector();
            selector.setCertificate(testCert);

            // Create the trust anchors (set of root CA certificates)
            Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>();
            for (X509Certificate cert : additionalCerts) {
                if (isSelfSigned(cert)) {
                    trustAnchors.add(new TrustAnchor(cert, null));
                }
            }

            // Configure the PKIX certificate builder
            PKIXBuilderParameters pkixParams = new PKIXBuilderParameters(trustAnchors, selector);
            pkixParams.setRevocationEnabled(false);
            pkixParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs), BC));

            // Build and verify the certification chain
            CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", BC);
            PKIXCertPathBuilderResult verifiedCertChain = (PKIXCertPathBuilderResult) builder.build(pkixParams);

            // The chain is built and verified
            return verifiedCertChain;
        } catch (CertPathBuilderException e) {
            throw new RuntimeException("Error building certification path: " + testCert.getSubjectX500Principal(), e);
        } catch (Exception e) {
            throw new RuntimeException("Error verifying the certificate: " + testCert.getSubjectX500Principal(), e);
        }
    }
1310163
X509Certificate selectCertificate(final CertStore store,
			final Collection<X509CertSelector> selectors) throws CertStoreException {
		for (CertSelector selector : selectors) {
			LOGGER.debug("Selecting certificate using {}", selector);
			Collection<? extends Certificate> certs = store
					.getCertificates(selector);
			if (certs.size() > 0) {
				LOGGER.debug("Selected {} certificate(s) using {}",
						certs.size(), selector);
				return (X509Certificate) certs.iterator().next();
			} else {
				LOGGER.debug("No certificates selected");
			}
		}
		return (X509Certificate) store.getCertificates(null).iterator().next();
	}
1329636
public void updateState(X509Certificate cert)
        throws CertificateException, IOException, CertPathValidatorException {

        if (cert == null) {
            return;
        }

        /* update subject DN */
        subjectDN = cert.getSubjectX500Principal();

        /* check for key needing to inherit alg parameters */
        X509CertImpl icert = X509CertImpl.toImpl(cert);
        PublicKey newKey = cert.getPublicKey();
        if (PKIX.isDSAPublicKeyWithoutParams(newKey)) {
            newKey = BasicChecker.makeInheritedParamsKey(newKey, pubKey);
        }

        /* update subject public key */
        pubKey = newKey;

        /*
         * if this is a trusted cert (init == true), then we
         * don't update any of the remaining fields
         */
        if (init) {
            init = false;
            return;
        }

        /* update subject key identifier */
        subjKeyId = icert.getSubjectKeyIdentifierExtension();

        /* update crlSign */
        crlSign = RevocationChecker.certCanSignCrl(cert);

        /* update current name constraints */
        if (nc != null) {
            nc.merge(icert.getNameConstraintsExtension());
        } else {
            nc = icert.getNameConstraintsExtension();
            if (nc != null) {
                // Make sure we do a clone here, because we're probably
                // going to modify this object later and we don't want to
                // be sharing it with a Certificate object!
                nc = (NameConstraintsExtension) nc.clone();
            }
        }

        /* update policy state variables */
        explicitPolicy =
            PolicyChecker.mergeExplicitPolicy(explicitPolicy, icert, false);
        policyMapping =
            PolicyChecker.mergePolicyMapping(policyMapping, icert);
        inhibitAnyPolicy =
            PolicyChecker.mergeInhibitAnyPolicy(inhibitAnyPolicy, icert);
        certIndex++;

        /*
         * Update remaining CA certs
         */
        remainingCACerts =
            ConstraintsChecker.mergeBasicConstraints(cert, remainingCACerts);

        init = false;
    }
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");
        }
    }
1357737
public static void saveX509Cert( Certificate cert, File certFile ) throws GeneralSecurityException, IOException
    {
        saveX509Cert( new Certificate[]{cert}, certFile );
    }
1080656
@Override
    public void updateState(X509Certificate cert)
        throws CertificateException, IOException, CertPathValidatorException {

        if (cert == null)
            return;

        X509CertImpl icert = X509CertImpl.toImpl(cert);

        /* see if certificate key has null parameters */
        if (PKIX.isDSAPublicKeyWithoutParams(icert.getPublicKey())) {
            keyParamsNeededFlag = true;
        }

        /* update certificate */
        this.cert = icert;

        /* update issuer DN */
        issuerDN = cert.getIssuerX500Principal();

        if (!X509CertImpl.isSelfIssued(cert)) {

            /*
             * update traversedCACerts only if this is a non-self-issued
             * intermediate CA cert
             */
            if (!init && cert.getBasicConstraints() != -1) {
                traversedCACerts++;
            }
        }

        /* update subjectNamesTraversed only if this is the EE cert or if
           this cert is not self-issued */
        if (init || !X509CertImpl.isSelfIssued(cert)){
            X500Principal subjName = cert.getSubjectX500Principal();
            subjectNamesTraversed.add(X500Name.asX500Name(subjName));

            try {
                SubjectAlternativeNameExtension subjAltNameExt
                    = icert.getSubjectAlternativeNameExtension();
                if (subjAltNameExt != null) {
                    GeneralNames gNames = subjAltNameExt.get(
                            SubjectAlternativeNameExtension.SUBJECT_NAME);
                    for (GeneralName gName : gNames.names()) {
                        subjectNamesTraversed.add(gName.getName());
                    }
                }
            } catch (IOException e) {
                if (debug != null) {
                    debug.println("ForwardState.updateState() unexpected "
                        + "exception");
                    e.printStackTrace();
                }
                throw new CertPathValidatorException(e);
            }
        }

        init = false;
    }
695350
public void setTrustStore(String trustStore, String trustPass, String trustManagerType, String trustStoreType) 
    {
        if((trustStore == null) || (trustPass == null))
        {
            this.trustStore =  System.getProperty("javax.net.ssl.trustStore");
            this.trustPass =  System.getProperty("javax.net.ssl.trustStorePassword");
        }
        else
        {
            this.trustStore = trustStore;
            this.trustPass = trustPass;
        }
 
        if (trustManagerType != null) {
            this.trustManagerType = trustManagerType;
        }
        if (trustStoreType != null) {
            this.trustStoreType = trustStoreType;
        }
        isTrustStoreSet = (trustStore != null) && (trustPass != null);
    }
245539
public static base_response add(nitro_service client, sslcertkey resource) throws Exception {
		sslcertkey addresource = new sslcertkey();
		addresource.certkey = resource.certkey;
		addresource.cert = resource.cert;
		addresource.key = resource.key;
		addresource.password = resource.password;
		addresource.fipskey = resource.fipskey;
		addresource.inform = resource.inform;
		addresource.passplain = resource.passplain;
		addresource.expirymonitor = resource.expirymonitor;
		addresource.notificationperiod = resource.notificationperiod;
		addresource.bundle = resource.bundle;
		return addresource.add_resource(client);
	}