V
V
Vanes Ri_Lax2015-09-09 09:17:40
Java
Vanes Ri_Lax, 2015-09-09 09:17:40

How to make SSL socket client server application?

Hello! I am writing a client-server application, it is necessary that they "communicate" using a secure protocol.
The server will be installed on a machine running CentOS 6.5
. The client will run on Android devices and not only.
I don't have enough knowledge in terms of SSL. What do I need for this?
Do I need machine settings, a certificate?
I found a lot of articles on the net, for example this
one, but as I understand it, a certificate is not used there, but are there any examples using a certificate?
Thank you very much in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dante Faustoff, 2015-09-09
@StFaustoff

Working with certificates is different. This can be as simple as using a certificate on the server side and further verification through certificate authorities, or using self-signed certificates, when both the client and the server have one certificate and exchange them when connected. The first option is easier, the second is free.
After that, you need to configure the web container. Here is a good example of setting up TomCat. Actually, I use a two-phase self-signed certification.
After that, the "heat" will begin =) Since I use a self-signed certificate, the task becomes a little more complicated. The fact is that on the side of the mobile client, you must first configure the context of the Internet connection to work with the certificate. Accordingly, the client goes to the certification servers to check the reliability of the resource. But since everything is self-made, you have to switch the security settings to the mode - trust everything.
After this setup, the context is passed for the connection being created and registered.
I will give an example of a code that has suffered through many hours of painstaking work

try{// Работа с SSL пробрасывает исключения, порой очень неприятные и непонятно как устранимые
   KeyStore keyStore = KeyStore.getInstance("Your_Type_Of_Certificate");//делаем хранилище ключей, аналогичное типу Вашего сертификата
   InputStream in = ...// крепим к потоку сам файл сертификата
   try{
      keyStore.load(in, "Your_Password".toCharArray());//грузим в хранилище сертификат, дополняя его паролем от сертификата
   }catch (Exception ex){
      Log.wtf("OMG",ex.getLocalizedMessage());//либо файла нет, либо пароль не тот
   }finally {
      in.close();
   }
   // Один из "столпов" клиентского SSL, отвечает за хранение всех сертификатов. Имеются разные варианты его настройки(разные алгоритмы)
   KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
   kmf.init(keyStore, "Your_Password".toCharArray());
   KeyManager[] keyManagers = kmf.getKeyManagers();

   //Второй элемент, который "должен" проверять, валидны ли наши сертификаты
   TrustManager[] wrappedTrustManagers = new TrustManager[]{
       new X509TrustManager() {
           public java.security.cert.X509Certificate[] getAcceptedIssuers() {
              return null;
            }
            public void checkClientTrusted(X509Certificate[] certs, String authType) { }
            public void checkServerTrusted(X509Certificate[] certs, String authType) {}
        }
   };
   SSLContext sslContext = SSLContext.getInstance("TLSv1");//Создаем контекст SSL по типу протокола
   sslContext.init(keyManagers, wrappedTrustManagers,  new java.security.SecureRandom());//инициализируем его
       return sslContext;// Радуемся =)
   }catch (Exception ex){
        Log.wtf("OMG", ex.getLocalizedMessage());// Печалимся ='(
        return null;
   }

The context can then be used when creating connections
//Устанавливаем контекст
   HttpsURLConnection.setDefaultSSLSocketFactory(методНаписанныйВыше().getSocketFactory());
    //Та самая "защита" которая говорит "мне плевать на всех, коннекчусь куда хочу". Виной этому самоподписанный сертификат.
   HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
   
   SchemeRegistry registry = new SchemeRegistry();

    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
    registry.register(new Scheme("Type_Of_Connection", socketFactory, 443));

    SingleClientConnManager mgr = new SingleClientConnManager(yourConnection.getParams(), registry);
    //Я работаю по https, по этому пример для него
    DefaultHttpClient httpClient = new DefaultHttpClient(mgr, yourConnection.getParams());

    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

For such a code, I would have killed myself, but alas, any attempts to fix it did not lead to success, I'm a hand-ass)
It is worth noting that I use the org.apache.http libraries and other deprecate things. I wish you to do everything according to the mind and beauty. I hope I helped)
If you have any questions, please contact.

R
relgames, 2015-09-10
@relgames

I would recommend not writing socket-server from scratch, but using Netty
maxrohde.com/2013/09/07/setting-up-ssl-with-netty

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question