Netty中使用SSL 双向认证

1. 前期准备工作

        双向证书认证的双方称为client和server,首先为client和server生成证书。由于仅仅是自己学习使用,因此可以在本地自建一个CA,然后用CA的证书分别签发client和server的证书。CA的创建和签发使用OpenSSL。 
在windows环境上安装OpenSSL,然后依据OpenSSL目录下的openssl.cnf中[ CA_default ]的配置创建相应的文件夹和文件 

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. demoCA/ —- CA的根目录   
  2. |– newcerts/—- CA签发出去的证书   
  3. |– private/ —- CA自己的私钥,默认名称是cakey.pem   
  4. |– serial —- 存放证书序列号的文件   
  5. |– index.txt —- 签发过的证书的记录,文本文件  

        serial这个文件中可以初始写入一行记录,包含两个字符01,表示下一个签发的证书采用的序列号是01 
接下来生成CA自己的公私钥(public/private key),生成证书签名请求(CSR, Certificate Signing Request)文件并对该请求进行自签名 
在openssl的根目录下运行 

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. openssl genrsa -out ./demoCA/private/cakey.pem 2048   
genrsa —- 同时生成public key和private key 
很多人将genrsa解释为只生成private key,这是不对的。可以用下面的命令从文件中解出公钥 
[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. openssl rsa -in cakey.pem -pubout > capublickey.pub  

注意最后的数字2048表示生成的RSA公私钥的长度

JDK7中对证书检查要求公钥的长度最少为1024位,否则会抛出异常 

java.security.cert.CertPathValidatorException: Algorithm constraints check failed 
该长度限制是可以配置的,配置文件路径是JAVA_HOME/jre/lib/security/java.security 
jdk.certpath.disabledAlgorithms=MD2, RSA keySize < 1024 


然后用上面生成的公私钥文件创建一个证书签名请求文件 

openssl req -new -key ./demoCA/private/cakey.pem -out careq.pem 

req —- 创建CSR或者证书 
-key —- openssl从这个文件中读取private key 
careq.pem的内容格式是 
[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. —–BEGIN CERTIFICATE REQUEST—–   
  2. MIICnzCCAYcCAQAwWjELMAkGA1UEBhMCQ04xCzAJBgNVBAgTAlpKMQswCQYDVQQH   
  3. … …   
  4. ZYu4AZp0VzqnQzCTeYTbC+AsA0RrPVjr95Il46AHvhq2JQpFw8DhrS8Ja1VburI4   
  5. ngFK   
  6. —–END CERTIFICATE REQUEST—–  

最后将该请求文件给CA机构做签名,但我们现在是想在本地建CA,因此自己对该文件进行自签名即可。 

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. openssl ca -selfsign -in careq.pem -out cacert.pem  

其实,上面生成CSR然后做自签名的两个步骤可合并到一步完成 

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. openssl req -new -x509 -key ./demoCA/private/cakey.pem -out cacert.pem  

至此,我们已经建立了自己的CA,接下去来分别签发client和server的证书。

创建client和server的证书、key store和trust store

        以创建client的证书为例。由于jdk自带的keytool工具可以方便的创建key store和公私钥,因此公私钥和csr的创建直接使用keytool 
key store和trust store分别对应于ssl握手证书认证中自己的证书和自己所信任的证书列表,二者的文件格式相同,不同之处是key store里面包含ssl握手一方的公私钥和证书,trust store里面包含ssl握手一方所信任的证书,一般没有这些证书所对应的私钥

  1. 生成client的keystore 和key pair 
    [html] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. keytool -genkey -alias client -keyalg RSA -keystore client.keystore -keysize 2048  
  2. 生成csr 
    [html] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. keytool -certreq -alias client -keystore client.keystore -file client.csr  
  3. 用本地CA对该csr签名 
    client证书中我们想添加证书的一项扩展,比如client id,用来区分client的身份,因此需要额外的一份扩展文件client.cnf,内容如下
    [html] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. [v3_req]   
    2. 1.2.3.412=ASN1:UTF8String:0000001444   

    可以将该csr和client.cnf文件拷贝到openssl根目录下,运行 
    [html] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. openssl ca -in client.csr -out client.pem -config ./openssl.cnf -extensions v3_req -extfile client.cnf  
  4. 将签过名的client.pem导入到keystore文件中 
    在导入之前,需要先将CA的证书导入keystore文件 
    [html] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. keytool -keystore client.keystore -importcert -alias CA -file cacert.pem   
    然后导入client自己的证书。注意alias是client,与生产keystore和key pair的必须匹配 
    [html] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. keytool -keystore client.keystore -importcert -alias client -file client.pem  

keystore文件内容的查看可以使用 
keytool -list -v -keystore client.keystore 
或者使用可视化工具KeyStore Explorer查看

5. 创建client的trust store 
由于server的证书也是本地CA签发的,因此client只要信任CA的证书那么自然会信任CA签发出的证书,所以我们只需将CA的证书导入trust store即可 
[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. keytool -import -alias cacert -file cacert.pem -keystore clienttruststore.keystore   

由于clienttruststore.keystore文件尚不存在,此命令首先创建该文件并将CA的证书导入该trust store

server的证书和key store和trust store可类似创建 

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. keytool -genkey -alias server -keyalg RSA -keystore server.keystore -keysize 2048   
  2. keytool -certreq -alias server -keystore server.keystore -file server.csr  
  3.   
  4. openssl ca -in server.csr -out server.pem -config ./openssl.cnf  
  5.   
  6. keytool -keystore server.keystore -importcert -alias CA -file cacert.pem   
  7. keytool -keystore server.keystore -importcert -alias server -file server.pem   
  8. keytool -import -alias ca -file cacert.pem -keystore servertruststore.keystore  

2. 创建SSL通讯的client和server

由于netty 5现在只有alpha版本,因此保险起见使用4.0.24.final版本的netty。 
netty的SSLContext提供了newClientContext来为client创建ssl context,但查看其源码未发现能支持双向认证,即client端的ssl context只接收一个trust store,而不能指定自己的证书以供server端校验。仿照netty example下的securechat的ssl实现但做了修改 
首先创建一个能提供client和server的ssl context的工具类,分别加载server和client的key store和trust store里面的证书

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public class SslContextFactory  
  2. {  
  3.         private static final String     PROTOCOL    = "TLS";    // TODO: which protocols will be adopted?  
  4.     private static final SSLContext SERVER_CONTEXT;  
  5.     private static final SSLContext CLIENT_CONTEXT;  
  6.   
  7.     static  
  8.     {  
  9.         SSLContext serverContext = null;  
  10.         SSLContext clientContext = null;  
  11.   
  12.         String keyStorePassword = "aerohive";  
  13.         try  
  14.         {  
  15.             KeyStore ks = KeyStore.getInstance("JKS");  
  16.             ks.load(SslContextFactory.class.getClassLoader().getResourceAsStream("cert\\server.keystore"), keyStorePassword.toCharArray());  
  17.   
  18.             // Set up key manager factory to use our key store  
  19.             KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());  
  20.             kmf.init(ks, keyStorePassword.toCharArray());  
  21.   
  22.             // truststore  
  23.             KeyStore ts = KeyStore.getInstance("JKS");  
  24.             ts.load(SslContextFactory.class.getClassLoader().getResourceAsStream("cert\\servertruststore.keystore"), keyStorePassword.toCharArray());  
  25.   
  26.             // set up trust manager factory to use our trust store  
  27.             TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());  
  28.             tmf.init(ts);  
  29.   
  30.             // Initialize the SSLContext to work with our key managers.  
  31.             serverContext = SSLContext.getInstance(PROTOCOL);  
  32.             serverContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);  
  33.   
  34.         } catch (Exception e)  
  35.         {  
  36.             throw new Error("Failed to initialize the server-side SSLContext", e);  
  37.         }  
  38.   
  39.         try  
  40.         {  
  41.             // keystore  
  42.             KeyStore ks = KeyStore.getInstance("JKS");  
  43.             ks.load(SslContextFactory.class.getClassLoader().getResourceAsStream("cert\\client.keystore"), keyStorePassword.toCharArray());  
  44.   
  45.             // Set up key manager factory to use our key store  
  46.             KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());  
  47.             kmf.init(ks, keyStorePassword.toCharArray());  
  48.   
  49.             // truststore  
  50.             KeyStore ts = KeyStore.getInstance("JKS");  
  51.             ts.load(SslContextFactory.class.getClassLoader().getResourceAsStream("cert\\clienttruststore.keystore"), keyStorePassword.toCharArray());  
  52.   
  53.             // set up trust manager factory to use our trust store  
  54.             TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());  
  55.             tmf.init(ts);  
  56.             clientContext = SSLContext.getInstance(PROTOCOL);  
  57.             clientContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);  
  58.         } catch (Exception e)  
  59.         {  
  60.             throw new Error("Failed to initialize the client-side SSLContext", e);  
  61.         }  
  62.   
  63.         SERVER_CONTEXT = serverContext;  
  64.         CLIENT_CONTEXT = clientContext;  
  65.     }  
  66.   
  67.     public static SSLContext getServerContext()  
  68.     {  
  69.         return SERVER_CONTEXT;  
  70.     }  
  71.   
  72.     public static SSLContext getClientContext()  
  73.     {  
  74.         return CLIENT_CONTEXT;  
  75.     }  
  76.     ... ...  
  77. }  

         io.netty.example.securechat.SecureChatClientInitializer类的构造器接收一个io.netty.handler.ssl.SslContext类型的对象,这个SslContext的对象最终被用来创建SslHandler,而上面factory产生的是javax.net.ssl.SSLContext的对象,因此可以做改动如下 

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public class ClientInitializer extends ChannelInitializer   
  2. {  
  3.   
  4. private final javax.net.ssl.SSLContext  sslCtx;  
  5.   
  6. public ClientInitializer(javax.net.ssl.SSLContext sslCtx)  
  7. {  
  8.     this.sslCtx = sslCtx;  
  9. }  
  10.   
  11. @Override  
  12. public void initChannel(SocketChannel ch) throws Exception  
  13. {  
  14.     ChannelPipeline pipeline = ch.pipeline();  
  15.   
  16.     SSLEngine sslEngine = sslCtx.createSSLEngine(Client.HOST, Client.PORT);  
  17.     sslEngine.setUseClientMode(true);  
  18.     pipeline.addLast(new SslHandler(sslEngine));  
  19.   
  20.     // On top of the SSL handler, add the text line codec.  
  21.     pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));  
  22.     pipeline.addLast(new StringDecoder());  
  23.     pipeline.addLast(new StringEncoder());  
  24.   
  25.     // and then business logic.  
  26.     pipeline.addLast(new ClientHandler());  
  27. }  
  28. }  


最后添加jvm参数 

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. -Djavax.net.debug=ssl,handshake   
  2. -Ddeployment.security.TLSv1.1=true -Ddeployment.security.TLSv1.2=true

来查看ssl握手过程控制台的log

具体实现请参考附件源码。

http://download.csdn.net/detail/virgilli/8373319

1. 本人测试,发现证书需要按照文档重新生成
2. 如果是mac 的需要注意证书的地址(在源代码中)
3. 在按照教程生成的过程中,需要保证省和组织机构的名称一致。这个可以在index.txt 中查看。

附录: 
openssl的配置 
对证书签名时,遇到openssl异常failed to update database TXT_DB error 

可以有三种方法解决这个问题

方法一:

 

修改demoCA下 index.txt.attr

 

Java代码  收藏代码
  1. unique_subject = yes  

 改为

Java代码  收藏代码
  1. unique_subject = no  

 方法二:

 

删除demoCA下的index.txt,并再touch下

 

Java代码  收藏代码
  1. rm index.txt  
  2.   
  3. touch index.txt  

 方法三:

将 common name设置成不同的


有可能是因为签名的csr文件的subject中的一项或几项在该CA之前签发过的证书中已经出现过或者是csr中提供的国家/省份等等的名称与CA自己的不相同,这些限制都可以在openssl.cnf文件中修改 
unique_subject=no

[ policy_match ] 
countryName = match 
#stateOrProvinceName = match 
organizationName = match 
organizationalUnitName = optional 
commonName = supplied 
emailAddress = optional


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章