public virtual HttpClient GetHttpClient() { // workaround attempt for issue #81 // it does not seem like _not_ using the ThreadSafeClientConnManager actually // caused any problems, but it seems wise to use it "just in case", since it provides // extra safety and there are no observed side effects. BasicHttpParams @params = new BasicHttpParams(); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.Register(new Apache.Http.Conn.Scheme.Scheme("http", PlainSocketFactory .GetSocketFactory(), 80)); SSLSocketFactory sslSocketFactory = SSLSocketFactory.GetSocketFactory(); schemeRegistry.Register(new Apache.Http.Conn.Scheme.Scheme("https", this.sslSocketFactory == null ? sslSocketFactory : this.sslSocketFactory, 443)); ClientConnectionManager cm = new ThreadSafeClientConnManager(@params, schemeRegistry ); DefaultHttpClient client = new DefaultHttpClient(cm, @params); // synchronize access to the cookieStore in case there is another // thread in the middle of updating it. wait until they are done so we get their changes. lock (this) { client.SetCookieStore(cookieStore); } return(client); }
public _ConnectionConfigurator_536(SSLSocketFactory sf, HostnameVerifier hv, int timeout) { this.sf = sf; this.hv = hv; this.timeout = timeout; }
private SSLSocketFactory newSslSocketFactory() { try { // Get an instance of the Bouncy Castle KeyStore format KeyStore trusted = KeyStore.getInstance("BKS"); // Get the raw resource, which contains the keystore with // your trusted certificates (root and any intermediate certs) InputStream in = context.getResources().openRawResource( R.raw.mykeystore); try { // Initialize the keystore with the provided trusted // certificates // Also provide the password of the keystore trusted.load(in, "mysecret".toCharArray()); } finally { in.close(); } // Pass the keystore to the SSLSocketFactory. The factory is // responsible // for the verification of the server certificate. SSLSocketFactory sf = new SSLSocketFactory(trusted); // Hostname verification from certificate sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); return(sf); } catch (Exception e) {
public SSLConnectionSocketFactory(SSLSocketFactory socketfactory, string[] supportedProtocols , string[] supportedCipherSuites, X509HostnameVerifier hostnameVerifier) { this.socketfactory = Args.NotNull(socketfactory, "SSL socket factory"); this.supportedProtocols = supportedProtocols; this.supportedCipherSuites = supportedCipherSuites; this.hostnameVerifier = hostnameVerifier != null ? hostnameVerifier : BrowserCompatibleHostnameVerifier; }
public TlsSslSocketFactory(IKeyManager[] keyManagers = null, ITrustManager[] trustManagers = null) { if (keyManagers != null || trustManagers != null) { var context = SSLContext.GetInstance("TLS"); context.Init(keyManagers, trustManagers, null); _factory = context.SocketFactory; } }
/// <param name="sslSocketFactoryFromUser"> /// This is to open up the system for end user to inject the sslSocket factories with their /// custom KeyStore /// </param> public virtual void SetSSLSocketFactory(SSLSocketFactory sslSocketFactoryFromUser ) { if (sslSocketFactory != null) { throw new RuntimeException("SSLSocketFactory already set"); } sslSocketFactory = sslSocketFactoryFromUser; }
public virtual void SetSSLSocketFactory(SSLSocketFactory sslSocketFactoryFromUser ) { if (sslSocketFactory != null) { throw new RuntimeException("SSLSocketFactory already set"); } sslSocketFactory = sslSocketFactoryFromUser; }
protected override void Dispose(bool disposing) { if (disposing) { _factory?.Dispose(); _factory = null; } base.Dispose(disposing); }
/// <since>4.3</since> public BasicConnFactory(SocketFactory plainfactory, SSLSocketFactory sslfactory, int connectTimeout, SocketConfig sconfig, ConnectionConfig cconfig) : base() { this.plainfactory = plainfactory; this.sslfactory = sslfactory; this.connectTimeout = connectTimeout; this.sconfig = sconfig != null ? sconfig : SocketConfig.Default; this.connFactory = new DefaultBHttpClientConnectionFactory(cconfig != null ? cconfig : ConnectionConfig.Default); }
protected override SSLSocketFactory ConfigureCustomSSLSocketFactory(HttpsURLConnection connection) { SSLSocketFactory socketFactory = sslContext.SocketFactory; if (connection != null) { connection.SSLSocketFactory = socketFactory; } return(socketFactory); }
void SetupSSL(HttpsURLConnection httpsConnection) { if (httpsConnection == null) { return; } SSLSocketFactory socketFactory = ConfigureCustomSSLSocketFactory(httpsConnection); if (socketFactory != null) { httpsConnection.SSLSocketFactory = socketFactory; return; } KeyStore keyStore = KeyStore.GetInstance(KeyStore.DefaultType); keyStore.Load(null, null); bool gotCerts = TrustedCerts?.Count > 0; if (gotCerts) { for (int i = 0; i < TrustedCerts.Count; i++) { Certificate cert = TrustedCerts [i]; if (cert == null) { continue; } keyStore.SetCertificateEntry($"ca{i}", cert); } } keyStore = ConfigureKeyStore(keyStore); KeyManagerFactory kmf = ConfigureKeyManagerFactory(keyStore); TrustManagerFactory tmf = ConfigureTrustManagerFactory(keyStore); if (tmf == null) { // If there are no certs and no trust manager factory, we can't use a custom manager // because it will cause all the HTTPS requests to fail because of unverified trust // chain if (!gotCerts) { return; } tmf = TrustManagerFactory.GetInstance(TrustManagerFactory.DefaultAlgorithm); tmf.Init(keyStore); } SSLContext context = SSLContext.GetInstance("TLS"); context.Init(kmf?.GetKeyManagers(), tmf.GetTrustManagers(), null); httpsConnection.SSLSocketFactory = context.SocketFactory; }
public BasicConnFactory(SSLSocketFactory sslfactory, HttpParams @params) : base() { Args.NotNull(@params, "HTTP params"); this.plainfactory = null; this.sslfactory = sslfactory; this.connectTimeout = @params.GetIntParameter(CoreConnectionPNames.ConnectionTimeout , 0); this.sconfig = HttpParamConfig.GetSocketConfig(@params); this.connFactory = new DefaultBHttpClientConnectionFactory(HttpParamConfig.GetConnectionConfig (@params)); }
private OkHttpClient GetUnsafeOkHttpClient() { ITrustManager[] trustAllCerts = new ITrustManager[] { new X509TrustManager() }; SSLContext sslContext = SSLContext.GetInstance("SSL"); sslContext.Init(null, trustAllCerts, null); SSLSocketFactory sslSocketFactory = sslContext.SocketFactory; OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.SetSslSocketFactory(sslSocketFactory); okHttpClient.SetHostnameVerifier(new UnsafeHostnameVerifier()); return(okHttpClient); }
private SSLSocketFactory GetFactory() { if (_factory != null) { return(_factory); } Android.Util.Log.Warn("ModernHttpClient", "ImprovedSSLSocketFactory : creating factory again"); var context = SSLContext.GetInstance("TLS"); context.Init(null, new[] { _trustManager }, null); _factory = context.SocketFactory; return(_factory); }
/// <exception cref="System.IO.IOException"></exception> public virtual HttpClientConnection Create(HttpHost host) { string scheme = host.GetSchemeName(); Socket socket = null; if (Sharpen.Runtime.EqualsIgnoreCase("http", scheme)) { socket = this.plainfactory != null?this.plainfactory.CreateSocket() : new Socket (); } if (Sharpen.Runtime.EqualsIgnoreCase("https", scheme)) { socket = (this.sslfactory != null ? this.sslfactory : SSLSocketFactory.GetDefault ()).CreateSocket(); } if (socket == null) { throw new IOException(scheme + " scheme is not supported"); } string hostname = host.GetHostName(); int port = host.GetPort(); if (port == -1) { if (Sharpen.Runtime.EqualsIgnoreCase(host.GetSchemeName(), "http")) { port = 80; } else { if (Sharpen.Runtime.EqualsIgnoreCase(host.GetSchemeName(), "https")) { port = 443; } } } socket.ReceiveTimeout = this.sconfig.GetSoTimeout(); socket.Connect(new IPEndPoint(hostname, port), this.connectTimeout); socket.NoDelay = this.sconfig.IsTcpNoDelay(); int linger = this.sconfig.GetSoLinger(); if (linger >= 0) { socket.SetSoLinger(linger > 0, linger); } socket.SetKeepAlive(this.sconfig.IsSoKeepAlive()); return(this.connFactory.CreateConnection(socket)); }
/// <summary> /// Sets up the socket factory and the hostname verifier for the next time a /// client is requested. /// </summary> private static void Setup(SSLSocketFactory factory, IHostnameVerifier verifier) { // create our custom socket factory to handle TLS v1.2 on older devices // although we can actually use it on any Android version as it is just // a proxy class that makes sure all supported protocols are enabled //if (Android.OS.Build.VERSION.SdkInt < BuildVersionCodes.Lollipop) //{ socketFactory = new CompleteSSLSocketFactory(factory); //} //else //{ // socketFactory = factory; //} // set the hostname verifer hostnameVerifier = verifier; }
public static SSLSocketFactory createSSLSocketFactory() { SSLSocketFactory sSLSocketFactory = null; try { SSLContext sc = SSLContext.GetInstance("TLS"); sc.Init(null, new ITrustManager[] { new HttpsTrustManager() }, new SecureRandom()); sSLSocketFactory = sc.SocketFactory; } catch (Exception e) { } return(sSLSocketFactory); }
async Task <String> JavaConnectAndReceiveMessage() { var hostName = "192.168.1.103"; var port = 56111; // Build Java Keystore Stream keyin = Resources.OpenRawResource(Resource.Raw.ClientBKS); KeyStore ks = KeyStore.GetInstance("BKS"); ks.Load(keyin, "password".ToCharArray()); return(await Task.Run(() => { String defaultAlgorithm = KeyManagerFactory.DefaultAlgorithm; KeyManagerFactory keyManagerFactory = KeyManagerFactory.GetInstance(defaultAlgorithm); keyManagerFactory.Init(ks, "password".ToCharArray()); SSLContext sslContext = SSLContext.GetInstance("TLS"); sslContext.Init(keyManagerFactory.GetKeyManagers(), null, null); SSLSocketFactory sslSocketFactory = sslContext.SocketFactory; Javax.Net.Ssl.SSLSocket sslSocket = (Javax.Net.Ssl.SSLSocket)sslSocketFactory.CreateSocket(new Java.Net.Socket(hostName, port), hostName, port, false); sslSocket.AddHandshakeCompletedListener(this); sslSocket.NeedClientAuth = true; sslSocket.KeepAlive = true; sslSocket.StartHandshake(); // Exchange Messages Stream sslIS = sslSocket.InputStream; Stream sslOS = sslSocket.OutputStream; // Encode a test message into a byte array. // Signal the end of the message using the "<EOF>". byte[] messsage = Encoding.UTF8.GetBytes("Hello from the client.<EOF>"); sslOS.Write(messsage, 0, messsage.Length); sslOS.Flush(); string serverMessage = ReadMessage(sslIS); sslSocket.Close(); return serverMessage; })); }
public SSLConnectionSocketFactory(SSLSocketFactory socketfactory, X509HostnameVerifier hostnameVerifier) : this(socketfactory, null, null, hostnameVerifier) { }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: public static void main(String[] paramArrayOfString) throws Exception public static void Main(string[] paramArrayOfString) { bool @bool; char[] arrayOfChar; char c; string str1; if (paramArrayOfString.Length == 1 || paramArrayOfString.Length == 2) { string[] arrayOfString = paramArrayOfString[0].Split(":", true); str1 = arrayOfString[0]; c = (arrayOfString.Length == 1) ? (char)443 : (char)int.Parse(arrayOfString[1]); string str = (paramArrayOfString.Length == 1) ? "changeit" : paramArrayOfString[1]; arrayOfChar = str.ToCharArray(); } else { Console.WriteLine("Usage: java InstallCert [:port] [passphrase]"); return; } File file = new File("jssecacerts"); if (!file.File) { char c1 = Path.DirectorySeparatorChar; File file1 = new File(System.getProperty("java.home") + c1 + "lib" + c1 + "security"); file = new File(file1, "jssecacerts"); if (!file.File) { file = new File(file1, "cacerts"); } } Console.WriteLine("Loading KeyStore " + file + "..."); FileStream fileInputStream = new FileStream(file, FileMode.Open, FileAccess.Read); KeyStore keyStore = KeyStore.getInstance(KeyStore.DefaultType); keyStore.load(fileInputStream, arrayOfChar); fileInputStream.Close(); SSLContext sSLContext = SSLContext.getInstance("TLS"); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.DefaultAlgorithm); trustManagerFactory.init(keyStore); X509TrustManager x509TrustManager = (X509TrustManager)trustManagerFactory.TrustManagers[0]; SavingTrustManager savingTrustManager = new SavingTrustManager(x509TrustManager); sSLContext.init(null, new TrustManager[] { savingTrustManager }, null); SSLSocketFactory sSLSocketFactory = sSLContext.SocketFactory; Console.WriteLine("Opening connection to " + str1 + ":" + c + "..."); SSLSocket sSLSocket = (SSLSocket)sSLSocketFactory.createSocket(str1, c); sSLSocket.SoTimeout = 10000; try { Console.WriteLine("Starting SSL handshake..."); sSLSocket.startHandshake(); sSLSocket.close(); Console.WriteLine(); Console.WriteLine("No errors, certificate is already trusted"); } catch (SSLException sSLException) { Console.WriteLine(); sSLException.printStackTrace(System.out); } X509Certificate[] arrayOfX509Certificate = savingTrustManager.chain; if (arrayOfX509Certificate == null) { Console.WriteLine("Could not obtain server certificate chain"); return; } StreamReader bufferedReader = new StreamReader(System.in); Console.WriteLine(); Console.WriteLine("Server sent " + arrayOfX509Certificate.Length + " certificate(s):"); Console.WriteLine(); MessageDigest messageDigest1; MessageDigest messageDigest2 = (messageDigest1 = MessageDigest.getInstance("SHA1")).getInstance("MD5"); for (sbyte b = 0; b < arrayOfX509Certificate.Length; b++) { X509Certificate x509Certificate1 = arrayOfX509Certificate[b]; Console.WriteLine(" " + (b + true) + " Subject " + x509Certificate1.SubjectDN); Console.WriteLine(" Issuer " + x509Certificate1.IssuerDN); messageDigest1.update(x509Certificate1.Encoded); Console.WriteLine(" sha1 " + toHexString(messageDigest1.digest())); messageDigest2.update(x509Certificate1.Encoded); Console.WriteLine(" md5 " + toHexString(messageDigest2.digest())); Console.WriteLine(); } Console.WriteLine("Enter certificate to add to trusted keystore or 'q' to quit: [1]"); string str2 = bufferedReader.ReadLine().Trim(); try { @bool = (str2.Length == 0) ? 0 : (int.Parse(str2) - 1); } catch (System.FormatException) { Console.WriteLine("KeyStore not changed"); return; } X509Certificate x509Certificate = arrayOfX509Certificate[@bool]; string str3 = str1 + "-" + (@bool + true); keyStore.setCertificateEntry(str3, x509Certificate); FileStream fileOutputStream = new FileStream("jssecacerts", FileMode.Create, FileAccess.Write); keyStore.store(fileOutputStream, arrayOfChar); fileOutputStream.Close(); Console.WriteLine(); Console.WriteLine(x509Certificate); Console.WriteLine(); Console.WriteLine("Added certificate to keystore 'jssecacerts' using alias '" + str3 + "'"); }
} // getSSLSocketFactory() /* **************************************************************************** * setSSLSocketFactory() **************************************************************************** */ /** * Sets the SSL SocketFactory to use */ public void setSSLSocketFactory(SSLSocketFactory oSocketFactory) { moSocketFactory = oSocketFactory; } // setSSLSocketFactory()
public virtual CloseableHttpClient Build() { // Create main request executor HttpRequestExecutor requestExec = this.requestExec; if (requestExec == null) { requestExec = new HttpRequestExecutor(); } HttpClientConnectionManager connManager = this.connManager; if (connManager == null) { LayeredConnectionSocketFactory sslSocketFactory = this.sslSocketFactory; if (sslSocketFactory == null) { string[] supportedProtocols = systemProperties ? Split(Runtime.GetProperty("https.protocols" )) : null; string[] supportedCipherSuites = systemProperties ? Split(Runtime.GetProperty("https.cipherSuites" )) : null; X509HostnameVerifier hostnameVerifier = this.hostnameVerifier; if (hostnameVerifier == null) { hostnameVerifier = SSLConnectionSocketFactory.BrowserCompatibleHostnameVerifier; } if (sslcontext != null) { sslSocketFactory = new SSLConnectionSocketFactory(sslcontext, supportedProtocols, supportedCipherSuites, hostnameVerifier); } else { if (systemProperties) { sslSocketFactory = new SSLConnectionSocketFactory((SSLSocketFactory)SSLSocketFactory .GetDefault(), supportedProtocols, supportedCipherSuites, hostnameVerifier); } else { sslSocketFactory = new SSLConnectionSocketFactory(SSLContexts.CreateDefault(), hostnameVerifier ); } } } PoolingHttpClientConnectionManager poolingmgr = new PoolingHttpClientConnectionManager (RegistryBuilder.Create <ConnectionSocketFactory>().Register("http", PlainConnectionSocketFactory .GetSocketFactory()).Register("https", sslSocketFactory).Build()); if (defaultSocketConfig != null) { poolingmgr.SetDefaultSocketConfig(defaultSocketConfig); } if (defaultConnectionConfig != null) { poolingmgr.SetDefaultConnectionConfig(defaultConnectionConfig); } if (systemProperties) { string s = Runtime.GetProperty("http.keepAlive", "true"); if (Sharpen.Runtime.EqualsIgnoreCase("true", s)) { s = Runtime.GetProperty("http.maxConnections", "5"); int max = System.Convert.ToInt32(s); poolingmgr.SetDefaultMaxPerRoute(max); poolingmgr.SetMaxTotal(2 * max); } } if (maxConnTotal > 0) { poolingmgr.SetMaxTotal(maxConnTotal); } if (maxConnPerRoute > 0) { poolingmgr.SetDefaultMaxPerRoute(maxConnPerRoute); } connManager = poolingmgr; } ConnectionReuseStrategy reuseStrategy = this.reuseStrategy; if (reuseStrategy == null) { if (systemProperties) { string s = Runtime.GetProperty("http.keepAlive", "true"); if (Sharpen.Runtime.EqualsIgnoreCase("true", s)) { reuseStrategy = DefaultConnectionReuseStrategy.Instance; } else { reuseStrategy = NoConnectionReuseStrategy.Instance; } } else { reuseStrategy = DefaultConnectionReuseStrategy.Instance; } } ConnectionKeepAliveStrategy keepAliveStrategy = this.keepAliveStrategy; if (keepAliveStrategy == null) { keepAliveStrategy = DefaultConnectionKeepAliveStrategy.Instance; } AuthenticationStrategy targetAuthStrategy = this.targetAuthStrategy; if (targetAuthStrategy == null) { targetAuthStrategy = TargetAuthenticationStrategy.Instance; } AuthenticationStrategy proxyAuthStrategy = this.proxyAuthStrategy; if (proxyAuthStrategy == null) { proxyAuthStrategy = ProxyAuthenticationStrategy.Instance; } UserTokenHandler userTokenHandler = this.userTokenHandler; if (userTokenHandler == null) { if (!connectionStateDisabled) { userTokenHandler = DefaultUserTokenHandler.Instance; } else { userTokenHandler = NoopUserTokenHandler.Instance; } } ClientExecChain execChain = new MainClientExec(requestExec, connManager, reuseStrategy , keepAliveStrategy, targetAuthStrategy, proxyAuthStrategy, userTokenHandler); execChain = DecorateMainExec(execChain); HttpProcessor httpprocessor = this.httpprocessor; if (httpprocessor == null) { string userAgent = this.userAgent; if (userAgent == null) { if (systemProperties) { userAgent = Runtime.GetProperty("http.agent"); } if (userAgent == null) { userAgent = DefaultUserAgent; } } HttpProcessorBuilder b = HttpProcessorBuilder.Create(); if (requestFirst != null) { foreach (IHttpRequestInterceptor i in requestFirst) { b.AddFirst(i); } } if (responseFirst != null) { foreach (HttpResponseInterceptor i in responseFirst) { b.AddFirst(i); } } b.AddAll(new RequestDefaultHeaders(defaultHeaders), new RequestContent(), new RequestTargetHost (), new RequestClientConnControl(), new RequestUserAgent(userAgent), new RequestExpectContinue ()); if (!cookieManagementDisabled) { b.Add(new RequestAddCookies()); } if (!contentCompressionDisabled) { b.Add(new RequestAcceptEncoding()); } if (!authCachingDisabled) { b.Add(new RequestAuthCache()); } if (!cookieManagementDisabled) { b.Add(new ResponseProcessCookies()); } if (!contentCompressionDisabled) { b.Add(new ResponseContentEncoding()); } if (requestLast != null) { foreach (IHttpRequestInterceptor i in requestLast) { b.AddLast(i); } } if (responseLast != null) { foreach (HttpResponseInterceptor i in responseLast) { b.AddLast(i); } } httpprocessor = b.Build(); } execChain = new ProtocolExec(execChain, httpprocessor); execChain = DecorateProtocolExec(execChain); // Add request retry executor, if not disabled if (!automaticRetriesDisabled) { HttpRequestRetryHandler retryHandler = this.retryHandler; if (retryHandler == null) { retryHandler = DefaultHttpRequestRetryHandler.Instance; } execChain = new RetryExec(execChain, retryHandler); } HttpRoutePlanner routePlanner = this.routePlanner; if (routePlanner == null) { SchemePortResolver schemePortResolver = this.schemePortResolver; if (schemePortResolver == null) { schemePortResolver = DefaultSchemePortResolver.Instance; } if (proxy != null) { routePlanner = new DefaultProxyRoutePlanner(proxy, schemePortResolver); } else { if (systemProperties) { routePlanner = new SystemDefaultRoutePlanner(schemePortResolver, ProxySelector.GetDefault ()); } else { routePlanner = new DefaultRoutePlanner(schemePortResolver); } } } // Add redirect executor, if not disabled if (!redirectHandlingDisabled) { RedirectStrategy redirectStrategy = this.redirectStrategy; if (redirectStrategy == null) { redirectStrategy = DefaultRedirectStrategy.Instance; } execChain = new RedirectExec(execChain, routePlanner, redirectStrategy); } // Optionally, add service unavailable retry executor ServiceUnavailableRetryStrategy serviceUnavailStrategy = this.serviceUnavailStrategy; if (serviceUnavailStrategy != null) { execChain = new ServiceUnavailableRetryExec(execChain, serviceUnavailStrategy); } // Optionally, add connection back-off executor BackoffManager backoffManager = this.backoffManager; ConnectionBackoffStrategy connectionBackoffStrategy = this.connectionBackoffStrategy; if (backoffManager != null && connectionBackoffStrategy != null) { execChain = new BackoffStrategyExec(execChain, connectionBackoffStrategy, backoffManager ); } Lookup <AuthSchemeProvider> authSchemeRegistry = this.authSchemeRegistry; if (authSchemeRegistry == null) { authSchemeRegistry = RegistryBuilder.Create <AuthSchemeProvider>().Register(AuthSchemes .Basic, new BasicSchemeFactory()).Register(AuthSchemes.Digest, new DigestSchemeFactory ()).Register(AuthSchemes.Ntlm, new NTLMSchemeFactory()).Register(AuthSchemes.Spnego , new SPNegoSchemeFactory()).Register(AuthSchemes.Kerberos, new KerberosSchemeFactory ()).Build(); } Lookup <CookieSpecProvider> cookieSpecRegistry = this.cookieSpecRegistry; if (cookieSpecRegistry == null) { cookieSpecRegistry = RegistryBuilder.Create <CookieSpecProvider>().Register(CookieSpecs .BestMatch, new BestMatchSpecFactory()).Register(CookieSpecs.Standard, new RFC2965SpecFactory ()).Register(CookieSpecs.BrowserCompatibility, new BrowserCompatSpecFactory()).Register (CookieSpecs.Netscape, new NetscapeDraftSpecFactory()).Register(CookieSpecs.IgnoreCookies , new IgnoreSpecFactory()).Register("rfc2109", new RFC2109SpecFactory()).Register ("rfc2965", new RFC2965SpecFactory()).Build(); } CookieStore defaultCookieStore = this.cookieStore; if (defaultCookieStore == null) { defaultCookieStore = new BasicCookieStore(); } CredentialsProvider defaultCredentialsProvider = this.credentialsProvider; if (defaultCredentialsProvider == null) { if (systemProperties) { defaultCredentialsProvider = new SystemDefaultCredentialsProvider(); } else { defaultCredentialsProvider = new BasicCredentialsProvider(); } } return(new InternalHttpClient(execChain, connManager, routePlanner, cookieSpecRegistry , authSchemeRegistry, defaultCookieStore, defaultCredentialsProvider, defaultRequestConfig != null ? defaultRequestConfig : RequestConfig.Default, closeables != null ? new AList <IDisposable>(closeables) : null)); }
private SSLSocketFactory getSSLSocketFactory() { SSLSocketFactory factory = null; try { //reading the keyStore path and password from the environment properties string keyStorePath = java.lang.System.getProperty("javax.net.ssl.keyStore"); java.io.FileInputStream keyStoreStream = null; if (keyStorePath != null) { java.io.File file = new java.io.File(keyStorePath); if (file.exists()) { keyStoreStream = new java.io.FileInputStream(file); } else { keyStoreStream = searchDefaultCacerts(); } } else { keyStoreStream = searchDefaultCacerts(); } string keyStorePassWord = java.lang.System.getProperty("javax.net.ssl.keyStorePassword"); if (keyStorePassWord == null) { keyStorePassWord = "******"; } char[] passphrase = keyStorePassWord.ToCharArray(); //initiating SSLContext SSLContext ctx = SSLContext.getInstance("TLS"); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyStore ks = KeyStore.getInstance("JKS"); if (keyStoreStream != null) { ks.load(keyStoreStream, passphrase); } else { ks.load(null, null); } kmf.init(ks, passphrase); tmf.init(ks); ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); factory = ctx.getSocketFactory(); } catch (Exception e) { factory = null; #if DEBUG Console.WriteLine("Can't get SSL Socket Factory, the exception is {0}, {1}", e.GetType(), e.Message); #endif } return(factory); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Before public void setUp() public virtual void SetUp() { _originalSslSocketFactory = HttpsURLConnection.DefaultSSLSocketFactory; }
public static void setHostnameVerifier(this SSLSocketFactory factory, IX509HostnameVerifier verifier) { factory.HostnameVerifier = verifier; }
public CompleteSSLSocketFactory(SSLSocketFactory innerFactory) { this.innerFactory = innerFactory; }
public GHSocket ChangeToSSL(EndPoint remote_end) { if (jSocket == null) { throw new InvalidOperationException("The underlying socket is null"); } if (!jSocketChannel.isBlocking()) { throw new NotImplementedException("The SSL Socket for non-blocking mode is not supported"); } SSLSocketFactory factory = getSSLSocketFactory(); if (factory == null) { throw new ApplicationException("Can't get SSL Socket Factory"); } int err; // The problem with local address, when I closed the socket and try to create the new one // bounded to the given local address, I receive exception "Address already in use" IPEndPoint localEndPoint = null; // IPEndPoint localEndPoint = (IPEndPoint) LocalEndPoint_internal(out err); // if (err != 0) // localEndPoint = null; IPEndPoint remoteEndPoint = remote_end as IPEndPoint; if (remoteEndPoint == null) { remoteEndPoint = (IPEndPoint)RemoteEndPoint_internal(out err); if (err != 0) { remoteEndPoint = null; } } java.net.Socket sslSocket = null; try { if (remoteEndPoint != null) { if (localEndPoint != null) { sslSocket = factory.createSocket( java.net.InetAddress.getByName(remoteEndPoint.Address.ToString()), remoteEndPoint.Port, java.net.InetAddress.getByName(localEndPoint.Address.ToString()), localEndPoint.Port); } else { sslSocket = factory.createSocket( jSocket, remoteEndPoint.Address.ToString(), remoteEndPoint.Port, false); } if (sslSocket != null) { String[] protocols = { "TLSv1", "SSLv3" }; ((SSLSocket)sslSocket).setUseClientMode(true); ((SSLSocket)sslSocket).startHandshake(); } } else { sslSocket = factory.createSocket(); } } catch (Exception e) { sslSocket = null; #if DEBUG Console.WriteLine("Can't create SSL Socket, the exception is {0}, {1}", e.GetType(), e.Message); #endif } if (sslSocket == null) { // throw new ApplicationException("Can't create SSL Socket"); // it is important to the Socket class to distinguish if the underlying // handle (GHSocket) is still valid and can be used as non-SSL, or it is already // closed by this function and can't be used any more. return(null); } /* * string[] arr = ((SSLSocket)sslSocket).getEnabledProtocols(); * if (arr != null) * { * foreach (string s in arr) * Console.WriteLine("s:"+s); * } * string [] arr1 = ((SSLSocket)sslSocket).getEnabledCipherSuites(); * if (arr1 != null) * { * foreach (string s in arr1) * Console.WriteLine("s:"+s); * } */ return(new GHStreamSocketSSL(sslSocket)); }
/// <summary> /// Obtains default SSL socket factory with an SSL context based on system properties /// as described in /// <a href="http://docs.oracle.com/javase/1.5.0/docs/guide/security/jsse/JSSERefGuide.html"> /// "JavaTM Secure Socket Extension (JSSE) Reference Guide for the JavaTM 2 Platform /// Standard Edition 5</a> /// </summary> /// <returns>default system SSL socket factory</returns> /// <exception cref="Apache.Http.Conn.Ssl.SSLInitializationException"></exception> public static Apache.Http.Conn.Ssl.SSLConnectionSocketFactory GetSystemSocketFactory () { return(new Apache.Http.Conn.Ssl.SSLConnectionSocketFactory((SSLSocketFactory)SSLSocketFactory .GetDefault(), Split(Runtime.GetProperty("https.protocols")), Split(Runtime.GetProperty ("https.cipherSuites")), BrowserCompatibleHostnameVerifier)); }
public static Socket createSocket(this SSLSocketFactory factory, Socket s, string host, int port, bool autoClose) { return(factory.CreateSocket(s, host, port, autoClose)); }
public ImprovedSSLSocketFactory(SSLSocketFactory factory, ITrustManager trustManager) { _factory = factory; _trustManager = trustManager; }