/// <exception cref="Sharpen.NoSuchAlgorithmException"></exception> /// <exception cref="Sharpen.KeyStoreException"></exception> /// <exception cref="Sharpen.UnrecoverableKeyException"></exception> public virtual Apache.Http.Conn.Ssl.SSLContextBuilder LoadKeyMaterial(KeyStore keystore , char[] keyPassword, PrivateKeyStrategy aliasStrategy) { KeyManagerFactory kmfactory = KeyManagerFactory.GetInstance(KeyManagerFactory.GetDefaultAlgorithm ()); kmfactory.Init(keystore, keyPassword); KeyManager[] kms = kmfactory.GetKeyManagers(); if (kms != null) { if (aliasStrategy != null) { for (int i = 0; i < kms.Length; i++) { KeyManager km = kms[i]; if (km is X509KeyManager) { kms[i] = new SSLContextBuilder.KeyManagerDelegate((X509KeyManager)km, aliasStrategy ); } } } for (int i_1 = 0; i_1 < kms.Length; i_1++) { keymanagers.AddItem(kms[i_1]); } } return(this); }
private void SetClientCertificate(ClientCertificate certificate) { if (certificate == null) { return; } byte[] bytes; try { bytes = Convert.FromBase64String(certificate.RawData); } catch (Exception ex) { throw new HttpRequestException(FailureMessages.InvalidRawData, ex); } var stream = new System.IO.MemoryStream(bytes); var keyStore = KeyStore.GetInstance("PKCS12"); keyStore.Load(stream, certificate.Passphrase.ToCharArray()); var kmf = KeyManagerFactory.GetInstance("X509"); kmf.Init(keyStore, certificate.Passphrase.ToCharArray()); KeyManagers = kmf.GetKeyManagers(); }
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; }
protected override KeyManagerFactory ConfigureKeyManagerFactory(KeyStore keyStore) { if (_keyManagerFactory != null) { return(_keyManagerFactory); } _keyManagerFactory = KeyManagerFactory.GetInstance(KeyManagerFactory.DefaultAlgorithm); _keyManagerFactory.Init(keyStore, null); return(_keyManagerFactory); }
/// <summary> /// Set the client certificate provider (Android implementation) /// </summary> /// <param name="provider">The provider for client certificates on this platform</param> public virtual void SetClientCertificates(Abstractions.IClientCertificateProvider provider) { if (provider is IClientCertificateProvider androidProvider) { _keyMgrFactory = KeyManagerFactory.GetInstance("X509"); _keyMgrFactory.Init(androidProvider.KeyStore, null); } else { _keyMgrFactory = null; } }
private IKeyManager[] GetKeyManagersFromClientCert(byte[] pkcs12, char[] password) { if (pkcs12 != null) { using (MemoryStream memoryStream = new MemoryStream(pkcs12)) { KeyStore keyStore = KeyStore.GetInstance("pkcs12"); keyStore.Load(memoryStream, password); KeyManagerFactory kmf = KeyManagerFactory.GetInstance("x509"); kmf.Init(keyStore, password); return(kmf.GetKeyManagers()); } } return(null); }
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; })); }
private void SetClientCertificate(ClientCertificate certificate) { if (certificate == null) { return; } var bytes = Convert.FromBase64String(certificate.RawData); var stream = new System.IO.MemoryStream(bytes); var keyStore = KeyStore.GetInstance("PKCS12"); keyStore.Load(stream, certificate.Passphrase.ToCharArray()); var kmf = KeyManagerFactory.GetInstance("X509"); kmf.Init(keyStore, certificate.Passphrase.ToCharArray()); KeyManagers = kmf.GetKeyManagers(); }
public localKeyManager( string keystorepath ) { Console.WriteLine("enter localKeyManager"); try { var xFileInputStream = default(FileInputStream); var xKeyStore = default(KeyStore); // certmgr.msc var xKeyStoreDefaultType = "Windows-MY"; var xKeyStorePassword = default(char[]); //try //{ // Console.WriteLine(new { xKeyStoreDefaultType }); // xKeyStore = KeyStore.getInstance(xKeyStoreDefaultType); //} //catch { xKeyStoreDefaultType = java.security.KeyStore.getDefaultType(); // http://www.coderanch.com/t/377172/java/java/cacerts-JAVA-HOME-jre-lib // /usr/lib/jvm/default-java/jre/lib/security/cacerts Console.WriteLine(new { xKeyStoreDefaultType }); xKeyStore = KeyStore.getInstance(xKeyStoreDefaultType); var fa = new FileInfo(typeof(Program).Assembly.Location); try { xFileInputStream = new FileInputStream(keystorepath); xKeyStorePassword = "".PadLeft(6, '0').ToCharArray(); } catch { throw; } } Console.WriteLine("localKeyManager " + new { xKeyStore }); xKeyStore.load(xFileInputStream, xKeyStorePassword); java.util.Enumeration en = xKeyStore.aliases(); //Console.WriteLine("aliases... done"); while (en.hasMoreElements()) { alias = (string)en.nextElement(); } KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); Console.WriteLine("localKeyManager " + new { kmf, alias }); kmf.init(xKeyStore, xKeyStorePassword); KeyManagers = kmf.getKeyManagers(); Console.WriteLine("localKeyManager " + new { KeyManagers.Length }); //{ xKeyStoreDefaultType = Windows-MY } //WindowsMYKeyManagers { xKeyStore = java.security.KeyStore@ac4d3b } //WindowsMYKeyManagers { kmf = javax.net.ssl.KeyManagerFactory@1c7d56b } //WindowsMYKeyManagers { KeyManagers = [Ljavax.net.ssl.KeyManager;@f77511 } // http://docs.oracle.com/javase/7/docs/api/javax/net/ssl/KeyManager.html // http://stackoverflow.com/questions/5292074/how-to-specify-outbound-certificate-alias-for-https-calls // http://www.angelfire.com/or/abhilash/site/articles/jsse-km/customKeyManager.html foreach (var KeyManager in KeyManagers) { var xX509KeyManager = KeyManager as X509KeyManager; if (xX509KeyManager != null) { Console.WriteLine("localKeyManager " + new { xX509KeyManager }); InternalX509KeyManager = xX509KeyManager; } } // http://stackoverflow.com/questions/15076820/java-sslhandshakeexception-no-cipher-suites-in-common // http://stackoverflow.com/questions/7535154/chrome-closing-connection-on-handshake-with-java-ssl-server } catch { throw; } }
//chooseServerAlias { keyType = EC_EC } //getClientAliases //chooseServerAlias { keyType = RSA } //getClientAliases //chooseServerAlias { keyType = RSA } //getClientAliases //chooseServerAlias { keyType = RSA } //getClientAliases //chooseServerAlias { keyType = RSA } //getClientAliases public static KeyManager[] WindowsMYKeyManagers() { Console.WriteLine("enter WindowsMYKeyManagers"); var KeyManagers = new KeyManager[0]; try { var xFileInputStream = default(FileInputStream); var xKeyStore = default(KeyStore); // certmgr.msc var xKeyStoreDefaultType = "Windows-MY"; try { Console.WriteLine(new { xKeyStoreDefaultType }); xKeyStore = KeyStore.getInstance(xKeyStoreDefaultType); } catch { xKeyStoreDefaultType = java.security.KeyStore.getDefaultType(); // http://www.coderanch.com/t/377172/java/java/cacerts-JAVA-HOME-jre-lib // /usr/lib/jvm/default-java/jre/lib/security/cacerts Console.WriteLine(new { xKeyStoreDefaultType }); xKeyStore = KeyStore.getInstance(xKeyStoreDefaultType); var fa = new FileInfo(typeof(Program).Assembly.Location); var keystorepath = fa.Directory.FullName + "/domain.keystore"; try { xFileInputStream = new FileInputStream(keystorepath); } catch { throw; } } Console.WriteLine("WindowsMYKeyManagers " + new { xKeyStore }); xKeyStore.load(xFileInputStream, null); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); Console.WriteLine("WindowsMYKeyManagers " + new { kmf }); kmf.init(xKeyStore, null); KeyManagers = kmf.getKeyManagers(); Console.WriteLine("WindowsMYKeyManagers " + new { KeyManagers.Length }); //{ xKeyStoreDefaultType = Windows-MY } //WindowsMYKeyManagers { xKeyStore = java.security.KeyStore@ac4d3b } //WindowsMYKeyManagers { kmf = javax.net.ssl.KeyManagerFactory@1c7d56b } //WindowsMYKeyManagers { KeyManagers = [Ljavax.net.ssl.KeyManager;@f77511 } // http://docs.oracle.com/javase/7/docs/api/javax/net/ssl/KeyManager.html // http://stackoverflow.com/questions/5292074/how-to-specify-outbound-certificate-alias-for-https-calls // http://www.angelfire.com/or/abhilash/site/articles/jsse-km/customKeyManager.html foreach (var KeyManager in KeyManagers) { var xX509KeyManager = KeyManager as X509KeyManager; if (xX509KeyManager != null) { Console.WriteLine("WindowsMYKeyManagers " + new { xX509KeyManager }); } } //WindowsMYKeyManagers { Length = 1 } //WindowsMYKeyManagers { xX509KeyManager = sun.security.ssl.SunX509KeyManagerImpl@ea3932 } //KeyStore ks = KeyStore.getInstance("JKS"); //// initialize KeyStore object using keystore name //ks.load(new FileInputStream(keyFile), null); //kmf.init(ks, keystorePasswd.toCharArray()); //ret = kmf.getKeyManagers(); // chooseServerAlias { keyType = RSA, StackTrace = <__StackTrace> } //java.security.KeyStore ks = null; //KeyManagerFactory kmf // http://stackoverflow.com/questions/15076820/java-sslhandshakeexception-no-cipher-suites-in-common // http://stackoverflow.com/questions/7535154/chrome-closing-connection-on-handshake-with-java-ssl-server } catch { throw; } return(KeyManagers); }
/// <summary>Initializes the keystores of the factory.</summary> /// <param name="mode">if the keystores are to be used in client or server mode.</param> /// <exception cref="System.IO.IOException"> /// thrown if the keystores could not be initialized due /// to an IO error. /// </exception> /// <exception cref="GeneralSecurityException"> /// thrown if the keystores could not be /// initialized due to a security error. /// </exception> public virtual void Init(SSLFactory.Mode mode) { bool requireClientCert = conf.GetBoolean(SSLFactory.SslRequireClientCertKey, SSLFactory .DefaultSslRequireClientCert); // certificate store string keystoreType = conf.Get(ResolvePropertyName(mode, SslKeystoreTypeTplKey), DefaultKeystoreType); KeyStore keystore = KeyStore.GetInstance(keystoreType); string keystoreKeyPassword = null; if (requireClientCert || mode == SSLFactory.Mode.Server) { string locationProperty = ResolvePropertyName(mode, SslKeystoreLocationTplKey); string keystoreLocation = conf.Get(locationProperty, string.Empty); if (keystoreLocation.IsEmpty()) { throw new GeneralSecurityException("The property '" + locationProperty + "' has not been set in the ssl configuration file." ); } string passwordProperty = ResolvePropertyName(mode, SslKeystorePasswordTplKey); string keystorePassword = GetPassword(conf, passwordProperty, string.Empty); if (keystorePassword.IsEmpty()) { throw new GeneralSecurityException("The property '" + passwordProperty + "' has not been set in the ssl configuration file." ); } string keyPasswordProperty = ResolvePropertyName(mode, SslKeystoreKeypasswordTplKey ); // Key password defaults to the same value as store password for // compatibility with legacy configurations that did not use a separate // configuration property for key password. keystoreKeyPassword = GetPassword(conf, keyPasswordProperty, keystorePassword); Log.Debug(mode.ToString() + " KeyStore: " + keystoreLocation); InputStream @is = new FileInputStream(keystoreLocation); try { keystore.Load(@is, keystorePassword.ToCharArray()); } finally { @is.Close(); } Log.Debug(mode.ToString() + " Loaded KeyStore: " + keystoreLocation); } else { keystore.Load(null, null); } KeyManagerFactory keyMgrFactory = KeyManagerFactory.GetInstance(SSLFactory.Sslcertificate ); keyMgrFactory.Init(keystore, (keystoreKeyPassword != null) ? keystoreKeyPassword. ToCharArray() : null); keyManagers = keyMgrFactory.GetKeyManagers(); //trust store string truststoreType = conf.Get(ResolvePropertyName(mode, SslTruststoreTypeTplKey ), DefaultKeystoreType); string locationProperty_1 = ResolvePropertyName(mode, SslTruststoreLocationTplKey ); string truststoreLocation = conf.Get(locationProperty_1, string.Empty); if (!truststoreLocation.IsEmpty()) { string passwordProperty = ResolvePropertyName(mode, SslTruststorePasswordTplKey); string truststorePassword = GetPassword(conf, passwordProperty, string.Empty); if (truststorePassword.IsEmpty()) { throw new GeneralSecurityException("The property '" + passwordProperty + "' has not been set in the ssl configuration file." ); } long truststoreReloadInterval = conf.GetLong(ResolvePropertyName(mode, SslTruststoreReloadIntervalTplKey ), DefaultSslTruststoreReloadInterval); Log.Debug(mode.ToString() + " TrustStore: " + truststoreLocation); trustManager = new ReloadingX509TrustManager(truststoreType, truststoreLocation, truststorePassword, truststoreReloadInterval); trustManager.Init(); Log.Debug(mode.ToString() + " Loaded TrustStore: " + truststoreLocation); trustManagers = new TrustManager[] { trustManager }; } else { Log.Debug("The property '" + locationProperty_1 + "' has not been set, " + "no TrustStore will be loaded" ); trustManagers = 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); }