有關(guān)SSL的原理和介紹在網(wǎng)上已經(jīng)有不少,對于Java下使用keytool生成證書,,配置SSL通信的教程也非常多,。但如果我們不能夠親自動(dòng)手做一個(gè)SSL Sever和SSL Client,可能就永遠(yuǎn)也不能深入地理解Java環(huán)境下,,SSL的通信是如何實(shí)現(xiàn)的。對SSL中的各種概念的認(rèn)識也可能會(huì)僅限于可以使用的程度,。本文通過構(gòu)造一個(gè)簡單的SSL Server和SSL Client來講解Java環(huán)境下SSL的通信原理,。
首先我們先回顧一下常規(guī)的Java Socket編程。在Java下寫一個(gè)Socket服務(wù)器和客戶端的例子還是比較簡單的,。以下是服務(wù)端的代碼:
Java代碼
1.package org.bluedash.tryssl;
2.
3.import java.io.BufferedReader;
4.import java.io.IOException;
5.import java.io.InputStbreamReader;
6.import java.io.PrintWriter;
7.import java.net.ServerSocket;
8.import java.net.Socket;
9.
10.public class Server extends Thread {
11. private Socket socket;
12.
13. public Server(Socket socket) {
14. this.socket = socket;
15. }
16.
17. public void run() {
18. try {
19. BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
20. PrintWriter writer = new PrintWriter(socket.getOutputStream());
21.
22. String data = reader.readLine();
23. writer.println(data);
24. writer.close();
25. socket.close();
26. } catch (IOException e) {
27.
28. }
29. }
30.
31. public static void main(String[] args) throws Exception {
32. while (true) {
33. new Server((new ServerSocket(8080)).accept()).start();
34. }
35. }
36.}
服務(wù)端很簡單:偵聽8080端口,,并把客戶端發(fā)來的字符串返回去。下面是客戶端的代碼:
Java代碼
1.package org.bluedash.tryssl;
2.
3.import java.io.BufferedReader;
4.import java.io.InputStreamReader;
5.import java.io.PrintWriter;
6.import java.net.Socket;
7.
8.public class Client {
9.
10. public static void main(String[] args) throws Exception {
11.
12. Socket s = new Socket("localhost", 8080);
13.
14. PrintWriter writer = new PrintWriter(s.getOutputStream());
15. BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
16. writer.println("hello");
17. writer.flush();
18. System.out.println(reader.readLine());
19. s.close();
20. }
21.
22.}
客戶端也非常簡單:向服務(wù)端發(fā)起請求,,發(fā)送一個(gè)"hello"字串,,然后獲得服務(wù)端的返回。把服務(wù)端運(yùn)行起來后,,執(zhí)行客戶端,,我們將得到"hello"的返回。
就是這樣一套簡單的網(wǎng)絡(luò)通信的代碼,,我們來把它改造成使用SSL通信,。在SSL通信協(xié)議中,我們都知道首先服務(wù)端必須有一個(gè)數(shù)字證書,,當(dāng)客戶端連接到服務(wù)端時(shí),,會(huì)得到這個(gè)證書,然后客戶端會(huì)判斷這個(gè)證書是否是可信的,,如果是,,則交換信道加密密鑰,進(jìn)行通信,。如果不信任這個(gè)證書,,則連接失敗。
因此,,我們首先要為服務(wù)端生成一個(gè)數(shù)字證書,。Java環(huán)境下,數(shù)字證書是用keytool生成的,,這些證書被存儲(chǔ)在store的概念中,,就是證書倉庫,。我們來調(diào)用keytool命令為服務(wù)端生成數(shù)字證書和保存它使用的證書倉庫:
Bash代碼
1.keytool -genkey -v -alias bluedash-ssl-demo-server -keyalg RSA -keystore ./server_ks -dname "CN=localhost,OU=cn,O=cn,L=cn,ST=cn,C=cn" -storepass server -keypass 123123
keytool -genkey -v -alias bluedash-ssl-demo-server -keyalg RSA -keystore ./server_ks -dname "CN=localhost,OU=cn,O=cn,L=cn,ST=cn,C=cn" -storepass server -keypass 123123
這樣,我們就將服務(wù)端證書bluedash-ssl-demo-server保存在了server_ksy這個(gè)store文件當(dāng)中,。有關(guān)keytool的用法在本文中就不再多贅述,。執(zhí)行上面的命令得到如下結(jié)果:
Bash代碼
1.Generating 1,024 bit RSA key pair and self-signed certificate (SHA1withRSA) with a validity of 90 days
2. for: CN=localhost, OU=cn, O=cn, L=cn, ST=cn, C=cn
3.[Storing ./server_ks]
Generating 1,024 bit RSA key pair and self-signed certificate (SHA1withRSA) with a validity of 90 days
for: CN=localhost, OU=cn, O=cn, L=cn, ST=cn, C=cn
[Storing ./server_ks]
然后,改造我們的服務(wù)端代碼,,讓服務(wù)端使用這個(gè)證書,,并提供SSL通信:
Java代碼
1.package org.bluedash.tryssl;
2.
3.import java.io.BufferedReader;
4.import java.io.FileInputStream;
5.import java.io.IOException;
6.import java.io.InputStreamReader;
7.import java.io.PrintWriter;
8.import java.net.ServerSocket;
9.import java.net.Socket;
10.import java.security.KeyStore;
11.
12.import javax.net.ServerSocketFactory;
13.import javax.net.ssl.KeyManagerFactory;
14.import javax.net.ssl.SSLContext;
15.import javax.net.ssl.SSLServerSocket;
16.
17.public class SSLServer extends Thread {
18. private Socket socket;
19.
20. public SSLServer(Socket socket) {
21. this.socket = socket;
22. }
23.
24. public void run() {
25. try {
26. BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
27. PrintWriter writer = new PrintWriter(socket.getOutputStream());
28.
29. String data = reader.readLine();
30. writer.println(data);
31. writer.close();
32. socket.close();
33. } catch (IOException e) {
34.
35. }
36. }
37.
38. private static String SERVER_KEY_STORE = "/Users/liweinan/projs/ssl/src/main/resources/META-INF/server_ks";
39. private static String SERVER_KEY_STORE_PASSWORD = "123123";
40.
41. public static void main(String[] args) throws Exception {
42. System.setProperty("javax.net.ssl.trustStore", SERVER_KEY_STORE);
43. SSLContext context = SSLContext.getInstance("TLS");
44.
45. KeyStore ks = KeyStore.getInstance("jceks");
46. ks.load(new FileInputStream(SERVER_KEY_STORE), null);
47. KeyManagerFactory kf = KeyManagerFactory.getInstance("SunX509");
48. kf.init(ks, SERVER_KEY_STORE_PASSWORD.toCharArray());
49.
50. context.init(kf.getKeyManagers(), null, null);
51.
52. ServerSocketFactory factory = context.getServerSocketFactory();
53. ServerSocket _socket = factory.createServerSocket(8443);
54. ((SSLServerSocket) _socket).setNeedClientAuth(false);
55.
56. while (true) {
57. new SSLServer(_socket.accept()).start();
58. }
59. }
60.}
可以看到,服務(wù)端的Socket準(zhǔn)備設(shè)置工作大大增加了,,增加的代碼的作用主要是將證書導(dǎo)入并進(jìn)行使用,。此外,,所使用的Socket變成了SSLServerSocket,,另外端口改到了8443(這個(gè)不是強(qiáng)制的,,僅僅是為了遵守習(xí)慣),。另外,,最重要的一點(diǎn),,服務(wù)端證書里面的CN一定和服務(wù)端的域名統(tǒng)一,,我們的證書服務(wù)的域名是localhost,,那么我們的客戶端在連接服務(wù)端時(shí)一定也要用localhost來連接,,否則根據(jù)SSL協(xié)議標(biāo)準(zhǔn),,域名與證書的CN不匹配,說明這個(gè)證書是不安全的,,通信將無法正常運(yùn)行,。
有了服務(wù)端,我們原來的客戶端就不能使用了,,必須要走SSL協(xié)議,。由于服務(wù)端的證書是我們自己生成的,沒有任何受信任機(jī)構(gòu)的簽名,,所以客戶端是無法驗(yàn)證服務(wù)端證書的有效性的,,通信必然會(huì)失敗。所以我們需要為客戶端創(chuàng)建一個(gè)保存所有信任證書的倉庫,,然后把服務(wù)端證書導(dǎo)進(jìn)這個(gè)倉庫,。這樣,當(dāng)客戶端連接服務(wù)端時(shí),,會(huì)發(fā)現(xiàn)服務(wù)端的證書在自己的信任列表中,,就可以正常通信了。
因此現(xiàn)在我們要做的是生成一個(gè)客戶端的證書倉庫,,因?yàn)閗eytool不能僅生成一個(gè)空白倉庫,,所以和服務(wù)端一樣,我們還是生成一個(gè)證書加一個(gè)倉庫(客戶端證書加倉庫):
Bash代碼
1.keytool -genkey -v -alias bluedash-ssl-demo-client -keyalg RSA -keystore ./client_ks -dname "CN=localhost,OU=cn,O=cn,L=cn,ST=cn,C=cn" -storepass client -keypass 456456
keytool -genkey -v -alias bluedash-ssl-demo-client -keyalg RSA -keystore ./client_ks -dname "CN=localhost,OU=cn,O=cn,L=cn,ST=cn,C=cn" -storepass client -keypass 456456
結(jié)果如下:
Bash代碼
1.Generating 1,024 bit RSA key pair and self-signed certificate (SHA1withRSA) with a validity of 90 days
2. for: CN=localhost, OU=cn, O=cn, L=cn, ST=cn, C=cn
3.[Storing ./client_ks]
Generating 1,024 bit RSA key pair and self-signed certificate (SHA1withRSA) with a validity of 90 days
for: CN=localhost, OU=cn, O=cn, L=cn, ST=cn, C=cn
[Storing ./client_ks]
接下來,,我們要把服務(wù)端的證書導(dǎo)出來,,并導(dǎo)入到客戶端的倉庫,。第一步是導(dǎo)出服務(wù)端的證書:
Bash代碼
1.keytool -export -alias bluedash-ssl-demo-server -keystore ./server_ks -file server_key.cer
keytool -export -alias bluedash-ssl-demo-server -keystore ./server_ks -file server_key.cer
執(zhí)行結(jié)果如下:
Bash代碼
1.Enter keystore password: server
2.Certificate stored in file <server_key.cer>
Enter keystore password: server
Certificate stored in file <server_key.cer>
然后是把導(dǎo)出的證書導(dǎo)入到客戶端證書倉庫:
Bash代碼
1.keytool -import -trustcacerts -alias bluedash-ssl-demo-server -file ./server_key.cer -keystore ./client_ks
keytool -import -trustcacerts -alias bluedash-ssl-demo-server -file ./server_key.cer -keystore ./client_ks
結(jié)果如下:
Bash代碼
1.Enter keystore password: client
2.Owner: CN=localhost, OU=cn, O=cn, L=cn, ST=cn, C=cn
3.Issuer: CN=localhost, OU=cn, O=cn, L=cn, ST=cn, C=cn
4.Serial number: 4c57c7de
5.Valid from: Tue Aug 03 15:40:14 CST 2010 until: Mon Nov 01 15:40:14 CST 2010
6.Certificate fingerprints:
7. MD5: FC:D4:8B:36:3F:1B:30:EA:6D:63:55:4F:C7:68:3B:0C
8. SHA1: E1:54:2F:7C:1A:50:F5:74:AA:63:1E:F9:CC:B1:1C:73:AA:34:8A:C4
9. Signature algorithm name: SHA1withRSA
10. Version: 3
11.Trust this certificate? [no]: yes
12.Certificate was added to keystore
Enter keystore password: client
Owner: CN=localhost, OU=cn, O=cn, L=cn, ST=cn, C=cn
Issuer: CN=localhost, OU=cn, O=cn, L=cn, ST=cn, C=cn
Serial number: 4c57c7de
Valid from: Tue Aug 03 15:40:14 CST 2010 until: Mon Nov 01 15:40:14 CST 2010
Certificate fingerprints:
MD5: FC:D4:8B:36:3F:1B:30:EA:6D:63:55:4F:C7:68:3B:0C
SHA1: E1:54:2F:7C:1A:50:F5:74:AA:63:1E:F9:CC:B1:1C:73:AA:34:8A:C4
Signature algorithm name: SHA1withRSA
Version: 3
Trust this certificate? [no]: yes
Certificate was added to keystore
好,準(zhǔn)備工作做完了,,我們來撰寫客戶端的代碼:
Java代碼
1.package org.bluedash.tryssl;
2.
3.import java.io.BufferedReader;
4.import java.io.InputStreamReader;
5.import java.io.PrintWriter;
6.import java.net.Socket;
7.
8.import javax.net.SocketFactory;
9.import javax.net.ssl.SSLSocketFactory;
10.
11.public class SSLClient {
12.
13. private static String CLIENT_KEY_STORE = "/Users/liweinan/projs/ssl/src/main/resources/META-INF/client_ks";
14.
15. public static void main(String[] args) throws Exception {
16. // Set the key store to use for validating the server cert.
17. System.setProperty("javax.net.ssl.trustStore", CLIENT_KEY_STORE);
18.
19. System.setProperty("javax.net.debug", "ssl,handshake");
20.
21. SSLClient client = new SSLClient();
22. Socket s = client.clientWithoutCert();
23.
24. PrintWriter writer = new PrintWriter(s.getOutputStream());
25. BufferedReader reader = new BufferedReader(new InputStreamReader(s
26. .getInputStream()));
27. writer.println("hello");
28. writer.flush();
29. System.out.println(reader.readLine());
30. s.close();
31. }
32.
33. private Socket clientWithoutCert() throws Exception {
34. SocketFactory sf = SSLSocketFactory.getDefault();
35. Socket s = sf.createSocket("localhost", 8443);
36. return s;
37. }
38.}
可以看到,,除了把一些類變成SSL通信類以外,客戶端也多出了使用信任證書倉庫的代碼,。以上,,我們便完成了SSL單向握手通信。即:客戶端驗(yàn)證服務(wù)端的證書,,服務(wù)端不認(rèn)證客戶端的證書,。
以上便是Java環(huán)境下SSL單向握手的全過程。因?yàn)槲覀冊诳蛻舳嗽O(shè)置了日志輸出級別為DEBUG:
Java代碼
1.System.setProperty("javax.net.debug", "ssl,handshake");
System.setProperty("javax.net.debug", "ssl,handshake");
因此我們可以看到SSL通信的全過程,,這些日志可以幫助我們更具體地了解通過SSL協(xié)議建立網(wǎng)絡(luò)連接時(shí)的全過程,。
結(jié)合日志,我們來看一下SSL雙向認(rèn)證的全過程:
第一步: 客戶端發(fā)送ClientHello消息,,發(fā)起SSL連接請求,告訴服務(wù)器自己支持的SSL選項(xiàng)(加密方式等),。
Bash代碼
1.*** ClientHello, TLSv1
*** ClientHello, TLSv1
第二步: 服務(wù)器響應(yīng)請求,,回復(fù)ServerHello消息,和客戶端確認(rèn)SSL加密方式:
Bash代碼
1.*** ServerHello, TLSv1
*** ServerHello, TLSv1
第三步: 服務(wù)端向客戶端發(fā)布自己的公鑰,。
第四步: 客戶端與服務(wù)端的協(xié)通溝通完畢,,服務(wù)端發(fā)送ServerHelloDone消息:
Bash代碼
1.*** ServerHelloDone
*** ServerHelloDone
第五步: 客戶端使用服務(wù)端給予的公鑰,創(chuàng)建會(huì)話用密鑰(SSL證書認(rèn)證完成后,,為了提高性能,,所有的信息交互就可能會(huì)使用對稱加密算法),并通過ClientKeyExchange消息發(fā)給服務(wù)器:
Bash代碼
1.*** ClientKeyExchange, RSA PreMasterSecret, TLSv1
*** ClientKeyExchange, RSA PreMasterSecret, TLSv1
第六步: 客戶端通知服務(wù)器改變加密算法,,通過ChangeCipherSpec消息發(fā)給服務(wù)端:
Bash代碼
1.main, WRITE: TLSv1 Change Cipher Spec, length = 1
main, WRITE: TLSv1 Change Cipher Spec, length = 1
第七步: 客戶端發(fā)送Finished消息,,告知服務(wù)器請檢查加密算法的變更請求:
Bash代碼
1.*** Finished
*** Finished
第八步:服務(wù)端確認(rèn)算法變更,返回ChangeCipherSpec消息
Bash代碼
1.main, READ: TLSv1 Change Cipher Spec, length = 1
main, READ: TLSv1 Change Cipher Spec, length = 1
第九步:服務(wù)端發(fā)送Finished消息,,加密算法生效:
Bash代碼
1.*** Finished
*** Finished
那么如何讓服務(wù)端也認(rèn)證客戶端的身份,,即雙向握手呢?其實(shí)很簡單,,在服務(wù)端代碼中,,把這一行:
Java代碼
1.((SSLServerSocket) _socket).setNeedClientAuth(false);
((SSLServerSocket) _socket).setNeedClientAuth(false);
改成:
Java代碼
1.((SSLServerSocket) _socket).setNeedClientAuth(true);
((SSLServerSocket) _socket).setNeedClientAuth(true);
就可以了。但是,,同樣的道理,,現(xiàn)在服務(wù)端并沒有信任客戶端的證書,因?yàn)榭蛻舳说淖C書也是自己生成的,。所以,,對于服務(wù)端,,需要做同樣的工作:把客戶端的證書導(dǎo)出來,并導(dǎo)入到服務(wù)端的證書倉庫:
Bash代碼
1.keytool -export -alias bluedash-ssl-demo-client -keystore ./client_ks -file client_key.cer
2.Enter keystore password: client
3.Certificate stored in file <client_key.cer>
keytool -export -alias bluedash-ssl-demo-client -keystore ./client_ks -file client_key.cer
Enter keystore password: client
Certificate stored in file <client_key.cer>
Bash代碼
1.keytool -import -trustcacerts -alias bluedash-ssl-demo-client -file ./client_key.cer -keystore ./server_ks
2.Enter keystore password: server
3.Owner: CN=localhost, OU=cn, O=cn, L=cn, ST=cn, C=cn
4.Issuer: CN=localhost, OU=cn, O=cn, L=cn, ST=cn, C=cn
5.Serial number: 4c57c80b
6.Valid from: Tue Aug 03 15:40:59 CST 2010 until: Mon Nov 01 15:40:59 CST 2010
7.Certificate fingerprints:
8. MD5: DB:91:F4:1E:65:D1:81:F2:1E:A6:A3:55:3F:E8:12:79
9. SHA1: BF:77:56:61:04:DD:95:FC:E5:84:48:5C:BE:60:AF:02:96:A2:E1:E2
10. Signature algorithm name: SHA1withRSA
11. Version: 3
12.Trust this certificate? [no]: yes
13.Certificate was added to keystore
keytool -import -trustcacerts -alias bluedash-ssl-demo-client -file ./client_key.cer -keystore ./server_ks
Enter keystore password: server
Owner: CN=localhost, OU=cn, O=cn, L=cn, ST=cn, C=cn
Issuer: CN=localhost, OU=cn, O=cn, L=cn, ST=cn, C=cn
Serial number: 4c57c80b
Valid from: Tue Aug 03 15:40:59 CST 2010 until: Mon Nov 01 15:40:59 CST 2010
Certificate fingerprints:
MD5: DB:91:F4:1E:65:D1:81:F2:1E:A6:A3:55:3F:E8:12:79
SHA1: BF:77:56:61:04:DD:95:FC:E5:84:48:5C:BE:60:AF:02:96:A2:E1:E2
Signature algorithm name: SHA1withRSA
Version: 3
Trust this certificate? [no]: yes
Certificate was added to keystore
完成了證書的導(dǎo)入,,還要在客戶端需要加入一段代碼,,用于在連接時(shí),客戶端向服務(wù)端出示自己的證書:
Java代碼
1.package org.bluedash.tryssl;
2.
3.import java.io.BufferedReader;
4.import java.io.FileInputStream;
5.import java.io.InputStreamReader;
6.import java.io.PrintWriter;
7.import java.net.Socket;
8.import java.security.KeyStore;
9.import javax.net.SocketFactory;
10.import javax.net.ssl.KeyManagerFactory;
11.import javax.net.ssl.SSLContext;
12.import javax.net.ssl.SSLSocketFactory;
13.
14.public class SSLClient {
15. private static String CLIENT_KEY_STORE = "/Users/liweinan/projs/ssl/src/main/resources/META-INF/client_ks";
16. private static String CLIENT_KEY_STORE_PASSWORD = "456456";
17.
18. public static void main(String[] args) throws Exception {
19. // Set the key store to use for validating the server cert.
20. System.setProperty("javax.net.ssl.trustStore", CLIENT_KEY_STORE);
21. System.setProperty("javax.net.debug", "ssl,handshake");
22. SSLClient client = new SSLClient();
23. Socket s = client.clientWithCert();
24.
25. PrintWriter writer = new PrintWriter(s.getOutputStream());
26. BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
27. writer.println("hello");
28. writer.flush();
29. System.out.println(reader.readLine());
30. s.close();
31. }
32.
33. private Socket clientWithoutCert() throws Exception {
34. SocketFactory sf = SSLSocketFactory.getDefault();
35. Socket s = sf.createSocket("localhost", 8443);
36. return s;
37. }
38.
39. private Socket clientWithCert() throws Exception {
40. SSLContext context = SSLContext.getInstance("TLS");
41. KeyStore ks = KeyStore.getInstance("jceks");
42.
43. ks.load(new FileInputStream(CLIENT_KEY_STORE), null);
44. KeyManagerFactory kf = KeyManagerFactory.getInstance("SunX509");
45. kf.init(ks, CLIENT_KEY_STORE_PASSWORD.toCharArray());
46. context.init(kf.getKeyManagers(), null, null);
47.
48. SocketFactory factory = context.getSocketFactory();
49. Socket s = factory.createSocket("localhost", 8443);
50. return s;
51. }
52.}
通過比對單向認(rèn)證的日志輸出,,我們可以發(fā)現(xiàn)雙向認(rèn)證時(shí),,多出了服務(wù)端認(rèn)證客戶端證書的步驟:
Bash代碼
1.*** CertificateRequest
2.Cert Types: RSA, DSS
3.Cert Authorities:
4.<CN=localhost, OU=cn, O=cn, L=cn, ST=cn, C=cn>
5.<CN=localhost, OU=cn, O=cn, L=cn, ST=cn, C=cn>
6.*** ServerHelloDone
*** CertificateRequest
Cert Types: RSA, DSS
Cert Authorities:
<CN=localhost, OU=cn, O=cn, L=cn, ST=cn, C=cn>
<CN=localhost, OU=cn, O=cn, L=cn, ST=cn, C=cn>
*** ServerHelloDone
Bash代碼
1.*** CertificateVerify
2.main, WRITE: TLSv1 Handshake, length = 134
3.main, WRITE: TLSv1 Change Cipher Spec, length = 1
*** CertificateVerify
main, WRITE: TLSv1 Handshake, length = 134
main, WRITE: TLSv1 Change Cipher Spec, length = 1
在 @*** ServerHelloDone@ 之前,服務(wù)端向客戶端發(fā)起了需要證書的請求 @*** CertificateRequest@ ,。
在客戶端向服務(wù)端發(fā)出 @Change Cipher Spec@ 請求之前,,多了一步客戶端證書認(rèn)證的過程 @*** CertificateVerify@ 。
客戶端與服務(wù)端互相認(rèn)證證書的情景
作者:tbwshc