tomcat配置https

来源:互联网 发布:c语言在线手册 编辑:程序博客网 时间:2024/04/30 02:12

 

keytool -genkey -keyalg RSA -alias tomcat -keystore d:/tomcat/keystore
tomcat keystore与entry密码需要一样 并且keystore中只能有一条entry
conf/server.xml

<Connector port="8443"
               maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
               enableLookups="false" disableUploadTimeout="true"
               acceptCount="100" debug="0" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS"
      keystoreFile="d:/tomcat5/keystore"
               keystorePass="123456"
      />


输入 https://serverIP 访问tomcat,失败。
查找原因,是因为,htpps协议缺省端口是443,因此ie在报文端口缺省设置成了443,然而tomcat的缺省ssl端口是8443,因此,实际上在ie中输入:https://serverip的时候,
它去访问443端口,自然tomcat没有反应。
解决方法:在tomcat server.xml中,将安全端口改成443,(注意,将8080的redirectport 也改成443!)


URL myURL = new URL("https://127.0.0.1/hessian/");

//创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
        HttpsURLConnection httpsConn = (HttpsURLConnection) myURL
                .openConnection();

        // 取得该连接的输入流,以读取响应内容
        InputStreamReader insr = new InputStreamReader(httpsConn
                .getInputStream());

        // 读取服务器的响应内容并显示
        int respInt = insr.read();
        while (respInt != -1) {
            System.out.print((char) respInt);
            respInt = insr.read();
        }


Exception in thread "main" javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

 

需要把证书添加到客户端的jre里

D:/>keytool -export -alias tomcat -keystore d:/tomcat5/keystore -file d:/tomcat5/tomcat.crt

keytool -import -file d:/tomcat5/tomcat.crt -keystore %java_home%/jre/lib/security/cacerts
默认的keystore密码为changeit


解决 HTTPS hostname wrong: should be <ip> 此类问题的方法

   在生成证书的时候,需要指定CN(Common name),这个很重要,千万不要随便指定。只能是域名,而不能是IP之类的。 比如指定了www.sso.com,那么
通过Java应用程序访问 https://www.sso.com 是正常的,但是https://10.*.*.*就不行,访问的域名必须是www.sso.com。
而且CN的名字还不能指定为IP,我出现的问题就是把它指定为IP了,真是想不到的。


使用 https 协议访问前, 加上以下代码 :

    System.setProperty("java.protocol.handler.pkgs", "javax.net.ssl");

    HostnameVerifier hv = new HostnameVerifier() {
         public boolean verify(String urlHostName, SSLSession session) {
         return urlHostName.equals(session.getPeerHost());
         }
    };
   
    HttpsURLConnection.setDefaultHostnameVerifier(hv);

这样既可正常访问, 注意导入的 HostnameVerifier 和 HttpsURLConnection 的 package 都是 javax.net.ssl, 而非 com.sun.net.ssl
如果允许所有 ip 都可以通过认证, 甚至可以在 verify 中直接返回 true ! 当然这是不推荐的做法.

原创粉丝点击