Java访问不受信任证书的https网站

     如果在Java中访问不受信任证书的https网站,会出现如下错误:

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

下面是牛人给出的详细步骤:

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

Are you getting this error? This simply means that the web server or the URL you are connecting to does not have a valid certificate from an authorized CA. But however, being a programmer you would want to find out the alternative way to solve this issue.

What you need to do is to import the server certificate and install it in your JDK's keystore. If I am talking greek, its ok. I too just leant this. Just follow these steps and you will be able to get rid of that error.

  1. First of all you copy the URL that you are connecting to and paste it in your browser. Let us say you are using IE. Just paste the url in the address bar and press enter.
  2. You will now probably see a dialog box warning you about the certificate. Now click on the 'View Certificate' and install the certificate. Ignore any warning messages.
  3. Now that the server certificate is installed in your computer, your browser will not warn you when you visit the same site again. But however your JRE dumb as it is does not yet know about this certificate's existence until you add it to its keystore. Usually you will use the keytool to manage certificates. Keytool is a command-line utility with numerous arguments that allow you to create and manage keystores for housing digital certificates. For the complete documentation of keytool,http://java.sun.com/j2se/1.3/docs/tooldocs/win32/keytool.html
  4. You can list the current certificates contained within a keystore using they keytool -listcommand. The initial password for the cacerts keystore is changeit. For example:
    • C:\Program Files\Citrix\Citrix Extranet Server\SGJC\jre\bin>keytool -list -keystore ..\lib\security\cacerts

      Enter keystore password: changeit

      You will then see the something like this:

      Keystore type: jks

      Keystore provider: SUN

      Your keystore contains 11 entries:

      engweb, Wed Apr 11 16:22:49 EDT 2001, trustedCertEntry,

      Certificate fingerprint (MD5): 8C:24:DA:52:7A:4A:16:4B:8E:FB:67:44:C9:D2:E4:16

      thawtepersonalfreemailca, Fri Feb 12 15:12:16 EST 1999, trustedCertEntry,

      Certificate fingerprint (MD5): 1E:74:C3:86:3C:0C:35:C5:3E:C2:7F:EF:3C:AA:3C:D9

      thawtepersonalbasicca, Fri Feb 12 15:11:01 EST 1999, trustedCertEntry,

      Certificate fingerprint (MD5): E6:0B:D2:C9:CA:2D:88:DB:1A:71:0E:4B:78:EB:02:41

      verisignclass3ca, Mon Jun 29 13:05:51 EDT 1998, trustedCertEntry,

      Certificate fingerprint (MD5): 78:2A:02:DF:DB:2E:14:D5:A7:5F:0A:DF:B6:8E:9C:5D

      thawteserverca, Fri Feb 12 15:14:33 EST 1999, trustedCertEntry,

      Certificate fingerprint (MD5): C5:70:C4:A2:ED:53:78:0C:C8:10:53:81:64:CB:D0:1D

      thawtepersonalpremiumca, Fri Feb 12 15:13:21 EST 1999, trustedCertEntry,

      Certificate fingerprint (MD5): 3A:B2:DE:22:9A:20:93:49:F9:ED:C8:D2:8A:E7:68:0D

      verisignclass4ca, Mon Jun 29 13:06:57 EDT 1998, trustedCertEntry,

      Certificate fingerprint (MD5): 1B:D1:AD:17:8B:7F:22:13:24:F5:26:E2:5D:4E:B9:10

      verisignclass1ca, Mon Jun 29 13:06:17 EDT 1998, trustedCertEntry,

      Certificate fingerprint (MD5): 51:86:E8:1F:BC:B1:C3:71:B5:18:10:DB:5F:DC:F6:20

      verisignserverca, Mon Jun 29 13:07:34 EDT 1998, trustedCertEntry,

      Certificate fingerprint (MD5): 74:7B:82:03:43:F0:00:9E:6B:B3:EC:47:BF:85:A5:93

      thawtepremiumserverca, Fri Feb 12 15:15:26 EST 1999, trustedCertEntry,

      Certificate fingerprint (MD5): 06:9F:69:79:16:66:90:02:1B:8C:8C:A2:C3:07:6F:3A

      verisignclass2ca, Mon Jun 29 13:06:39 EDT 1998, trustedCertEntry,

      Certificate fingerprint (MD5): EC:40:7D:2B:76:52:67:05:2C:EA:F2:3A:4F:65:F0:D8

  5. Now you have to add the previosly installed certificate to this keystore. To add, begin by exporting your CA Root certificate as a DER-encoded binary file and save it as C:\root.cer. (you can view the installed certificates under Tools->'Internet Options' ->Content->Certificates. Once you open the certificates, locate the one you just installed under 'Trusted Root Certification Authorities". Select the right one and click on 'export'. You can now save it (DER encoded binary) under your c: drive.
  6. Then use the keytool -import command to import the file into your cacerts keystore. 

        For example:-alias myprivateroot -keystore ..\lib\security\cacerts -file c:\root.cer

    Enter keystore password: changeit

    Owner: CN=Division name, OU=Department, O=Your Company, L=Anytown,

    ST=NC, C=US, EmailAddress=you@company.com

    Issuer: CN=Division name, OU=Department, O=Your Company, L=Anytown,

    ST=NC, C=US, EmailAddress=you@company.com

    Serial number: 79805d77eecfadb147e84f8cc2a22106

    Valid from: Wed Sep 19 14:15:10 EDT 2001 until: Mon Sep 19 14:23:20 EDT 2101

    Certificate fingerprints:

    MD5: B6:30:03:DC:6D:73:57:9B:F4:EE:13:16:C7:68:85:09

    SHA1: B5:C3:BB:CA:34:DF:54:85:2A:E9:B2:05:E0:F7:84:1E:6E:E3:E7:68

    Trust this certificate? [no]: yes

    Certificate was added to keystore

  7. 7. Now run keytool -list again to verify that your private root certificate was added:
    • C:\Program Files\Citrix\Citrix Extranet Server\SGJC\jre\bin>keytool -list -keystore ..\lib\security\cacerts

    You will now see a list of all the certificates including the one you just added.

    This confirms that your private root certificate has been added to the Extranet server cacerts keystore as a trusted certificate authority.


    If this tutorial doesn't answer your question, and you have a specific question, just ask an expert here. Post your question to get a direct answer.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 要使用Java实现读取证书访问HTTPS接口,需要遵循以下步骤: 1. 获取证书:首先,需要获取要访问HTTPS服务器的证书。可以使用浏览器访问该服务器,并导出证书为一个文件(一般为.crt或.pem格式)。 2. 将证书导入Java密钥库:将第一步获得的证书导入Java密钥库中。可以使用Java提供的keytool工具,执行类似以下命令: ``` keytool -import -file /path/to/certificate.crt -alias servercert -keystore /path/to/keystore.jks ``` 这将把证书导入到指定的密钥库中,并为证书指定一个别名。 3. 创建SSLContext:使用Java的KeyStore类加载密钥库,并创建一个包含需要的信任管理器的SSLContext实例。可以使用以下代码实现: ```java KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream trustStoreFile = new FileInputStream("/path/to/keystore.jks"); trustStore.load(trustStoreFile, "keystorepassword".toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustManagerFactory.getTrustManagers(), null); ``` 4. 创建HttpClient:使用Apache HttpClient库创建一个HttpClient对象,并指定使用刚才创建的SSLContext实例来进行HTTPS连接。可以使用以下代码实现: ```java HttpClient client = HttpClients.custom().setSSLContext(sslContext).build(); ``` 5. 发送HTTPS请求:使用HttpClient对象发送HTTPS请求到目标接口。可以使用HttpGet或HttpPost等请求类型,并执行execute方法,如下所示: ```java HttpGet request = new HttpGet("https://api.example.com"); HttpResponse response = client.execute(request); ``` 以上步骤完成后,即可通过Java程序读取证书访问HTTPS接口。需要注意的是,从第3步开始的代码需要进行异常处理,同时确保路径和密码等参数正确配置。 ### 回答2: 要用Java实现读取证书访问HTTPS接口,可以按照以下步骤进行操作: 1. 确保你已经获取到了HTTPS接口所需的证书文件,一般为以.crt、.pem或.jks为扩展名的文件。 2. 首先,需要创建一个HttpClient对象,用于发送HTTP请求。可以使用Apache HttpClient库来实现,该库提供了丰富的HTTP客户端功能。 3. 创建SSLContext对象,用于在发送HTTPS请求时验证服务器证书的有效性。可以使用KeyStore类加载证书文件,并通过TrustManagerFactory初始化SSLContext。 4. 创建一个HostnameVerifier对象,用于验证服务器主机名的有效性。可以使用自定义的实现类,也可以使用默认的实现类。 5. 创建一个HttpClientBuilder对象,并将SSLContext和HostnameVerifier对象设置给它。 6. 使用HttpClientBuilder对象创建HttpClient对象,同时设置代理、超时等相关参数。 7. 创建一个HttpGet或HttpPost对象,设置请求的URL和相关参数。 8. 调用HttpClient对象的execute方法发送请求,并获取返回的HttpResponse对象。 9. 从HttpResponse对象中获取服务器返回的数据,并进行后续处理。 示例代码如下: ```java import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.security.KeyStore; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.TrustManagerFactoryBuilder; public class HttpsClientExample { public static void main(String[] args) { try { // 加载证书 KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(HttpsClientExample.class.getResourceAsStream("client-truststore.crt"), "password".toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactoryBuilder.newBuilder() .withDefaultAlgorithm() .withKeystore(trustStore) .build(); SSLContext sslContext = SSLContextBuilder.create() .loadTrustMaterial(trustManagerFactory) .build(); CloseableHttpClient httpClient = HttpClients.custom() .setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext)) .build(); HttpGet httpGet = new HttpGet("https://example.com/api"); HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); // 读取返回的数据 InputStream inputStream = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } httpClient.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 以上就是使用Java实现读取证书访问HTTPS接口的基本步骤,根据具体的证书和接口要求,可能需要进行一些额外的配置和参数设置。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值