Page 1 of 2 12 LastLast
Results 1 to 20 of 22
  1. #1
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,423
    Blog Entries
    7
    Rep Power
    27

    Default configure SSL sockets?

    Greetings,

    In the old days (when everything was better), I had a sysadmin available; all I had to do is ask him to configure something for me. After some mysterious mumbo jumbo and some dragon blood and an occasional magic wand waving: voila, the configuration was done and I could continue working on my important stuff again.

    Not so nowadays: I'm self employed now and don't have a sysadmin available anymore. Until now, that wasn't a problem; I could manage do those silly things myself. Until somebody tried to convince me that my own home made http server needs to communicate over secure sockets. (yeah, right, the thingie only runs on a private network). Nevertheless, my http server can't defend itself against, ddos attacks, spoofing, snooping and what else ... I promised the guy I would implement secure sockets (if that would make him feel safer).

    I started reading and found those SSL sockets, including a factory: SSLServerSocketFactory. All I had to do was get my ServerSocket from that factory and define a few System properties that would tell where the certificate was and what the public password was. There is a tool available for that: keytool. No further intrusive coding was needed ...

    After a bit more reading and experimenting I am convinced I do need a sysadmin: all those tutorials don't make sense to me; I do understand what public key encryption and decryption is all about, but that keytool utility doesn't make sense to me: all I get is a lousy exception: 'Connection has been shutdown: javax.net.ssl.SSLHandshakeException: no cipher suites in common'.

    If some kind soul can tell me the exact lines how to make that keytool generate a CA signed certificate for my home made http server, I'd be extremely grateful; really, and you can get a nice cold Grolsch beer too, if you'd hop by once.

    Please don't tell me to read the keytool manual: I already did so, numerous times, but I'm doing something wrong (but what?) I'm just a simple math guy who isn't made for configuration purposes and I don't have any dragon blood nor a magic wand available like my old sysadmin had.

    kind regards,

    Jos
    Build a wall around Donald Trump; I'll pay for it.

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: configure SSL sockets?

    Hope you find out and tell the rest of us. I coded a simple HTTP server years ago (copied most of the code from a textbook) and have been using it for years for testing server stuff.
    I tried to add SSL once and gave up.
    I found this page that looks useful: https://www.owasp.org/index.php/Usin...ket_Extensions
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,423
    Blog Entries
    7
    Rep Power
    27

    Default Re: configure SSL sockets?

    Thanks for the link; I read it but it didn't help me any further. I think that keytool thing can do too much: it can handle keystores and truststores and certificates and certificate requests and it can clean you dirty dishes and I must be way too stupid to understand it all ;-) I just can't get my head around it and I'm afraid I need to be spoonfed with a boilerplate example *sigh* ...

    kind regards,

    Jos
    Build a wall around Donald Trump; I'll pay for it.

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: configure SSL sockets?

    Do you have a certificate? They used to cost $s but now I think there are some free ones available.
    I don't have a certificate to test with. I applied to one of the free sites and am waiting their response.
    Last edited by Norm; 11-07-2016 at 02:18 AM.
    If you don't understand my response, don't ignore it, ask a question.

  5. #5
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,423
    Blog Entries
    7
    Rep Power
    27

    Default Re: configure SSL sockets?

    All I have is a 'self signed' certificate; that should be good enough, although my browser(s) might protest, but all I get is that silly exception ... I also read (on an IBM site) that the default value for the keystore is the (system wide) file 'cacerts' in the $(JAVA_HOME)/lib/security directory; on my installation that store contains 57 certificates, but that one doesn't work either ...

    kind regards,

    Jos
    Build a wall around Donald Trump; I'll pay for it.

  6. #6
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,989
    Rep Power
    8

    Default Re: configure SSL sockets?

    Let me get this straight, you have a HTTP server running in Java and you want it to use a keystore to get its certificate from? Because I have Wildfly running with HTTPS and it's also using a keystore. I generate the keystore using Java code, so I would be able to share that.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  7. #7
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,423
    Blog Entries
    7
    Rep Power
    27

    Default Re: configure SSL sockets?

    Quote Originally Posted by SurfMan View Post
    Let me get this straight, you have a HTTP server running in Java and you want it to use a keystore to get its certificate from? Because I have Wildfly running with HTTPS and it's also using a keystore. I generate the keystore using Java code, so I would be able to share that.
    Basically yes: the documentation gives the impression that most of the SSL package runs in a non-intrusive way: all I (should) have to do is create my ServerSocket using a SSLServerSocketFactory and set a few System.properties ... (they should point to my keystore and define its password). For the definition of my keystore I juggled with that silly keytool (as the documentation wanted me to do so); to no avail ...

    kind regards,

    Jos
    Build a wall around Donald Trump; I'll pay for it.

  8. #8
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,423
    Blog Entries
    7
    Rep Power
    27

    Default Re: configure SSL sockets?

    f.w.i.w. this is how I created the self signed certificate:

    Java Code:
    keytool -genkey -keyalg RSA -alias selfsigned -keystore keystore.jks -storepass adminjwd2 -validity 3650 -keysize 2048
    and this is what keytool showed afterwards (after doing 'keytool -v -list -keystore keystore.jks):

    Java Code:
    Enter keystore password:
    
    Keystore type: JKS
    Keystore provider: SUN
    
    Your keystore contains 1 entry
    
    Alias name: selfsigned
    Creation date: 06-Nov-2016
    Entry type: PrivateKeyEntry
    Certificate chain length: 1
    Certificate[1]:
    Owner: CN=192.168.1.66:9090, OU=jwd2, O=jwd2, L=Voorschoten, ST=ZH, C=NL
    Issuer: CN=192.168.1.66:9090, OU=jwd2, O=jwd2, L=Voorschoten, ST=ZH, C=NL
    Serial number: 1ff27620
    Valid from: Sun Nov 06 13:19:38 CET 2016 until: Wed Nov 04 13:19:38 CET 2026
    Certificate fingerprints:
             MD5:  37:DD:E5:72:ED:D5:56:C4:95:14:C7:A0:08:18:CA:5B
             SHA1: D7:FD:29:36:95:03:FE:CA:BE:78:FC:26:7C:28:66:E2:61:32:91:D4
             SHA256: 7F:F1:79:60:E4:77:72:AE:66:98:7E:3B:6D:D1:AB:47:44:A0:02:00:87:D8:81:3A:15:4B:20:A7:54:9E:97:06
             Signature algorithm name: SHA256withRSA
             Version: 3
    
    Extensions:
    
    #1: ObjectId: 2.5.29.14 Criticality=false
    SubjectKeyIdentifier [
    KeyIdentifier [
    0000: F6 09 B7 35 75 FA A8 8E   F0 1D 88 EE 9D B1 2C B1  ...5u.........,.
    0010: 28 0C D9 30                                        (..0
    ]
    ]
    
    
    
    *******************************************
    *******************************************
    I can't see anything wrong (or right) in this certificate ...

    kind regards,

    Jos
    Build a wall around Donald Trump; I'll pay for it.

  9. #9
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: configure SSL sockets?

    I think there is a difference between signing and having a certificate. Still doing research: https://en.wikipedia.org/wiki/Certificate_authority
    If you don't understand my response, don't ignore it, ask a question.

  10. #10
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,423
    Blog Entries
    7
    Rep Power
    27

    Default Re: configure SSL sockets?

    Quote Originally Posted by Norm View Post
    I think there is a difference between signing and having a certificate. Still doing research: https://en.wikipedia.org/wiki/Certificate_authority
    Yep, true; that keytool command (see above) generates a certificates that is signed by me (it is 'self signed'); that of course doesn't make it a 'trusted' certificate (who trusts me?)
    but it should work, possibly after a warning on the client side, but it doesn't work and I don't understand zilch about it all ...

    kind regards,

    Jos
    Build a wall around Donald Trump; I'll pay for it.

  11. #11
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: configure SSL sockets?

    For today's experiment I tried this with my JDK version 6 system:
    //http://stackoverflow.com/questions/3775483/ssl-handshake-exception
    After creating a self-signed certificate it is required to export that certificate to the "cacert" file.
    In my case it was located in /usr/lib/java/jre/lib/security/cacert.
    You can export the certficate by using the keytool (you probably have to have root access):

    $ sudo keytool -exportcert -alias keyStoreAlias -keystore keyStoreKeys.keys -file /usr/local/java/jre/lib/security/cacerts
    My batch file:
    @Rem export cert to ca
    keytool -exportcert -alias NormsKey -keystore NormsKeyStore -file D:\Java\jdk1.6.0_29\jre\lib\security\cacerts
    MORE
    I got a new set of error messages:
    Exception occurred .... java.net.SocketException: java.security.NoSuchAlgorithmException: Error constructing implementation (algorithm: Default, provider: SunJSSE, class: com.sun.net.ssl.internal.ssl.DefaultSSLContextImpl )
    java.net.SocketException: java.security.NoSuchAlgorithmException: Error constructing implementation (algorithm: Default, provider: SunJSSE, class: com.sun.net.ssl.internal.ssl.DefaultSSLContextImpl )
    Before the messages started with:
    Exception occurred .... javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown
    javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown
    If you don't understand my response, don't ignore it, ask a question.

  12. #12
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,989
    Rep Power
    8

    Default Re: configure SSL sockets?

    With this command line I got a certificate that works if you let the JLHTTP server use it via properties:

    Java Code:
    keytool -genkey -keyalg RSA -alias selfsigned -keystore surfman.keystore -storepass foobar123 -validity 360 -keysize 2048
    And the JLHTTP code:
    Java Code:
    try {
        HTTPServer server = new HTTPServer(8090);
        server.setSecure(true);
        HTTPServer.VirtualHost virtualHost = server.getVirtualHost(null);
        virtualHost.setAllowGeneratedIndex(true);
        virtualHost.addContext("/", new HTTPServer.FileContextHandler(new File("/home/surfman/temp"), "/"), "GET");
        server.start();
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    These are the properties on the JVM:
    Java Code:
    -Djavax.net.ssl.keyStore=/home/surfman/temp/surfman.keystore
    -Djavax.net.ssl.keyStorePassword=foobar123
    You will ofcourse get your usual warnings in the browser about the home-brew certs, but when adding an exception, it works like a charm.

    configure SSL sockets?-hbinijmijagbdfkm.png
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  13. #13
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,423
    Blog Entries
    7
    Rep Power
    27

    Default Re: configure SSL sockets?

    Quote Originally Posted by Norm View Post
    For today's experiment I tried this with my JDK version 6 system:
    My batch file:

    I got a new set of error messages:
    Before the messages started with:
    Exporting a self signed certificate to the cacerts store is not going to help you: the store/file is supposed to contain authorized certificates which should be available system wide. Better remove that certificate again. In the mean time I made a little progress (thanks to SurfMan): on my Raspberry Pi everything fails, but on a little laptop, everything runs as expected: my browser protest against the self signed certificate but allow me to trust it nevertheless. I still can't make the Raspberry Pi behave as it should ...

    kind regards,

    Jos
    Build a wall around Donald Trump; I'll pay for it.

  14. #14
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,423
    Blog Entries
    7
    Rep Power
    27

    Default Re: configure SSL sockets?

    @Norm, a keystore as follows works for me on a MicroSoft Windows system:

    Java Code:
    keytool -genkey -keyalg DSA -alias selfsigned -keystore <your keystore>.jks -storepass password -validity 360
    It is self signed and your browser protests against it (you have to manually make it approve the certificate).

    kind regards,

    Jos
    Build a wall around Donald Trump; I'll pay for it.

  15. #15
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: configure SSL sockets?

    No luck with that. Here is what I get:

    Batch file to build keystore:
    @rem build test keystore
    D:\Java\jdk1.6.0_29\bin\keytool.exe -genkey -keyalg DSA -alias selfsigned -keystore JosAH.jks -storepass password -validity 360
    MORE


    Console when test program executed:
    D:\www\JNLP_jars>D:\Java\jdk1.6.0_29\bin\java.exe -Djavax.net.ssl.keyStore=JosAH.jks -Djavax.net.ssl.keyStorePassword=password SSL_Tester Args
    args=[Args] <<< debug output
    Priv exp --- null
    Exception occurred .... java.net.SocketException: java.security.NoSuchAlgorithmException: Error constructing implementation (algorithm: Default, provider: SunJSSE, class: com.sun.net.ssl.internal.ssl.DefaultSSLContextImpl )
    java.net.SocketException: java.security.NoSuchAlgorithmException: Error constructing implementation (algorithm: Default, provider: SunJSSE, class: com.sun.net.ssl.internal.ssl.DefaultSSLContextImpl )
    at javax.net.ssl.DefaultSSLServerSocketFactory.throwE xception(SSLServerSocketFactory.java:142)
    at javax.net.ssl.DefaultSSLServerSocketFactory.create ServerSocket(SSLServerSocketFactory.java:149)
    at SSL_Tester$SSLServer.main(SSL_Tester.java:176)
    at SSL_Tester$1.run(SSL_Tester.java:123)
    at java.lang.Thread.run(Thread.java:662)
    Caused by: java.security.NoSuchAlgorithmException: Error constructing implementation (algorithm: Default, provider: SunJSSE, class: com.sun.net.ssl.internal.ssl.DefaultSSLContextImpl )
    at java.security.Provider$Service.newInstance(Provide r.java:1245)
    at sun.security.jca.GetInstance.getInstance(GetInstan ce.java:220)
    at sun.security.jca.GetInstance.getInstance(GetInstan ce.java:147)
    at javax.net.ssl.SSLContext.getInstance(SSLContext.ja va:125)
    at javax.net.ssl.SSLContext.getDefault(SSLContext.jav a:68)
    at javax.net.ssl.SSLServerSocketFactory.getDefault(SS LServerSocketFactory.java:96)
    at SSL_Tester$SSLServer.main(SSL_Tester.java:175)
    ... 2 more
    Caused by: java.security.UnrecoverableKeyException: Cannot recover key
    at sun.security.provider.KeyProtector.recover(KeyProt ector.java:311)
    at sun.security.provider.JavaKeyStore.engineGetKey(Ja vaKeyStore.java:121)
    at sun.security.provider.JavaKeyStore$JKS.engineGetKe y(JavaKeyStore.java:38)
    at java.security.KeyStore.getKey(KeyStore.java:763)
    at com.sun.net.ssl.internal.ssl.SunX509KeyManagerImpl .<init>(SunX509KeyManagerImpl.java:113)
    at com.sun.net.ssl.internal.ssl.KeyManagerFactoryImpl $SunX509.engineInit(KeyManagerFactoryImpl.java:48)
    at javax.net.ssl.KeyManagerFactory.init(KeyManagerFac tory.java:239)
    at com.sun.net.ssl.internal.ssl.DefaultSSLContextImpl .getDefaultKeyManager(DefaultSSLContextImpl.java:1 70)
    at com.sun.net.ssl.internal.ssl.DefaultSSLContextImpl .<init>(DefaultSSLContextImpl.java:40)
    at sun.reflect.NativeConstructorAccessorImpl.newInsta nce0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInsta nce(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newI nstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Construc tor.java:513)
    at java.lang.Class.newInstance0(Class.java:355)
    at java.lang.Class.newInstance(Class.java:308)
    at java.security.Provider$Service.newInstance(Provide r.java:1221)
    ... 8 more

    Note: I'm not working on this as a project so it's up to JosAH to continue if he wants. I'll be done.
    Last edited by Norm; 11-10-2016 at 01:44 AM.
    If you don't understand my response, don't ignore it, ask a question.

  16. #16
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,423
    Blog Entries
    7
    Rep Power
    27

    Default Re: configure SSL sockets?

    @Norm: I tested it with Windows 10 and the MicroSoft Edge browser; your browser doesn't support the DSA algorithm. I don't know how to check the supported en/decryption algorithms in browsers ...

    kind regards,

    Jos
    Build a wall around Donald Trump; I'll pay for it.

  17. #17
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: configure SSL sockets?

    In case anyone was wondering what java code I was using:
    Java Code:
    /* https://www.owasp.org/index.php/Using_the_Java_Secure_Socket_Extensions
    
    The initial handshake on this connection can be initiated in one of three ways:
    
    calling startHandshake which explicitly begins handshakes, or
    any attempt to read or write application data on this socket causes an implicit handshake, or
    a call to getSession tries to set up a session if there is no currently valid session, and an implicit handshake is done.
    
    If handshaking fails for any reason, the SSLSocket is closed, and no further communications can be done.
    
    //https://community.oracle.com/thread/1146413?start=0
     If your server's certificate isn't signed by a recognized CA you have to import it into your truststore
    
    //================================================================================
    //http://stackoverflow.com/questions/3775483/ssl-handshake-exception
    After creating a self-signed certificate it is required to export that certificate to the "cacert" file. 
    In my case it was located in /usr/lib/java/jre/lib/security/cacert. 
    You can export the certficate by using the keytool (you probably have to have root access):
    
    $ sudo keytool -exportcert -alias keyStoreAlias -keystore keyStoreKeys.keys -file /usr/local/java/jre/lib/security/cacerts
    
    =======================================================================================================================
    The problem you're having is with the certificates. Here is a list of things you might need to be familiar with 
    before working with a secure SSL program. There must be a truststore, keystore, and the certs have to be added.
    To add the key to your cacerts file, as in step 6, the computer might ask you for a password that you don't know. 
    It is "changeit" mostt likely
    
    1) To create a new keystore and self-signed certificate with corresponding public/private keys:
    
     keytool -genkeypair -alias "username" -keyalg RSA -validity 7 -keystore keystore
    
    2) To Examine the keystore:
    
    keytool -list -v -keystore keystore
    
    3) Export and examine the self-signed certificate:
    
    keytool -export -alias "username" -keystore keystore -rfc -file "username".cer
    
    4) Import the certificate into a new truststore:
    
    keytool -import -alias "username" -file "username".cer -keystore truststore
    
    5) Examine the truststore:
    
    keytool -list -v -keystore truststore
    
    6) Add to keystore (this is what your looking for):
    
    sudo keytool -import -file "username".cer -alias "username" -keystore "path-to-keystore"
    
    On some systems this is found in
    
    /usr/lib/jvm/<java version folder>/jre/lib/security/cacerts
    and on other systems it is something like
    
    /etc/ssl/certs/java/cacerts
    
    //===========================================================================================================================
    //http://stackoverflow.com/questions/29485987/ssl-exception-javax-net-ssl-sslhandshakeexception-received-fatal-alert-certif
    For SSLClient :-
            System.setProperty("javax.net.ssl.trustStore","client.jks");
            System.setProperty("javax.net.ssl.trustStorePassword", "123456");
    
    //=================================================================
    //http://www.java-forums.org/networking/96447-configure-ssl-sockets.html#post414610
    keytool -genkey -keyalg RSA -alias selfsigned -keystore surfman.keystore -storepass foobar123 -validity 360 -keysize 2048
    
    And the JLHTTP code:
    Java Code:
    
    
    try {
        HTTPServer server = new HTTPServer(8090);
        server.setSecure(true);
        HTTPServer.VirtualHost virtualHost = server.getVirtualHost(null);
        virtualHost.setAllowGeneratedIndex(true);
        virtualHost.addContext("/", new HTTPServer.FileContextHandler(new File("/home/surfman/temp"), "/"), "GET");
        server.start();
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    
    These are the properties on the JVM:
    Java Code:
    -Djavax.net.ssl.keyStore=/home/surfman/temp/surfman.keystore
    -Djavax.net.ssl.keyStorePassword=foobar123
    
    */
    
    import java.io.*;
    import java.security.Security;
    import java.security.PrivilegedActionException;
    
    import javax.net.ssl.*;
    import com.sun.net.ssl.*;
    import com.sun.net.ssl.internal.ssl.Provider;
    
    
    /**
     * @author Joe Prasanna Kumar
     * This program simulates an SSL Server listening on a specific port for client requests
     * 
     * Algorithm:
     * 1. Regsiter the JSSE provider
     * 2. Set System property for keystore by specifying the keystore which contains the server certificate
     * 3. Set System property for the password of the keystore which contains the server certificate
     * 4. Create an instance of SSLServerSocketFactory
     * 5. Create an instance of SSLServerSocket by specifying the port to which the SSL Server socket needs to bind with
     * 6. Initialize an object of SSLSocket
     * 7. Create InputStream object to read data sent by clients
     * 8. Create an OutputStream object to write data back to clients.
     * 
     */ 
    
    public class SSL_Tester {
    
       public static void main(final String[] args) {
          System.out.println("args="+java.util.Arrays.toString(args)); //<<<<<<<
          Thread t1 = new Thread(new Runnable() {
             public void run() {
                try{SSLServer.main(args);}catch(Exception x){x.printStackTrace();}
             }
          });
          t1.start();
    
          try{Thread.sleep(100);}catch(Exception x){}    //  let server get started
    
          if(args.length == 0) {
             Thread t2 = new Thread(new Runnable() {
                public void run() {
                   try{SSLClient.main(args);}catch(Exception x){x.printStackTrace();}
                }
             });
             t2.start();
          }
          // wait and exit   in case not able to end manually
          try{Thread.sleep(25000);}catch(Exception x){}
          System.out.println("Exiting main");
          System.exit(0);
     
       }  //  end main()>>>>>>>>>>>>>>>>>>>>>>>>>>
    
    
    
    
    static class SSLServer {
    
    	/**
    	 * @param args
    	 */
    
    	public static void main(String[] args) throws Exception {
    
    		int intSSLport = 4443; // Port where the SSL Server needs to listen for new requests from the client
    
    		{     //???? why {}s
    			// Registering the JSSE provider
    			Security.addProvider(new Provider());
    
    			//Specifying the Keystore details
             if(args.length == 0 || args[0].equals("ARGS")) {  // for testing w/o args - bat with args will set these
             System.out.println("args="+java.util.Arrays.toString(args));          //<<<<<<<
    			System.setProperty("javax.net.ssl.keyStore","NormsKeystore");            //<<<<<<<<<
    			System.setProperty("javax.net.ssl.keyStorePassword","password");
             }
    
    			// Enable debugging to view the handshake and communication which happens between the SSLClient and the SSLServer
    //			System.setProperty("javax.net.debug","all");  //<<<<<<<<< gives lots of output!!!!
    		}
    
    		try {
    				// Initialize the Server Socket
    				SSLServerSocketFactory sslServerSocketfactory = (SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
    				SSLServerSocket sslServerSocket = (SSLServerSocket)sslServerSocketfactory.createServerSocket(intSSLport);  //<<<<<<<< 55
    				SSLSocket sslSocket = (SSLSocket)sslServerSocket.accept();
                System.out.println("accept socket="+sslSocket); //<<<<<<<<<
                // accept socket=18ceff1[SSL_NULL_WITH_NULL_NULL: Socket[addr=/127.0.0.1,port=52814,localport=4443]]
                // accept socket=62d56[SSL_NULL_WITH_NULL_NULL: Socket[addr=/127.0.0.1,port=56296,localport=4443]]
    
    
    				// Create Input / Output Streams for communication with the client
    				while(true)
    				{
    				  PrintWriter out = new PrintWriter(sslSocket.getOutputStream(), true);      // 61 java.net.SocketException: Socket is closed
    		        BufferedReader in = new BufferedReader(
    						      new InputStreamReader(
    								      sslSocket.getInputStream()));
    		        String inputLine, outputLine;
    
    		        while ((inputLine = in.readLine()) != null) {     //<<<<<<<<<< 106 javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown
    		             out.println(inputLine);
    		             System.out.println("S "+inputLine);
    		        }
    
    		        // Close the streams and the socket
    		        out.close();
    		        in.close();
    		        sslSocket.close();
    		        sslServerSocket.close();
    
    				}
    			}
    
    
    		catch(Exception exp)
    		{
    			PrivilegedActionException priexp = new PrivilegedActionException(exp);
    			System.out.println(" Priv exp --- " + priexp.getMessage());
    
    			System.out.println(" Exception occurred .... " +exp);
    			exp.printStackTrace();
    		}
    
    	}     // end main()
    
    }
    
    //package org.owasp.crypto;
    
    
    /**
     * @author Joe Prasanna Kumar
     * This program simulates a client socket program which communicates with the SSL Server
     * 
     * Algorithm:
     * 1. Determine the SSL Server Name and port in which the SSL server is listening
     * 2. Register the JSSE provider
     * 3. Create an instance of SSLSocketFactory
     * 4. Create an instance of SSLSocket
     * 5. Create an OutputStream object to write to the SSL Server
     * 6. Create an InputStream object to receive messages back from the SSL Server
     * 
     */ 
    
    static class SSLClient {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) throws Exception{
    		String strServerName = "localhost"; // SSL Server Name
    		int intSSLport = 4443; // Port where the SSL Server is listening
    		PrintWriter out = null;
          BufferedReader in = null;
    
    		{
    			// Registering the JSSE provider
    			Security.addProvider(new Provider());
    		}
    
    		try {
    			// Creating Client Sockets
    			SSLSocketFactory sslsocketfactory = (SSLSocketFactory)SSLSocketFactory.getDefault();
    			SSLSocket sslSocket = (SSLSocket)sslsocketfactory.createSocket(strServerName,intSSLport);
    
             	// Initializing the streams for Communication with the Server
             	out = new PrintWriter(sslSocket.getOutputStream(), true);
             	in = new BufferedReader(new InputStreamReader(sslSocket.getInputStream()));
    
             StringReader sr = new StringReader("a message\nwith 2 lines\n");
    			BufferedReader stdIn = new BufferedReader(sr); //new InputStreamReader(System.in));
    			String userInput = "Hello Testing ";
    			out.println(userInput);
             System.out.println("C - entering while"); //<<<<<<<
    
    			while ((userInput = stdIn.readLine()) != null) {
    			    out.println(userInput);
    			    System.out.println("echo: " + userInput);
    			}
    
    			out.println(userInput);    //????
             System.out.println("S closing"); //<<<<<<<<<<<<
    
    			// Closing the Streams and the Socket
    			out.close();
    			in.close();
    			stdIn.close();
    			sslSocket.close();
    		}
    
    		catch(Exception exp)
    		{
    			System.out.println(" Exception occurred .... " +exp);
    			exp.printStackTrace();
    		}
    
    	}
    
    }
    
    }
    If you don't understand my response, don't ignore it, ask a question.

  18. #18
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,989
    Rep Power
    8

    Default Re: configure SSL sockets?

    To make a Java server use a selfsigned certificate, you could use my solution.
    To make a Java client accept a selfsigned vertificate you can create a SSLSocketFactory that accepts whatever you throw at it. See Howardism: Accepting Self-Signed SSL Certificates in Java
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  19. #19
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,423
    Blog Entries
    7
    Rep Power
    27

    Default Re: configure SSL sockets?

    Quote Originally Posted by SurfMan View Post
    To make a Java server use a selfsigned certificate, you could use my solution.
    To make a Java client accept a selfsigned vertificate you can create a SSLSocketFactory that accepts whatever you throw at it. See Howardism: Accepting Self-Signed SSL Certificates in Java
    Hold on a sec: those darn sockets are supposed to work in a non-intusive way: i.e. just fiddle with the keytool tool and define a few properties and use a SSLServerSocketFactory in the code; so far I only had a bit of luck on a MicroSoft Windows 10 laptop and on a Linux laptop; my Raspbery Pi refuses to work (it has an ordinary Oracle JSE installation); can we conclude that the implementation on the Pi is just broken?

    kind regards,

    Jos
    Build a wall around Donald Trump; I'll pay for it.

  20. #20
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,423
    Blog Entries
    7
    Rep Power
    27

    Default Re: configure SSL sockets?

    I solved this nasty issue (at least for me); the system runs on a Raspberry Pi; it is an IoT thingy and handles a couple of other devices 'over the air' (read: 2.4GHz) and the micro controllers for those devices are way too small to handle ssl sockets; consequently that Pi has to handle ordinary sockets as well as an ssl server socket (for the outside world). After some experimenting (read: furious hacking with a lot of tobacco and espresso coffee and the occasional Grolsch beers), I noticed that a stand alone http server did work on that tiny Pi thingy, while it failed miserably (see all replies above) in my full system. I decided to initialize my hhtp server first, before anything else was initialized and: voila, the thing worked. I don't know the reason for it, because all those modules are more or less independent of each other ...

    thanks to the folks that tried to help me and

    kind regards,

    Jos

    ps. now I have to figure out what was in the way of those silly ssl sockets on that Pi.
    Build a wall around Donald Trump; I'll pay for it.

Page 1 of 2 12 LastLast

Similar Threads

  1. configure publishing
    By BenitoJuarez in forum Eclipse
    Replies: 0
    Last Post: 04-26-2013, 01:36 PM
  2. how to configure DSN....??
    By bonjovi4u in forum JDBC
    Replies: 20
    Last Post: 05-19-2010, 10:54 AM
  3. How to configure jmf in net beans
    By ishan in forum NetBeans
    Replies: 0
    Last Post: 01-08-2010, 06:44 AM
  4. Configure Classpath
    By Doctor Cactus in forum New To Java
    Replies: 3
    Last Post: 01-08-2009, 01:11 PM
  5. How to configure "keep alive" in Sockets?
    By rajdotme in forum Networking
    Replies: 1
    Last Post: 04-16-2008, 11:36 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •