Make an SSLConext for this Python version using public or sslca
969588
def __get_ssl_context(cls, sslca=None):
        
        if ((version_info[0] == 2 and (version_info[1] >= 7 and version_info[2] >= 5)) or
                (version_info[0] == 3 and version_info[1] >= 4)):
            logger.debug('SSL method for 2.7.5+ / 3.4+')
            # pylint: disable=no-name-in-module
            from ssl import SSLContext, PROTOCOL_TLSv1_2, CERT_REQUIRED, OP_NO_COMPRESSION
            ctx = SSLContext(PROTOCOL_TLSv1_2)
            ctx.set_ciphers('HIGH:!SSLv3:!TLSv1:!aNULL:@STRENGTH')
            # see CRIME security exploit
            ctx.options |= OP_NO_COMPRESSION
            # the following options are used to verify the identity of the broker
            if sslca:
                ctx.load_verify_locations(sslca)
                ctx.verify_mode = CERT_REQUIRED
                ctx.check_hostname = False
            else:
                # Verify public certifcates if sslca is None (default)
                from ssl import Purpose  # pylint: disable=no-name-in-module
                ctx.load_default_certs(purpose=Purpose.SERVER_AUTH)
                ctx.verify_mode = CERT_REQUIRED
                ctx.check_hostname = True

        elif version_info[0] == 3 and version_info[1] < 4:
            logger.debug('Using SSL method for 3.2+, < 3.4')
            # pylint: disable=no-name-in-module
            from ssl import SSLContext, CERT_REQUIRED, PROTOCOL_SSLv23, OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_TLSv1
            ctx = SSLContext(PROTOCOL_SSLv23)
            ctx.options |= (OP_NO_SSLv2 | OP_NO_SSLv3 | OP_NO_TLSv1)
            ctx.set_ciphers('HIGH:!SSLv3:!TLSv1:!aNULL:@STRENGTH')
            # the following options are used to verify the identity of the broker
            if sslca:
                ctx.load_verify_locations(sslca)
                ctx.verify_mode = CERT_REQUIRED
            else:
                # Verify public certifcates if sslca is None (default)
                ctx.set_default_verify_paths()
                ctx.verify_mode = CERT_REQUIRED

        else:
            raise Exception("Unsupported Python version %s" % '.'.join(str(item) for item in version_info[:3]))

        return ctx
311348
private SslContext buildSslContext() throws Exception {
        keyAndCertificateFactory().buildAndSaveCertificates();

        return SslContextBuilder.forServer(
            keyAndCertificateFactory().mockServerPrivateKey(),
            // do we need this password??
            ConfigurationProperties.javaKeyStorePassword(),
            new X509Certificate[]{
                keyAndCertificateFactory().mockServerX509Certificate(),
                keyAndCertificateFactory().mockServerCertificateAuthorityX509Certificate()
            }
        ).build();
    }
875577
def _init_ssl(self):
        

        if not have_openssl:
            raise ImportError('SSL sockets have been disabled due to missing requirement: pyopenssl.')

        try:
            ctx = SSL.Context(SSL.TLSv1_METHOD)

            if isinstance(self.ssl_key, crypto.PKey):
                ctx.use_privatekey(self.ssl_key)
            else:
                ctx.use_privatekey_file(self.ssl_key)

            if isinstance(self.ssl_certificate, crypto.X509):
                ctx.use_certificate(self.ssl_certificate)
            else:
                ctx.use_certificate_file(self.ssl_certificate)

            if isinstance(self.ssl_ca, crypto.X509):
                store = ctx.get_cert_store()
                store.add_cert(self.ssl_ca)
            else:
                ctx.load_verify_locations(self.ssl_ca, None)

            verify_method = SSL.VERIFY_PEER
            if (self._ssl_allow_self_signed):
                verify_method = SSL.VERIFY_NONE

            ctx.set_verify(verify_method, self._verify_ssl_callback)

            self._device = SSL.Connection(ctx, self._device)

        except SSL.Error as err:
            raise CommError('Error setting up SSL connection.', err)
71167
def cli(env, identifier):
    """"""

    manager = SoftLayer.SSLManager(env.client)
    certificate = manager.get_certificate(identifier)

    write_cert(certificate['commonName'] + '.crt', certificate['certificate'])
    write_cert(certificate['commonName'] + '.key', certificate['privateKey'])

    if 'intermediateCertificate' in certificate:
        write_cert(certificate['commonName'] + '.icc',
                   certificate['intermediateCertificate'])

    if 'certificateSigningRequest' in certificate:
        write_cert(certificate['commonName'] + '.csr',
                   certificate['certificateSigningRequest'])
178775
def inject_into_urllib3():
    ''

    _validate_dependencies_met()

    util.ssl_.SSLContext = PyOpenSSLContext
    util.HAS_SNI = HAS_SNI
    util.ssl_.HAS_SNI = HAS_SNI
    util.IS_PYOPENSSL = True
    util.ssl_.IS_PYOPENSSL = True
1091292
def SSLCertificates(self):
        
        url = self._url + "/SSLCertificate"
        params = {"f" : "json"}
        return self._post(url=url,
                          param_dict=params,
                          proxy_url=self._proxy_url,
                          proxy_port=self._proxy_port)
71622
def _get_ssl_sock(self):
        """"""
        assert self.scheme == u"https", self
        raw_connection = self.url_connection.raw._connection
        if raw_connection.sock is None:
            # sometimes the socket is not yet connected
            # see https://github.com/kennethreitz/requests/issues/1966
            raw_connection.connect()
        return raw_connection.sock
306632
def _ssl_wrap_socket(self, sock):
        
        context = self._parameters['ssl_options'].get('context')
        if context is not None:
            hostname = self._parameters['ssl_options'].get('server_hostname')
            return context.wrap_socket(
                sock, do_handshake_on_connect=True,
                server_hostname=hostname
            )
        if 'ssl_version' not in self._parameters['ssl_options']:
            self._parameters['ssl_options']['ssl_version'] = (
                compatibility.DEFAULT_SSL_VERSION
            )
        return ssl.wrap_socket(
            sock, do_handshake_on_connect=True,
            **self._parameters['ssl_options']
        )
1102261
def create_ssl_context():
        """"""
        ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
        ssl_context.check_hostname = False
        ssl_context.verify_mode = ssl.CERT_NONE
        return ssl_context
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;
    }
582233
def create_self_signed_cert(bits, cn, comment)
      rsa = OpenSSL::PKey::RSA.new(bits){|p, n|
        case p
        when 0; $stderr.putc "."  # BN_generate_prime
        when 1; $stderr.putc "+"  # BN_generate_prime
        when 2; $stderr.putc "*"  # searching good prime,
                                  # n = #of try,
                                  # but also data from BN_generate_prime
        when 3; $stderr.putc "\n" # found good prime, n==0 - p, n==1 - q,
                                  # but also data from BN_generate_prime
        else;   $stderr.putc "*"  # BN_generate_prime
        end
      }
      cert = OpenSSL::X509::Certificate.new
      cert.version = 2
      cert.serial = 1
      name = OpenSSL::X509::Name.new(cn)
      cert.subject = name
      cert.issuer = name
      cert.not_before = Time.now
      cert.not_after = Time.now + (365*24*60*60)
      cert.public_key = rsa.public_key

      ef = OpenSSL::X509::ExtensionFactory.new(nil,cert)
      ef.issuer_certificate = cert
      cert.extensions = [
        ef.create_extension("basicConstraints","CA:FALSE"),
        ef.create_extension("keyUsage", "keyEncipherment"),
        ef.create_extension("subjectKeyIdentifier", "hash"),
        ef.create_extension("extendedKeyUsage", "serverAuth"),
        ef.create_extension("nsComment", comment),
      ]
      aki = ef.create_extension("authorityKeyIdentifier",
                                "keyid:always,issuer:always")
      cert.add_extension(aki)
      cert.sign(rsa, OpenSSL::Digest::SHA1.new)

      return [ cert, rsa ]
    end
1192599
def authenticate(self):
        '''
        
        '''
        log.debug('Authenticate to %s:%d, using the certificate %s',
                  self.address, self.port, self.certificate)
        if ':' in self.address:
            skt_ver = socket.AF_INET6
        else:
            skt_ver = socket.AF_INET
        skt = socket.socket(skt_ver, socket.SOCK_STREAM)
        self.ssl_skt = ssl.wrap_socket(skt,
                                       ca_certs=self.certificate,
                                       cert_reqs=ssl.CERT_REQUIRED)
        try:
            self.ssl_skt.connect((self.address, self.port))
            self.auth_try_id = 0
        except socket.error as err:
            log.error('Unable to open the SSL socket.')
            self.auth_try_id += 1
            if not self.max_try or self.auth_try_id < self.max_try:
                log.error('Trying to authenticate again in %d seconds', self.timeout)
                time.sleep(self.timeout)
                self.authenticate()
            log.critical('Giving up, unable to authenticate to %s:%d using the certificate %s',
                         self.address, self.port, self.certificate)
            raise ClientConnectException(err)

        # Explicit INIT
        self.ssl_skt.write(defaults.MAGIC_REQ)
        # Receive the private key
        private_key = self.ssl_skt.recv(defaults.BUFFER_SIZE)
        # Send back explicit ACK
        self.ssl_skt.write(defaults.MAGIC_ACK)
        # Read the hex of the verification key
        verify_key_hex = self.ssl_skt.recv(defaults.BUFFER_SIZE)
        # Send back explicit ACK
        self.ssl_skt.write(defaults.MAGIC_ACK)
        self.priv_key = nacl.secret.SecretBox(private_key)
        self.verify_key = nacl.signing.VerifyKey(verify_key_hex, encoder=nacl.encoding.HexEncoder)
543465
async def create_websocket(url: str,
                           ssl: Optional[SSLContext] = None,
                           headers: Optional[list] = None,
                           subprotocols: Optional[list] = None):
    
    url = yarl.URL(url)
    args = {}
    if headers:
        args["headers"] = headers

    # automatically use ssl if it's websocket secure
    if ssl is None:
        ssl = url.scheme == "wss"
    if ssl:
        if ssl is True:
            ssl = SSLContext()
        args["ssl_context"] = ssl
        args["autostart_tls"] = True
        args["tls_standard_compatible"] = False

    addr = (url.host, int(url.port))
    ws = Websocket()
    await ws.__ainit__(
        addr=addr, path=url.path_qs, subprotocols=subprotocols, **args)
    return ws
78571
public static SSLContext acceptingSslContext() {
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, TRUST_MANAGERS, new SecureRandom());
            return sslContext;

        } catch (NoSuchAlgorithmException | KeyManagementException ex) {
            throw new RuntimeException("Unable to create issue-ignoring SSLContext: " + ex.getMessage(), ex);
        }
    }
634413
@Deprecated
    public B sslContext(
            SessionProtocol protocol,
            File keyCertChainFile, File keyFile, @Nullable String keyPassword) throws SSLException {

        if (requireNonNull(protocol, "protocol") != SessionProtocol.HTTPS) {
            throw new IllegalArgumentException("unsupported protocol: " + protocol);
        }

        return tls(keyCertChainFile, keyFile, keyPassword);
    }
1155012
public SslContext build() throws SSLException {
        if (forServer) {
            return SslContext.newServerContextInternal(provider, sslContextProvider, trustCertCollection,
                trustManagerFactory, keyCertChain, key, keyPassword, keyManagerFactory,
                ciphers, cipherFilter, apn, sessionCacheSize, sessionTimeout, clientAuth, protocols, startTls,
                enableOcsp);
        } else {
            return SslContext.newClientContextInternal(provider, sslContextProvider, trustCertCollection,
                trustManagerFactory, keyCertChain, key, keyPassword, keyManagerFactory,
                ciphers, cipherFilter, apn, protocols, sessionCacheSize, sessionTimeout, enableOcsp);
        }
    }
447459
def vserver_sslcert_add(v_name, sc_name, **connection_args):
    '''
    
    '''
    ret = True
    if vserver_sslcert_exists(v_name, sc_name, **connection_args):
        return False
    nitro = _connect(**connection_args)
    if nitro is None:
        return False
    sslcert = NSSSLVServerSSLCertKeyBinding()
    sslcert.set_vservername(v_name)
    sslcert.set_certkeyname(sc_name)
    try:
        NSSSLVServerSSLCertKeyBinding.add(nitro, sslcert)
    except NSNitroError as error:
        log.debug('netscaler module error - NSSSLVServerSSLCertKeyBinding.add() failed: %s', error)
        ret = False
    _disconnect(nitro)
    return ret