为HTTPSURLConnection设置TLS协议

时间:2015-02-24 13:39:22

标签: java security http ssl

我需要对付使用TLS协议连接的F5机器。  为此,我构建了一个使用HTTPsURLConnection对象的类。

m_httpsConnection = (HttpsURLConnection) m_url.openConnection();

然后,我下载了F5证书文件,使用JDK keytool创建密钥库,并用它来尝试设置连接以使用TLS协议:

        InputStream in = new FileInputStream(new File("c:/temp/F5keystore"));
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(in, "changeit".toCharArray());
        in.close();

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, new TrustManager[] {defaultTrustManager}, null);
        SSLSocketFactory sslSocketFactory = context.getSocketFactory();

        ((HttpsURLConnection) m_httpsConnection).setSSLSocketFactory(sslSocketFactory);

(我饶了你们的捕获......)

代码似乎正在迅速传递,但当我这样做时:

OutputStream os = m_httpsConnection.getOutputStream();

我明白了......

“javax.net.ssl.SSLHandshakeException:sun.security.validator.ValidatorException:PKIX路径构建失败:sun.security.provider.certpath.SunCertPathBuilderException:无法找到所请求目标的有效证书路径

现在,我在c:\ temp下有文件F5keystore文件,为什么不找到它呢?..

这是将TLS设置为连接的正确方法吗?现在我在打开连接后这样做,虽然我可能认为它应该在连接打开之前。但是,连接仍然是空的......


我在此处根据您的要求添加更多信息:

C:\temp>keytool -v -printcert -file server.crt
Owner: EMAILADDRESS=root@localhost.localdomain, CN=localhost.localdomain, OU=MyOrg, O=MyCompany, L=Seattle, ST=WA, C=--
Issuer: EMAILADDRESS=root@localhost.localdomain, CN=localhost.localdomain, OU=MyOrg, O=MyCompany, L=Seattle, ST=WA, C=--

Serial number: 90f9d7e288ae6a77
Valid from: Fri Nov 07 08:20:36 IST 2014 until: Mon Nov 04 08:20:36 IST 2024
Certificate fingerprints:
         MD5:  C1:BE:43:9B:8B:C3:AA:F7:F2:BF:E6:06:08:42:18:17
         SHA1: 12:36:01:30:14:68:1C:C9:7D:7B:32:75:C6:08:86:E9:36:AD:CF:AA
         Signature algorithm name: SHA1withRSA
         Version: 3

Extensions:

#1: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: AA B6 71 94 D1 CB ED DF   1B 38 66 12 70 94 AA 76  ..q......8f.p..v
0010: 68 DF 2A 16                                        h.*.
]
]

#2: ObjectId: 2.5.29.19 Criticality=false
BasicConstraints:[
  CA:true
  PathLen:2147483647
]

#3: ObjectId: 2.5.29.35 Criticality=false
AuthorityKeyIdentifier [
KeyIdentifier [
0000: AA B6 71 94 D1 CB ED DF   1B 38 66 12 70 94 AA 76  ..q......8f.p..v
0010: 68 DF 2A 16                                        h.*.
]

[EMAILADDRESS=root@localhost.localdomain, CN=localhost.localdomain, OU=MyOrg, O=MyCompany, L=Seattle, ST=WA, C=--]
SerialNumber: [    90f9d7e2 88ae6a77]
]

最诚挚的问候,Tal

1 个答案:

答案 0 :(得分:0)

我明白实际上我可以绕过证书问题以继续我的活动。所以我用this来实现这个旁路。谢谢大家。