在Java加密技术(八)中,咱们模拟了一个基于RSA非对称加密网络的安全通讯。如今咱们深度了解一下现有的安全网络通讯——SSL。
咱们须要构建一个由CA机构签发的有效证书,这里咱们使用上文中生成的自签名证书zlex.cer
这里,咱们将证书导入到咱们的密钥库。
html
- keytool -import -alias www.zlex.org -file d:/zlex.cer -keystore d:/zlex.keystore
其中
-import表示导入
-alias指定别名,这里是www.zlex.org
-file指定算法,这里是d:/zlex.cer
-keystore指定存储位置,这里是d:/zlex.keystore
在这里我使用的密码为654321
控制台输出: java
- 输入keystore密码:
- 再次输入新密码:
- 全部者:CN=www.zlex.org, OU=zlex, O=zlex, L=BJ, ST=BJ, C=CN
- 签发人:CN=www.zlex.org, OU=zlex, O=zlex, L=BJ, ST=BJ, C=CN
- 序列号:4a1e48df
- 有效期: Thu May 28 16:18:39 CST 2009 至Wed Aug 26 16:18:39 CST 2009
- 证书指纹:
- MD5:19:CA:E6:36:E2:DF:AD:96:31:97:2F:A9:AD:FC:37:6A
- SHA1:49:88:30:59:29:45:F1:69:CA:97:A9:6D:8A:CF:08:D2:C3:D5:C0:C4
- 签名算法名称:SHA1withRSA
- 版本: 3
- 信任这个认证? [否]: y
- 认证已添加至keystore中
OK,最复杂的准备工做已经完成。
接下来咱们将域名www.zlex.org定位到本机上。打开C:\Windows\System32\drivers\etc\hosts文件,将www.zlex.org绑定在本机上。在文件末尾追加127.0.0.1 www.zlex.org。如今经过地址栏访问http://www.zlex.org,或者经过ping命令,若是可以定位到本机,域名映射就搞定了。
如今,配置tomcat。先将zlex.keystore拷贝到tomcat的conf目录下,而后配置server.xml。将以下内容加入配置文件算法
- <Connector
- SSLEnabled="true"
- URIEncoding="UTF-8"
- clientAuth="false"
- keystoreFile="conf/zlex.keystore"
- keystorePass="123456"
- maxThreads="150"
- port="443"
- protocol="HTTP/1.1"
- scheme="https"
- secure="true"
- sslProtocol="TLS" />
注意clientAuth="false"测试阶段,置为false,正式使用时建议使用true。如今启动tomcat,访问https://www.zlex.org/。
显然,证书未能经过认证,这个时候你能够选择安装证书(上文中的zlex.cer文件就是证书),做为受信任的根证书颁发机构导入,再次重启浏览器(IE,其余浏览器对于域名www.zlex.org不支持本地方式访问),访问https://www.zlex.org/,你会看到地址栏中会有个小锁
,就说明安装成功。全部的浏览器联网操做已经在RSA加密解密系统的保护之下了。但彷佛咱们感觉不到。
这个时候不少人开始怀疑,若是咱们要手工作一个这样的https的访问是否是须要把浏览器的这些个功能都实现呢?不须要!
接着上篇内容,给出以下代码实现:
express
- import java.io.FileInputStream;
- import java.security.KeyStore;
- import java.security.PrivateKey;
- import java.security.PublicKey;
- import java.security.Signature;
- import java.security.cert.Certificate;
- import java.security.cert.CertificateFactory;
- import java.security.cert.X509Certificate;
- import java.util.Date;
-
- import javax.crypto.Cipher;
- import javax.net.ssl.HttpsURLConnection;
- import javax.net.ssl.KeyManagerFactory;
- import javax.net.ssl.SSLContext;
- import javax.net.ssl.SSLSocketFactory;
- import javax.net.ssl.TrustManagerFactory;
-
- public abstract class CertificateCoder extends Coder {
-
-
- public static final String KEY_STORE = "JKS";
-
- public static final String X509 = "X.509";
- public static final String SunX509 = "SunX509";
- public static final String SSL = "SSL";
-
-
- private static PrivateKey getPrivateKey(String keyStorePath, String alias,
- String password) throws Exception {
- KeyStore ks = getKeyStore(keyStorePath, password);
- PrivateKey key = (PrivateKey) ks.getKey(alias, password.toCharArray());
- return key;
- }
-
-
- private static PublicKey getPublicKey(String certificatePath)
- throws Exception {
- Certificate certificate = getCertificate(certificatePath);
- PublicKey key = certificate.getPublicKey();
- return key;
- }
-
-
- private static Certificate getCertificate(String certificatePath)
- throws Exception {
- CertificateFactory certificateFactory = CertificateFactory
- .getInstance(X509);
- FileInputStream in = new FileInputStream(certificatePath);
-
- Certificate certificate = certificateFactory.generateCertificate(in);
- in.close();
-
- return certificate;
- }
-
-
- private static Certificate getCertificate(String keyStorePath,
- String alias, String password) throws Exception {
- KeyStore ks = getKeyStore(keyStorePath, password);
- Certificate certificate = ks.getCertificate(alias);
-
- return certificate;
- }
-
-
- private static KeyStore getKeyStore(String keyStorePath, String password)
- throws Exception {
- FileInputStream is = new FileInputStream(keyStorePath);
- KeyStore ks = KeyStore.getInstance(KEY_STORE);
- ks.load(is, password.toCharArray());
- is.close();
- return ks;
- }
-
-
- public static byte[] encryptByPrivateKey(byte[] data, String keyStorePath,
- String alias, String password) throws Exception {
-
- PrivateKey privateKey = getPrivateKey(keyStorePath, alias, password);
-
-
- Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());
- cipher.init(Cipher.ENCRYPT_MODE, privateKey);
-
- return cipher.doFinal(data);
-
- }
-
-
- public static byte[] decryptByPrivateKey(byte[] data, String keyStorePath,
- String alias, String password) throws Exception {
-
- PrivateKey privateKey = getPrivateKey(keyStorePath, alias, password);
-
-
- Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());
- cipher.init(Cipher.DECRYPT_MODE, privateKey);
-
- return cipher.doFinal(data);
-
- }
-
-
- public static byte[] encryptByPublicKey(byte[] data, String certificatePath)
- throws Exception {
-
-
- PublicKey publicKey = getPublicKey(certificatePath);
-
- Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());
- cipher.init(Cipher.ENCRYPT_MODE, publicKey);
-
- return cipher.doFinal(data);
-
- }
-
-
- public static byte[] decryptByPublicKey(byte[] data, String certificatePath)
- throws Exception {
-
- PublicKey publicKey = getPublicKey(certificatePath);
-
-
- Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());
- cipher.init(Cipher.DECRYPT_MODE, publicKey);
-
- return cipher.doFinal(data);
-
- }
-
-
- public static boolean verifyCertificate(String certificatePath) {
- return verifyCertificate(new Date(), certificatePath);
- }
-
-
- public static boolean verifyCertificate(Date date, String certificatePath) {
- boolean status = true;
- try {
-
- Certificate certificate = getCertificate(certificatePath);
-
- status = verifyCertificate(date, certificate);
- } catch (Exception e) {
- status = false;
- }
- return status;
- }
-
-
- private static boolean verifyCertificate(Date date, Certificate certificate) {
- boolean status = true;
- try {
- X509Certificate x509Certificate = (X509Certificate) certificate;
- x509Certificate.checkValidity(date);
- } catch (Exception e) {
- status = false;
- }
- return status;
- }
-
-
- public static String sign(byte[] sign, String keyStorePath, String alias,
- String password) throws Exception {
-
- X509Certificate x509Certificate = (X509Certificate) getCertificate(
- keyStorePath, alias, password);
-
- KeyStore ks = getKeyStore(keyStorePath, password);
-
- PrivateKey privateKey = (PrivateKey) ks.getKey(alias, password
- .toCharArray());
-
-
- Signature signature = Signature.getInstance(x509Certificate
- .getSigAlgName());
- signature.initSign(privateKey);
- signature.update(sign);
- return encryptBASE64(signature.sign());
- }
-
-
- public static boolean verify(byte[] data, String sign,
- String certificatePath) throws Exception {
-
- X509Certificate x509Certificate = (X509Certificate) getCertificate(certificatePath);
-
- PublicKey publicKey = x509Certificate.getPublicKey();
-
- Signature signature = Signature.getInstance(x509Certificate
- .getSigAlgName());
- signature.initVerify(publicKey);
- signature.update(data);
-
- return signature.verify(decryptBASE64(sign));
-
- }
-
-
- public static boolean verifyCertificate(Date date, String keyStorePath,
- String alias, String password) {
- boolean status = true;
- try {
- Certificate certificate = getCertificate(keyStorePath, alias,
- password);
- status = verifyCertificate(date, certificate);
- } catch (Exception e) {
- status = false;
- }
- return status;
- }
-
-
- public static boolean verifyCertificate(String keyStorePath, String alias,
- String password) {
- return verifyCertificate(new Date(), keyStorePath, alias, password);
- }
-
-
- private static SSLSocketFactory getSSLSocketFactory(String password,
- String keyStorePath, String trustKeyStorePath) throws Exception {
-
- KeyManagerFactory keyManagerFactory = KeyManagerFactory
- .getInstance(SunX509);
- KeyStore keyStore = getKeyStore(keyStorePath, password);
- keyManagerFactory.init(keyStore, password.toCharArray());
-
-
- TrustManagerFactory trustManagerFactory = TrustManagerFactory
- .getInstance(SunX509);
- KeyStore trustkeyStore = getKeyStore(trustKeyStorePath, password);
- trustManagerFactory.init(trustkeyStore);
-
-
- SSLContext ctx = SSLContext.getInstance(SSL);
- ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory
- .getTrustManagers(), null);
- SSLSocketFactory sf = ctx.getSocketFactory();
-
- return sf;
- }
-
-
- public static void configSSLSocketFactory(HttpsURLConnection conn,
- String password, String keyStorePath, String trustKeyStorePath)
- throws Exception {
- conn.setSSLSocketFactory(getSSLSocketFactory(password, keyStorePath,
- trustKeyStorePath));
- }
- }
增长了configSSLSocketFactory方法供外界调用,该方法为HttpsURLConnection配置了SSLSocketFactory。当HttpsURLConnection配置了SSLSocketFactory后,咱们就能够经过HttpsURLConnection的getInputStream、getOutputStream,像往常使用HttpURLConnection作操做了。尤为要说明一点,未配置SSLSocketFactory前,HttpsURLConnection的getContentLength()得到值永远都是-1。
给出相应测试类:
apache
- import static org.junit.Assert.*;
-
- import java.io.DataInputStream;
- import java.io.InputStream;
- import java.net.URL;
-
- import javax.net.ssl.HttpsURLConnection;
-
- import org.junit.Test;
-
- public class CertificateCoderTest {
- private String password = "123456";
- private String alias = "www.zlex.org";
- private String certificatePath = "d:/zlex.cer";
- private String keyStorePath = "d:/zlex.keystore";
- private String clientKeyStorePath = "d:/zlex-client.keystore";
- private String clientPassword = "654321";
-
- @Test
- public void test() throws Exception {
- System.err.println("公钥加密——私钥解密");
- String inputStr = "Ceritifcate";
- byte[] data = inputStr.getBytes();
-
- byte[] encrypt = CertificateCoder.encryptByPublicKey(data,
- certificatePath);
-
- byte[] decrypt = CertificateCoder.decryptByPrivateKey(encrypt,
- keyStorePath, alias, password);
- String outputStr = new String(decrypt);
-
- System.err.println("加密前: " + inputStr + "\n\r" + "解密后: " + outputStr);
-
-
- assertArrayEquals(data, decrypt);
-
-
- assertTrue(CertificateCoder.verifyCertificate(certificatePath));
-
- }
-
- @Test
- public void testSign() throws Exception {
- System.err.println("私钥加密——公钥解密");
-
- String inputStr = "sign";
- byte[] data = inputStr.getBytes();
-
- byte[] encodedData = CertificateCoder.encryptByPrivateKey(data,
- keyStorePath, alias, password);
-
- byte[] decodedData = CertificateCoder.decryptByPublicKey(encodedData,
- certificatePath);
-
- String outputStr = new String(decodedData);
- System.err.println("加密前: " + inputStr + "\n\r" + "解密后: " + outputStr);
- assertEquals(inputStr, outputStr);
-
- System.err.println("私钥签名——公钥验证签名");
-
- String sign = CertificateCoder.sign(encodedData, keyStorePath, alias,
- password);
- System.err.println("签名:\r" + sign);
-
-
- boolean status = CertificateCoder.verify(encodedData, sign,
- certificatePath);
- System.err.println("状态:\r" + status);
- assertTrue(status);
-
- }
-
- @Test
- public void testHttps() throws Exception {
- URL url = new URL("https://www.zlex.org/examples/");
- HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
-
- conn.setDoInput(true);
- conn.setDoOutput(true);
-
- CertificateCoder.configSSLSocketFactory(conn, clientPassword,
- clientKeyStorePath, clientKeyStorePath);
-
- InputStream is = conn.getInputStream();
-
- int length = conn.getContentLength();
-
- DataInputStream dis = new DataInputStream(is);
- byte[] data = new byte[length];
- dis.readFully(data);
-
- dis.close();
- System.err.println(new String(data));
- conn.disconnect();
- }
- }
注意testHttps方法,几乎和咱们往常作HTTP访问没有差异,咱们来看控制台输出:
浏览器
- <!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- -->
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
- <HTML><HEAD><TITLE>Apache Tomcat Examples</TITLE>
- <META http-equiv=Content-Type content="text/html">
- </HEAD>
- <BODY>
- <P>
- <H3>Apache Tomcat Examples</H3>
- <P></P>
- <ul>
- <li><a href="servlets">Servlets examples</a></li>
- <li><a href="jsp">JSP Examples</a></li>
- </ul>
- </BODY></HTML>
经过浏览器直接访问https://www.zlex.org/examples/你也会得到上述内容。也就是说应用甲方做为服务器构建tomcat服务,乙方能够经过上述方式访问甲方受保护的SSL应用,而且不须要考虑具体的加密解密问题。甲乙双方能够通过相应配置,经过双方的tomcat配置有效的SSL服务,简化上述代码实现,彻底经过证书配置完成SSL双向认证!
tomcat