How to access the HTTPS link using httpsurlconnection in Java

Source: Internet
Author: User
Tags ssl connection

In the web application interaction process, there are many scenarios that need to ensure the security of communication data; in the previous articles, we have introduced how to use WS-Security to ensure the security of the interface interaction process during web service calling. It is worth noting that, the transmission protocol based on this method is still HTTP. The scalability and Data Interaction efficiency are relatively high. The other method is to use https, it is a re-encapsulation of HTTP at the protocol layer, with SSL/TLS added. All data that uses this protocol for communication will be encrypted, at present, web development programming has a certain degree of encapsulation, so the use of HTTPS to provide external services, in addition to the certificate, the programming capability requirements are not high, compared to the former threshold is low, however, it is inefficient to encrypt all the data communicated between the two parties and there are several handshakes during the interaction process; the following describes some problems that may occur when accessing HTTPS links in Java;

A key class is used to access HTTPS links in Java.HttpsurlconnectionSee the following implementation code:

  1. // Create a URL object
  2. URL myurl = new URL ("https://www.sun.com ");
  3. // Create an httpsurlconnection object and set its sslsocketfactory object
  4. Httpsurlconnection httpsconn = (httpsurlconnection) myurl
  5. . Openconnection ();
  6. // Obtain the input stream of the connection to read the response content
  7. Inputstreamreader insr = new inputstreamreader (httpsconn
  8. . Getinputstream ());
  9. // Read and display the server response content
  10. Int respint = insr. Read ();
  11. While (respint! =-1 ){
  12. System. Out. Print (char) respint );
  13. Respint = insr. Read ();
  14. }

When the connection is obtained and accessed by a normal browserVerify that the server certificate is trusted(Issued by an authority or signed by an authority). If the server certificate is not trusted, the default implementation will be problematic.SunjsseThe following exception is thrown:
Javax.net. SSL. sslhandshakeexception: Sun. Security. validator. validatorexception: pkix path building failed: Sun. Security. provider. certpath. Failed: unable to find valid certification path to requested target

As mentioned above, sunjsse (Java Secure Socket Extension) is a collection of packages for secure Internet communication. It is a pure Java implementation of SSL and TLS. It can transparently provide data encryption, server authentication, information integrity, and other functions, this allows us to use a secure socket established by JSSE just like a common socket. JSSE is an open standard. Not only can Sun implement a sunjsse, but in fact other companies have their own JSSE, which can then be used in JVM through JCA.
For details about JSSE, refer to reference: http://java.sun.com/j2se/1.5.0/docs/guide/security/jsse/jsserefguide.html;
And Java security guide: http://java.sun.com/j2se/1.5.0/docs/guide/security /;

Before learning about JSSE, you need to understand a Java security concept: the truststore file of the client. The client's truststore file stores the certificate information of the server trusted by the client. When the client performs an SSL connection, JSSE determines whether to trust the server certificate based on the Certificate in this file. In sunjsse, a trust manager class determines whether to trust a remote certificate. This class has the following processing rules:
1. If the system propertyJavax.net. SLL. truststoreIf the truststore file is specified, the trust manager searches for and uses the file in the LIB/security/directory under the JRE installation path to check the certificate.
2. If the system property does not specify the truststore file, it will go to the JRE installation path to find the default truststore file. The relative path of this file is lib/security/Jssecacerts.
3. If jssecacerts does not exist but cacerts exists (it is released along with j2sdk and contains a limited number of trusted Basic certificates), the default truststore file is lib/security/Cacerts.

How can we deal with this situation? There are two solutions:
1. According to the above rules of the trust manager,Import the public key of the server to jssecacertsOr set the path of the truststore file to be loaded in the system properties. For certificate import, run the following command: keytool-import-file src_cer_file-keystore dest_cer_store. For certificates, you can export them in the browser;
2. Implement your own certificate trust manager class, suchMyx509trustmanagerThis class must implement three methods in the x509trustmanager interface. Then, load the custom class in httpsurlconnection. For details, see the following two code snippets. One is the custom certificate trust manager, the second is the code for CONNECT:

  1. Package test;
  2. Import java. Io. fileinputstream;
  3. Import java. Security. keystore;
  4. Import java. Security. cert. certificateexception;
  5. Import java. Security. cert. x509certificate;
  6. Import javax.net. SSL. trustmanager;
  7. Import javax.net. SSL. trustmanagerfactory;
  8. Import javax.net. SSL. x509trustmanager;
  9. Public class myx509trustmanager implements x509trustmanager {
  10. /*
  11. * The default x509trustmanager returned by sunx509. we'll delegate
  12. * Decisions to it, and fall back to the logic in this class if
  13. * Default x509trustmanager doesn' t trust it.
  14. */
  15. X509trustmanager sunjssex509trustmanager;
  16. Myx509trustmanager () throws exception {
  17. // Create a "default" JSSE x509trustmanager.
  18. Keystore Ks = keystore. getinstance ("jks ");
  19. KS. Load (New fileinputstream ("trustedcerts "),
  20. "Passphrase". tochararray ());
  21. Trustmanagerfactory TMF =
  22. Trustmanagerfactory. getinstance ("sunx509", "sunjsse ");
  23. TMF. INIT (KS );
  24. Trustmanager TMS [] = TMF. gettrustmanagers ();
  25. /*
  26. * Iterate over the returned trustmanagers, look
  27. * For an instance of x509trustmanager. If found,
  28. * Use that as our "default" trust manager.
  29. */
  30. For (INT I = 0; I <TMS. length; I ++ ){
  31. If (TMS [I] instanceof x509trustmanager ){
  32. Sunjssex509trustmanager = (x509trustmanager) TMS [I];
  33. Return;
  34. }
  35. }
  36. /*
  37. * Find some other way to initialize, or else we have to fail
  38. * Constructor.
  39. */
  40. Throw new exception ("couldn't initialize ");
  41. }
  42. /*
  43. * Delegate to the default trust manager.
  44. */
  45. Public void checkclienttrusted (x509certificate [] Chain, string authtype)
  46. Throws certificateexception {
  47. Try {
  48. Sunjssex509trustmanager. checkclienttrusted (chain, authtype );
  49. } Catch (certificateexception excep ){
  50. // Do any special handling here, or rethrow exception.
  51. }
  52. }
  53. /*
  54. * Delegate to the default trust manager.
  55. */
  56. Public void checkservertrusted (x509certificate [] Chain, string authtype)
  57. Throws certificateexception {
  58. Try {
  59. Sunjssex509trustmanager. checkservertrusted (chain, authtype );
  60. } Catch (certificateexception excep ){
  61. /*
  62. * Possibly pop up a dialog box asking whether to trust
  63. * Cert chain.
  64. */
  65. }
  66. }
  67. /*
  68. * Merely pass this through.
  69. */
  70. Public x509certificate [] getacceptedissuers (){
  71. Return sunjssex509trustmanager. getacceptedissuers ();
  72. }
  73. }

  1. // Create an sslcontext object and use the specified trust manager to initialize the object
  2. Trustmanager [] TM = {New myx509trustmanager ()};
  3. Sslcontext = sslcontext. getinstance ("SSL", "sunjsse ");
  4. Sslcontext. INIT (null, TM, new java. Security. securerandom ());
  5. // Obtain the sslsocketfactory object from the sslcontext object
  6. Sslsocketfactory SSF = sslcontext. getsocketfactory ();
  7. // Create a URL object
  8. URL myurl = new URL ("https://ebanks.gdb.com.cn/sperbank/perbankLogin.jsp ");
  9. // Create an httpsurlconnection object and set its sslsocketfactory object
  10. Httpsurlconnection httpsconn = (httpsurlconnection) myurl. openconnection ();
  11. Httpsconn. setsslsocketfactory (SSF );
  12. // Obtain the input stream of the connection to read the response content
  13. Inputstreamreader insr = new inputstreamreader (httpsconn. getinputstream ());
  14. // Read and display the server response content
  15. Int respint = insr. Read ();
  16. While (respint! =-1 ){
  17. System. Out. Print (char) respint );
  18. Respint = insr. Read ();
  19. }

The two methods have their own advantages. The first methodJSSE security will not be damagedBut manually import the certificate. If there are many servers, the JRE of each server must perform the same operation. method 2Higher flexibilityBut be careful with the implementation, otherwise it may leave security risks;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.