java SSL 简单操作demo

SSL process :http://docs.oracle.com/javase/7/docs/technotes/guides/security/jsse/JSSERefGuide.html#HowSSLWorks

1、客户端服务器谈判协商可用的加密套件:

     在客户端与服务器开始的SSL session中,客户端发消息告诉服务器其自己所支持的加密套件列表:

        SSLSocket.getSupportedCipherSuites() ,然后服务器选择一个较好的加密套件

2、Authenticating the Server (认证服务器)

     该步骤实质为 客户端认证服务器,即客户端是否选择信任自己正在交流的服务器,其实该步骤是可选的。

    服务器为了证明自己就是自己所声称的身份,服务器需要向客户端出示自己的“ public key certificate”――

公开密钥证书,如果证书有效,则客户端就可以确认服务器的身份。

  服务器会与客户端交换信息使得双方同意该 secret key,例如RSA,客户端从服务器出示的 证书中获得public key,然后加密 secret key information,接着发送该加密的信息给服务器,服务器利用自己的private key 解密信息,以便认证客户端

3、Sending the Encrypted Data

Both the client and the server now have access to the same secret key. With each message, they use the cryptographic hash function, chosen in the first step of this process, and shared secret information, to compute an HMAC that they append to the message. They then use the secret key and the secret key algorithm negotiated in the first step of this process to encrypt the secure data and the HMAC. The client and server can now communicate securely using their encrypted and hashed data.

以下为ssl 消息的图:

java SSL 简单操作demo_第1张图片

The SSL messages are sent in the following order:

  1. Client hello - The client sends the server information including the highest version of SSL it supports and a list of the cipher suites it supports. (TLS 1.0 is indicated as SSL 3.1.) The cipher suite information includes cryptographic algorithms and key sizes.

  2. Server hello - The server chooses the highest version of SSL and the best cipher suite that both the client and server support and sends this information to the client.

  3. Certificate - The server sends the client a certificate or a certificate chain. A certificate chain typically begins with the server's public key certificate and ends with the certificate authority's root certificate. This message is optional, but is used whenever server authentication is required.

  4. Certificate request - If the server needs to authenticate the client, it sends the client a certificate request. In Internet applications, this message is rarely sent.

  5. Server key exchange - The server sends the client a server key exchange message when the public key information sent in message 3 above is not sufficient for key exchange. For example, in ciphersuites based on Diffie-Hellman, this message contains the server's DH public key.

  6. Server hello done - The server tells the client that it is finished with its initial negotiation messages.

  7. Certificate - If the server requests a certificate from the client in message 4, the client sends its certificate chain, just as the server did in message 3.

    Note: Only a few Internet server applications ask for a certificate from the client.

  8. Client key exchange - The client generates information used to create a key to use for symmetric encryption. For RSA, the client then encrypts this key information with the server's public key and sends it to the server. For ciphersuites based on Diffie-Hellman, this message contains the client's DH public key.

  9. Certificate verify - This message is sent when a client presents a certificate as previously explained. Its purpose is to allow the server to complete the process of authenticating the client. When this message is used, the client sends information that it digitally signs using a cryptographic hash function. When the server decrypts this information with the client's public key, the server is able to authenticate the client.

  10. Change cipher spec - The client sends a message telling the server to change to encrypted mode.

  11. Finished - The client tells the server that it is ready for secure data communication to begin.

  12. Change cipher spec - The server sends a message telling the client to change to encrypted mode.

  13. Finished - The server tells the client that it is ready for secure data communication to begin. This is the end of the SSL handshake.

  14. Encrypted data - The client and the server communicate using the symmetric encryption algorithm and the cryptographic hash function negotiated in messages 1 and 2, and using the secret key that the client sent to the server in Message 8. The handshake can be renegotiated at this time. See the next section for details.

  15. Close Messages - At the end of the connection, each side will send a close_notify message to inform the peer that the connection is closed.

If the parameters generated during an SSL session are saved, these parameters can sometimes be reused for future SSL sessions. Saving SSL session parameters allows encrypted communication to begin much more quickly.

import javax.net.ssl.*;
import java.security.*;

// Create/initialize the SSLContext with key material

char[] passphrase = "passphrase".toCharArray();

// First initialize the key and trust material.
KeyStore ksKeys = KeyStore.getInstance("JKS");
ksKeys.load(new FileInputStream("testKeys"), passphrase);
KeyStore ksTrust = KeyStore.getInstance("JKS");
ksTrust.load(new FileInputStream("testTrust"), passphrase);

// KeyManager's decide which key material to use.
KeyManagerFactory kmf =
    KeyManagerFactory.getInstance("SunX509");
kmf.init(ksKeys, passphrase);

// TrustManager's decide whether to allow connections.
TrustManagerFactory tmf =
    TrustManagerFactory.getInstance("SunX509");
tmf.init(ksTrust);

sslContext = SSLContext.getInstance("TLS");
sslContext.init(
    kmf.getKeyManagers(), tmf.getTrustManagers(), null);

// We're ready for the engine.
SSLEngine engine = sslContext.createSSLengine(hostname, port);

// Use as client
engine.setUseClientMode(true);

当下的web应用好多都转到了https,有时候需要利用java发送https请求,但是呢服务器有证书,又没有好的办法得到服务器证书,一般会自定义jsse里的信任管理器,让客户端不验证服务器的证书的有效性,此方法一般就叫绕过证书之类的,下面给一个参考demo:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**  
 * @Title: SSLDemo1.java
 * @Package 
 * @Description: TODO(用一句话描述该文件做什么)
 * @author huhu  
 * @date 2016年1月21日 上午10:08:45
 * @version V1.0  
 */
public class SSLDemo1 {

	
	public static void main(String[] args) throws Exception {
		
		
		trustAllHttpsCertificates();
		
		HostnameVerifier hv = new HostnameVerifier() {
			@Override
			public boolean verify(String hostname, SSLSession session) {
				 System.out.println("Warning: URL Host: " + hostname + " vs. " + session.getPeerHost());  
				 return true;  
			}
		};
		HttpsURLConnection.setDefaultHostnameVerifier(hv);
		
		// 在建立Https连接之前做如上处理后,后续就跟普通http处理一样
		
		
		
		
		URL url = new URL("https://dynamic.12306.cn/otsweb/main.jsp");
		HttpsURLConnection conn  = (HttpsURLConnection) url.openConnection();
		SSLContext sc = SSLContext.getInstance("SSL");
		conn.connect();
//		BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())) ;
//		String input = "" ;
//		
//		while((input = br.readLine()) != null){
//			 System.out.println(input);
//		}
		
	}

	private static void trustAllHttpsCertificates() throws Exception{
		
		TrustManager[] tms = new TrustManager[1];
		TrustManager tm = new CustomTrustManager();
		tms[0] = tm ;
		
		SSLContext context = SSLContext.getInstance("SSL");
		context.init(null, tms, null);
		HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
	}
	
	
	static class CustomTrustManager implements X509TrustManager{

		@Override
		public void checkClientTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
			
		}

		@Override
		public void checkServerTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
			
		}

		@Override
		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}
	}
}

Generating and Processing SSL/TLS data

The two main SSLEngine methods wrap() and unwrap() are responsible for generating and consuming network data respectively.

PKIX TrustManager Support

The default trust manager algorithm is "PKIX". The default can be changed by editing the ssl.TrustManagerFactory.algorithm property in the java.security file.

wKiom1ah-KLwJSJeAAA7Fj3zH5g500.png

HostnameVerifier

public class MyHostnameVerifier implements HostnameVerifier {

    public boolean verify(String hostname, SSLSession session) {
        // pop up an interactive dialog box
        // or insert additional matching logic
        if (good_address) {
            return true;
        } else {
            return false;
        }
    }
}
HttpsURLConnection urlc = (HttpsURLConnection)
  (new URL("https://www.sun.com/")).openConnection();
urlc.setHostnameVerifier(new MyHostnameVerifier());


你可能感兴趣的:(java,ssl,简单操作)