Initialize the SSL handshake.

@throws SSLException
8410
public void init() throws SSLException {
        if (sslEngine != null) {
            // We already have a SSL engine created, no need to create a new one
            return;
        }

        InetSocketAddress peer = (InetSocketAddress) session
                .getAttribute(SslFilter.PEER_ADDRESS);
        
        // Create the SSL engine here
        if (peer == null) {
            sslEngine = sslContext.createSSLEngine();
        } else {
            sslEngine = sslContext.createSSLEngine(peer.getHostName(), peer.getPort());
        }
        
        // Initialize the engine in client mode if necessary
        sslEngine.setUseClientMode(parent.isUseClientMode());

        // Initialize the different SslEngine modes
        if (parent.isWantClientAuth()) {
            sslEngine.setWantClientAuth(true);
        }

        if (parent.isNeedClientAuth()) {
            sslEngine.setNeedClientAuth(true);
        }

        if (parent.getEnabledCipherSuites() != null) {
            sslEngine.setEnabledCipherSuites(parent.getEnabledCipherSuites());
        }

        if (parent.getEnabledProtocols() != null) {
            sslEngine.setEnabledProtocols(parent.getEnabledProtocols());
        }

        // TODO : we may not need to call this method...
        sslEngine.beginHandshake();
        
        
        handshakeStatus = sslEngine.getHandshakeStatus();

        handshakeComplete = false;
        initialHandshakeComplete = false;
        writingEncryptedData = false;
    }
770216
synchronized public void setSSLParameters(SSLParameters params) {
        super.setSSLParameters(params);

        // the super implementation does not handle the following parameters
        identificationProtocol = params.getEndpointIdentificationAlgorithm();
        algorithmConstraints = params.getAlgorithmConstraints();
        if ((handshaker != null) && !handshaker.started()) {
            handshaker.setIdentificationProtocol(identificationProtocol);
            handshaker.setAlgorithmConstraints(algorithmConstraints);
        }
    }
464140
private void init() throws Exception {
        if (sslContext == null) {
            if (keyStoreInputStream == null && sslConfig.getKeyStorePath() == null &&
		trustStoreInputStream == null && sslConfig.getTrustStorePath() == null) {
                TrustManager[] trust_managers = null;
                if (sslConfig.isTrustAll()) {
                    logger.debug("No keystore or trust store configured.  ACCEPTING UNTRUSTED CERTIFICATES!!!!!");
                    // Create a trust manager that does not validate certificate chains
                    TrustManager trustAllCerts = new X509TrustManager() {
			    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
				return null;
			    }
			    public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
			    }

			    public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
			    }
			};
                    trust_managers = new TrustManager[] { trustAllCerts };
                }
                
                SecureRandom secureRandom = (sslConfig.getSecureRandomAlgorithm() == null)?null:
		    SecureRandom.getInstance(sslConfig.getSecureRandomAlgorithm());
                sslContext = SSLContext.getInstance(sslConfig.getProtocol());
                sslContext.init(null, trust_managers, secureRandom);
            } else {
                // verify that keystore and truststore
                // parameters are set up correctly               
                checkKeyStore();

                KeyStore keyStore = loadKeyStore();
                KeyStore trustStore = loadTrustStore();

                Collection<? extends CRL> crls = loadCRL(sslConfig.getCrlPath());

                if (sslConfig.isValidateCerts() && keyStore != null) {
                    if (sslConfig.getCertAlias() == null) {
                        List<String> aliases = Collections.list(keyStore.aliases());
			sslConfig.setCertAlias(aliases.size() == 1 ? aliases.get(0) : null);
                    }

                    Certificate cert = sslConfig.getCertAlias() == null?null:
			keyStore.getCertificate(sslConfig.getCertAlias());
                    if (cert == null) {
                        throw new Exception("No certificate found in the keystore" + (sslConfig.getCertAlias() == null ? "":" for alias " + sslConfig.getCertAlias()));
                    }

                    CertificateValidator validator = new CertificateValidator(trustStore, crls);
                    validator.setMaxCertPathLength(sslConfig.getMaxCertPathLength());
                    validator.setEnableCRLDP(sslConfig.isEnableCRLDP());
                    validator.setEnableOCSP(sslConfig.isEnableOCSP());
                    validator.setOcspResponderURL(sslConfig.getOcspResponderURL());
                    validator.validate(keyStore, cert);
                }

                KeyManager[] keyManagers = getKeyManagers(keyStore);
                TrustManager[] trustManagers = getTrustManagers(trustStore, crls);

                SecureRandom secureRandom = (sslConfig.getSecureRandomAlgorithm() == null)?null:
		    SecureRandom.getInstance(sslConfig.getSecureRandomAlgorithm());
                sslContext = (sslConfig.getProvider() == null)?
		    SSLContext.getInstance(sslConfig.getProtocol()):
		    SSLContext.getInstance(sslConfig.getProtocol(), sslConfig.getProvider());
                sslContext.init(keyManagers, trustManagers, secureRandom);

                SSLEngine engine = newSslEngine();
                
                logger.info("Enabled Protocols {} of {}",
			    Arrays.asList(engine.getEnabledProtocols()),
			    Arrays.asList(engine.getSupportedProtocols()));
		logger.debug("Enabled Ciphers {} of {}",
			     Arrays.asList(engine.getEnabledCipherSuites()),
			     Arrays.asList(engine.getSupportedCipherSuites()));
            }
        }
    }
1146277
void handshakeAlert(byte description) throws SSLProtocolException {
        String message = Alerts.alertDescription(description);

        if (debug != null && Debug.isOn("handshake")) {
            System.out.println("SSL - handshake alert: " + message);
        }
        throw new SSLProtocolException("handshake alert:  " + message);
    }
848783
protected function handshake()
    {
        if (null !== $this->session) {
            return;
        }

        $query = ['use_b64'   => $this->options['use_b64'],
                  'EIO'       => $this->options['version'],
                  'transport' => $this->options['transport']];

        if (isset($this->url['query'])) {
            $query = \array_replace($query, $this->url['query']);
        }

        $context = $this->context;
        $protocol = true === $this->url['secured'] ? 'ssl' : 'http';

        if (!isset($context[$protocol])) {
            $context[$protocol] = [];
        }

        // add customer headers
        if (isset($this->options['headers'])) {
            $headers = isset($context[$protocol]['header']) ? $context[$protocol]['header'] : [];
            $context[$protocol]['header'] = \array_merge($headers, $this->options['headers']);
        }

        $url    = \sprintf(
            '%s://%s:%d/%s/?%s',
            $this->url['scheme'],
            $this->url['host'],
            $this->url['port'],
            \trim($this->url['path'], '/'),
            \http_build_query($query)
        );

        $result = @\file_get_contents($url, false, \stream_context_create($context));

        if (false === $result) {
            $message = null;
            $error = \error_get_last();

            if (null !== $error && false !== \strpos($error['message'], 'file_get_contents()')) {
                $message = $error['message'];
            }

            throw new ServerConnectionFailureException($message);
        }

        $open_curly_at = \strpos($result, '{');
        $todecode = \substr($result, $open_curly_at, \strrpos($result, '}')-$open_curly_at+1);
        $decoded = \json_decode($todecode, true);

        if (!\in_array('websocket', $decoded['upgrades'])) {
            throw new UnsupportedTransportException('websocket');
        }

        $cookies = [];
        foreach ($http_response_header as $header) {
            if (\preg_match('/^Set-Cookie:\s*([^;]*)/i', $header, $matches)) {
                $cookies[] = $matches[1];
            }
        }
        $this->cookies = $cookies;

        $this->session = new Session(
            $decoded['sid'],
            $decoded['pingInterval'] / 1000,
            $decoded['pingTimeout'] / 1000,
            $decoded['upgrades']
        );
    }
1187100
private function initialize()
    {
        // generate key pair.
        $this->privateKey = $this->generator->createPrivateKey();
        $this->publicKey = $this->privateKey->getPublicKey();

        // generate salt
        $this->salt = openssl_random_pseudo_bytes(16);

        $this->publicKeyContent = hex2bin($this->serializer->serialize($this->publicKey->getPoint()));
    }
1014650
private SslHandshakeResult initializeSocket(SocketChannel sc, boolean clientMode, List<Long> clockSkews)
            throws IOException {
        ByteBuffer timeBuffer = ByteBuffer.allocate(Long.BYTES);
        if (clientMode) {
            synchronized (sc.blockingLock()) {
                boolean isBlocking = sc.isBlocking();
                // Just being lazy and using blocking mode here to get the server's current timestamp
                sc.configureBlocking(true);
                do {
                    sc.read(timeBuffer);
                } while (timeBuffer.hasRemaining());
                sc.configureBlocking(isBlocking);
            }
            if (clockSkews != null) {
                clockSkews.add(System.currentTimeMillis() - ((ByteBuffer) timeBuffer.flip()).getLong());
            }
        } else {
            timeBuffer.putLong(System.currentTimeMillis());
            timeBuffer.flip();
            do {
                sc.write(timeBuffer);
            } while (timeBuffer.hasRemaining());
        }
        return setupSSLIfNeeded(sc, clientMode);
    }
642798
public synchronized void init() {
		for (SocketBinding binding : socketBindings) {
			socketBindingsMap.put(binding.getName(), binding);
		}
		for (SecurityRealm realm : securityRealms) {
			securityRealmsMap.put(realm.getName(), realm);
		}
		for (Interface iface : interfaces) {
			interfacesMap.put(iface.getName(), iface);
		}
		if (subsystem != null) {
			for (UndertowSubsystem.FileHandler handler : subsystem.getFileHandlers()) {
				handlersMap.put(handler.getName(), handler);
			}
			if (subsystem.getFilters() != null) {
				for (UndertowSubsystem.ResponseHeaderFilter filter : subsystem.getFilters().getResponseHeaders()) {
					filtersMap.put(filter.getName(), filter);
				}
				for (UndertowSubsystem.ErrorPageFilter filter : subsystem.getFilters().getErrorPages()) {
					filtersMap.put(filter.getName(), filter);
				}
				for (UndertowSubsystem.CustomFilter filter : subsystem.getFilters().getCustomFilters()) {
					filtersMap.put(filter.getName(), filter);
				}
			}
		}
	}
370290
private void handshake() throws WebSocketException
    {
        try
        {
            // Perform handshake with the proxy server.
            mProxyHandshaker.perform();
        }
        catch (IOException e)
        {
            // Handshake with the proxy server failed.
            String message = String.format(
                "Handshake with the proxy server (%s) failed: %s", mAddress, e.getMessage());

            // Raise an exception with PROXY_HANDSHAKE_ERROR.
            throw new WebSocketException(WebSocketError.PROXY_HANDSHAKE_ERROR, message, e);
        }

        if (mSSLSocketFactory == null)
        {
            // SSL handshake with the WebSocket endpoint is not needed.
            return;
        }

        try
        {
            // Overlay the existing socket.
            mSocket = mSSLSocketFactory.createSocket(mSocket, mHost, mPort, true);
        }
        catch (IOException e)
        {
            // Failed to overlay an existing socket.
            String message = "Failed to overlay an existing socket: " + e.getMessage();

            // Raise an exception with SOCKET_OVERLAY_ERROR.
            throw new WebSocketException(WebSocketError.SOCKET_OVERLAY_ERROR, message, e);
        }

        try
        {
            // Start the SSL handshake manually. As for the reason, see
            // http://docs.oracle.com/javase/7/docs/technotes/guides/security/jsse/samples/sockets/client/SSLSocketClient.java
            ((SSLSocket)mSocket).startHandshake();

            if (mSocket instanceof SSLSocket)
            {
                // Verify that the proxied hostname matches the certificate here since
                // this is not automatically done by the SSLSocket.
                verifyHostname((SSLSocket)mSocket, mProxyHandshaker.getProxiedHostname());
            }
        }
        catch (IOException e)
        {
            // SSL handshake with the WebSocket endpoint failed.
            String message = String.format(
                "SSL handshake with the WebSocket endpoint (%s) failed: %s", mAddress, e.getMessage());

            // Raise an exception with SSL_HANDSHAKE_ERROR.
            throw new WebSocketException(WebSocketError.SSL_HANDSHAKE_ERROR, message, e);
        }
    }
260727
@SuppressWarnings("unchecked")
	protected void _handshake() throws IOException {
		// do connection handshake

		PyroSerializer ser = PyroSerializer.getFor(Config.SERIALIZER);
		Map<String, Object> handshakedata = new HashMap<String, Object>();
		handshakedata.put("handshake", pyroHandshake);
		if(Config.METADATA)
			handshakedata.put("object", objectid);
		byte[] data = ser.serializeData(handshakedata);
		int flags = Config.METADATA? Message.FLAGS_META_ON_CONNECT : 0;
		Message msg = new Message(Message.MSG_CONNECT, data, ser.getSerializerId(), flags, sequenceNr, annotations(), pyroHmacKey);
		IOUtil.send(sock_out, msg.to_bytes());
		if(Config.MSG_TRACE_DIR!=null) {
			Message.TraceMessageSend(sequenceNr, msg.get_header_bytes(), msg.get_annotations_bytes(), msg.data);
		}

		// process handshake response
		msg = Message.recv(sock_in, new int[]{Message.MSG_CONNECTOK, Message.MSG_CONNECTFAIL}, pyroHmacKey);
		responseAnnotations(msg.annotations, msg.type);
		Object handshake_response = "?";
		if(msg.data!=null) {
			if((msg.flags & Message.FLAGS_COMPRESSED) != 0) {
				_decompressMessageData(msg);
			}
			try {
				ser = PyroSerializer.getFor(msg.serializer_id);
				handshake_response = ser.deserializeData(msg.data);
			} catch (Exception x) {
				msg.type=Message.MSG_CONNECTFAIL;
				handshake_response = "<not available because unsupported serialization format>";
			}
		}
		if(msg.type==Message.MSG_CONNECTOK) {
			if((msg.flags & Message.FLAGS_META_ON_CONNECT) != 0) {
				HashMap<String, Object> response_dict = (HashMap<String, Object>)handshake_response;
				HashMap<String, Object> metadata = (HashMap<String, Object>) response_dict.get("meta");
				_processMetadata(metadata);
				handshake_response = response_dict.get("handshake");
				try {
					validateHandshake(handshake_response);
				} catch (IOException x) {
					close();
					throw x;
				}
			}
		} else if (msg.type==Message.MSG_CONNECTFAIL) {
			close();
			throw new PyroException("connection rejected, reason: "+handshake_response);
		} else {
			close();
			throw new PyroException("connect: invalid msg type "+msg.type+" received");
		}
	}
1124014
def _initialize(self):
        ''''''
        credentials = (self.username if self.username else '') + ':' + (self.password if self.password else '')
        credentials = credentials.encode(self._encoding)
        self._connection.send(credentials + b'\3\0')
        response = self._connection.recv(1)

        if len(response) != 1:
            self.close()
            self._init_socket()

            self._connection.send(credentials + b'\0')
            response = self._connection.recv(1)
            if len(response) != 1:
                self.close()
                raise QAuthenticationException('Connection denied.')

        self._protocol_version = min(struct.unpack('B', response)[0], 3)
171966
public void renegotiate() {
        try {
            this.sslConnLink.getSSLEngine().beginHandshake();
        } catch (SSLException se) {
            FFDCFilter.processException(se,
                                        getClass().getName() + ".renegotiate", "1");
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Error while attempting handshake renegotiation; " + se);
            }
        }
    }
94371
public Server openSsl() throws SSLException, CertificateException {
        SelfSignedCertificate cert = new SelfSignedCertificate();
        sslContext = SslContextBuilder.forServer(cert.certificate(), cert.privateKey())
                .sslProvider(SslProvider.OPENSSL)
                .build();
        return this;
    }
1103107
@Override
    public void init(boolean forward) throws CertPathValidatorException {
        if (!forward) {
            prevPubKey = trustedPubKey;
            if (PKIX.isDSAPublicKeyWithoutParams(prevPubKey)) {
                // If TrustAnchor is a DSA public key and it has no params, it
                // cannot be used to verify the signature of the first cert,
                // so throw exception
                throw new CertPathValidatorException("Key parameters missing");
            }
            prevSubject = caName;
        } else {
            throw new
                CertPathValidatorException("forward checking not supported");
        }
    }
369089
def do_handshake(self):
        """"""
        while True:
            try:
                return self._sslobj.do_handshake()
            except SSLError:
                ex = sys.exc_info()[1]
                if ex.args[0] == SSL_ERROR_WANT_READ:
                    if self.timeout == 0.0:
                        raise
                    six.exc_clear()
                    self._io.wait_read(timeout=self.timeout, timeout_exc=_SSLErrorHandshakeTimeout)
                elif ex.args[0] == SSL_ERROR_WANT_WRITE:
                    if self.timeout == 0.0:
                        raise
                    six.exc_clear()
                    self._io.wait_write(timeout=self.timeout, timeout_exc=_SSLErrorHandshakeTimeout)
                else:
                    raise
1036413
private void handshakeFinished()
        throws IOException {
/*DEL
        // this call just forces some internal library
        // variables to be initailized
        this.conn.finishHandshake();
*/
        String cs =
            this.sslEngine.getSession().getCipherSuite();
        this.encryption = !cs.contains("WITH_NULL");
        logger.debug("encryption alg: " + cs);
    }
715234
def enable_ssl(self, *args, **kwargs):
        
        if self.handshake_sent:
            raise SSLError('can only enable SSL before handshake')

        self.secure = True
        self.sock = ssl.wrap_socket(self.sock, *args, **kwargs)