· конфиденциалност и цялостност на обменяните в двете посоки данни;
· идентификация на сървъра;
· идентификация на клиента.
import
java.io.*; import java.net.*; public class HTTPClient { public static void main(String[] args) { int port = 80; // подразбиращ се http порт String host = "www.verisign.com"; try { InetAddress addr = InetAddress.getByName(host); Socket socket = new Socket(addr, port); Writer out = new OutputStreamWriter(socket.getOutputStream()); out.write("GET http://" + host + "/ HTTP/1.1\r\n"); out.write("Host: " + host + "\r\n"); out.write("\r\n"); out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader( socket.getInputStream())); // четене на заглавната част ( header) String s; while (!(s = in.readLine()).equals("")) { System.out.println(s); } System.out.println(); // четене на броя символи String contentLength = in.readLine(); int length = Integer.MAX_VALUE; try { length = Integer.parseInt(contentLength.trim(), 16); } catch (NumberFormatException ex) { System.out.println("This server doesn't send the content-length"); socket.close(); return; } System.out.print("Content Length = "); System.out.println(contentLength+ " ("+length+" characters)"); int c; int i = 0; while ((c = in.read()) != -1 && i++ < length) { System.out.write(c); } System.out.println(); socket.close(); } catch (IOException ex) { System.out.println(ex); } } |
В най-честияслучай, SSL се използва
между
идентифициран сървър и клиент
Ако протоколът е RSA, след първоначалната заявка на клиента, сървърът изпраща на клиента сертификационна верига. Клиентът използва последният сертификат във веригата за да криптира подходящ pre-master ключ , който се ипрaща обратно на сървъра. След това той се преобразува и в двете страни в симетричен криптиращ ключ, който в последствие се използва за криптиране.
import
java.io.*; import javax.net.ssl.*; public class HTTPSClient { public static void main(String[] args) { int port = 443; // подразбиращ се https порт String host = "www.verisign.com";; try { SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket socket = (SSLSocket) factory.createSocket(host, port); Writer out = new OutputStreamWriter(socket.getOutputStream()); socket.startHandshake(); out.write("GET http://" + host + "/ HTTP/1.1\r\n"); out.write("Host: " + host + "\r\n"); out.write("\r\n"); out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader( socket.getInputStream())); // четене на заглавната част ( header) String s; while (!(s = in.readLine()).equals("")) { System.out.println(s); } System.out.println(); // четене на броя символи String contentLength = in.readLine(); int length = Integer.MAX_VALUE; try { length = Integer.parseInt(contentLength.trim(), 16); } catch (NumberFormatException ex) { System.out.println("This server doesn't send the content-length"); return; } System.out.println("will send "+contentLength+ " = "+length+"characters\n"); int c; int i = 0; while ((c = in.read()) != -1 && i++ < length) { System.out.write(c); } System.out.println(); socket.close(); } catch (IOException ex) { System.err.println(ex); } } } |
import
java.util.Properties; import java.io.*; import java.net.*; import java.security.KeyStore; import javax.net.*; import javax.net.ssl.*; class ServeOneClient extends Thread { private Socket socket; private BufferedReader in; private PrintWriter out; public ServeOneClient(Socket s) throws IOException { socket = s; in = new BufferedReader( new InputStreamReader( socket.getInputStream())); // Enable auto-flush: out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true); System.out.println ("new client call"); start(); // Calls run() } public void run() { try { while (true) { String str = in.readLine(); System.out.println("Client sent: " + str); if (str.equalsIgnoreCase("END")){ out.println("client sent \"End\" - closing connection..."); System.out.println("Closing connection..."); break; }else { out.println("the client's line /"+str+ "/ has "+str.length()+" characters"); } } System.out.println("client sent \"End\" -closing..."); } catch (IOException e) { } finally { try { socket.close(); } catch(IOException e) {} } } } public class MultiClientSslServer { private static int port = 2001; public static void main(String args[])throws IOException { Properties props = System.getProperties(); props.put("javax.net.ssl.trustStore","samplecacerts"); props.put("javax.net.ssl.trustStorePassword","changeit"); ServerSocket ss=null; boolean auth = false; if (args.length >= 1) { if(args[0].equalsIgnoreCase("auth")){ auth=true; } } try { ServerSocketFactory ssf = getServerSocketFactory(); ss = ssf.createServerSocket(port); System.out.print("SslServer started"); if(auth){ ((SSLServerSocket)ss).setNeedClientAuth(true); System.out.println(" with client authentication"); } else{ System.out.println(" without client authentication"); } } catch (IOException e) { System.out.println("Unable to start MultiClientSslServer: " + e.getMessage()); e.printStackTrace(); } try { while(true) { // Blocks until a connection occurs: Socket socket = ss.accept(); try { new ServeOneClient(socket); } catch(IOException e) { socket.close(); } } } finally { ss.close(); } } private static ServerSocketFactory getServerSocketFactory() { SSLServerSocketFactory ssf = null; try { // set up key manager to do server authentication SSLContext ctx; KeyManagerFactory kmf; KeyStore ks; char[] passphrase = "passphrase".toCharArray(); ctx = SSLContext.getInstance("TLS"); kmf = KeyManagerFactory.getInstance("SunX509"); ks = KeyStore.getInstance("JKS"); ks.load(new FileInputStream("testkeys"), passphrase); kmf.init(ks, passphrase); ctx.init(kmf.getKeyManagers(), null, null); //подразбиращи се TrustManagerFactory ssf = ctx.getServerSocketFactory(); return ssf; } catch (Exception e) { e.printStackTrace(); return null; } } |
import
java.io.*; import javax.net.ssl.*; public class SSLClient { public static void main(String[] args) throws Exception { String message = ""; try { SSLSocketFactory factory = (SSLSocketFactory)SSLSocketFactory.getDefault(); SSLSocket socket = (SSLSocket)factory.createSocket("127.0.0.1", 2001); socket.startHandshake(); BufferedReader sin = new BufferedReader( new InputStreamReader(System.in)); PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter( socket.getOutputStream()))); BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream())); while(!message.equalsIgnoreCase("END")){ System.out.print("input a line (\"END\" to finish): "); message = sin.readLine(); out.println(message); out.flush(); if (out.checkError()) System.out.println( "SSLSocketClient: java.io.PrintWriter error"); /* read response */ String inputLine; if ((inputLine = in.readLine()) != null){ System.out.println("Server sends: "+inputLine); } else { System.out.println("No response from server"); } } in.close(); out.close(); socket.close(); } catch (Exception e) { e.printStackTrace(); } } } |
import
java.util.Properties; import java.security.KeyStore; import java.io.*; import javax.net.ssl.*; public class SSLAuthClient { public static void main(String[] args) throws Exception { String message = ""; Properties props = System.getProperties(); props.put("javax.net.ssl.trustStore","samplecacerts"); props.put("javax.net.ssl.trustStorePassword","changeit"); SSLSocketFactory factory = null; try { factory = getSocketFactory(); } catch (Exception e) { throw new IOException(e.getMessage()); } SSLSocket socket = (SSLSocket)factory.createSocket("127.0.0.1", 2001); socket.startHandshake(); BufferedReader sin = new BufferedReader( new InputStreamReader(System.in)); PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream()))); BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream())); while(!message.equalsIgnoreCase("END")){ System.out.print("input a line (\"END\" to finish): "); message = sin.readLine(); out.println(message); out.flush(); if (out.checkError()) System.out.println( "SSLSocketClient: java.io.PrintWriter error"); String inputLine; if ((inputLine = in.readLine()) != null){ System.out.println("Server sends: "+inputLine); } else { System.out.println("No response from server"); } } socket.close(); } private static SSLSocketFactory getSocketFactory() { SSLSocketFactory factory = null; try { // set up key manager to do server authentication SSLContext ctx; KeyManagerFactory kmf; KeyStore ks; char[] passphrase = "passphrase".toCharArray(); ctx = SSLContext.getInstance("TLS"); kmf = KeyManagerFactory.getInstance("SunX509"); ks = KeyStore.getInstance("JKS"); ks.load(new FileInputStream("testkeys"), passphrase); kmf.init(ks, passphrase); ctx.init(kmf.getKeyManagers(), null, null); factory = ctx.getSocketFactory(); return factory; } catch (Exception e) { e.printStackTrace(); return null; } } } |