Httpsclient Fetch Certificate

Source: Internet
Author: User
Tags sha1

The following exception occurred during the execution of the WebService:

Unable to find valid certification path to requested target

This is the exception that occurs when a security certificate is missing, and the solution is to import the WebService security certificate you want to access to the client. Here's one way to get a security certificate

1, write a program specifically to obtain a security certificate, refer to Installcert.java:

/* * Copyright 2006 Sun Microsystems, Inc. All rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, is permitted provided that the FOL lowing conditions * is met: * *-redistributions of source code must retain the above copyright * notice, this LIS T of conditions and the following disclaimer. * *-redistributions in binary form must reproduce the above copyright * Notice, this list of conditions and the FO Llowing Disclaimer in the * documentation and/or other materials provided with the distribution. * *-Neither the name of Sun Microsystems nor the names of its * contributors is used to endorse or promote pro Ducts derived * from this software without specific prior written permission. * * This software are provided by the COPYRIGHT holders and CONTRIBUTORS ' as * is ' and any EXPRESS OR implied warranties, I Ncluding, LIMITED to, * The implied warranties of merchantability and FITNESS for A particUlar * PURPOSE is disclaimed. In NO EVENT shall the COPYRIGHT OWNER OR * CONTRIBUTORS is liable for any DIRECT, INDIRECT, incidental, special, * EXEMPLA RY, or consequential damages (including, but not LIMITED to, * procurement of substitute GOODS OR SERVICES; LOSS of Use, DATA, OR * profits; or business interruption) however caused and on any theory of * liability, WHETHER in contract, STRICT liability, OR TORT (including * negligence OR OTHERWISE)  Arising in an any-out-of-the-software, even IF advised of the possibility of SUCH DAMAGE.*/ImportJava.io.*;ImportJava.net.URL;ImportJava.security.*;Importjava.security.cert.*;ImportJavax.net.ssl.*; Public classInstallcert { Public Static voidMain (string[] args)throwsException {String host; intPort; Char[] passphrase; if((Args.length = = 1) | | (Args.length = = 2) ) {string[] C= Args[0].split (":"); Host= C[0]; Port= (C.length = = 1)? 443:integer.parseint (c[1]); String P= (Args.length = = 1)? "Changeit": args[1]; Passphrase=P.tochararray (); } Else{System.out.println ("Usage:java Installcert ); return; } File File=NewFile ("Jssecacerts"); if(File.isfile () = =false) {        CharSEP =File.separatorchar; File dir=NewFile (System.getproperty ("java.home") +SEP+ "Lib" + SEP + "security"); File=NewFile (dir, "Jssecacerts"); if(File.isfile () = =false) {file=NewFile (dir, "Cacerts"); }} System.out.println ("Loading KeyStore" + file + "..."); InputStream in=Newfileinputstream (file); KeyStore KS=keystore.getinstance (Keystore.getdefaulttype ());    Ks.load (in, passphrase);    In.close (); Sslcontext Context= Sslcontext.getinstance ("TLS"); Trustmanagerfactory TMF=trustmanagerfactory.getinstance (Trustmanagerfactory.getdefaultalgorithm ());    Tmf.init (KS); X509trustmanager Defaulttrustmanager= (X509trustmanager) tmf.gettrustmanagers () [0]; Savingtrustmanager TM=NewSavingtrustmanager (Defaulttrustmanager); Context.init (NULL,NewTrustmanager[] {TM},NULL); Sslsocketfactory Factory=context.getsocketfactory (); System.out.println ("Opening connection to" + Host + ":" + Port + "..."); Sslsocket Socket=(Sslsocket) factory.createsocket (host, Port); Socket.setsotimeout (10000); Try{System.out.println ("Starting SSL handshake ...");        Socket.starthandshake ();        Socket.close ();        System.out.println (); System.out.println ("No errors, certificate is already trusted"); } Catch(sslexception e) {System.out.println ();    E.printstacktrace (System.out); } x509certificate[] Chain=Tm.chain; if(Chain = =NULL) {System.out.println ("Could not obtain server certificate chain"); return; } BufferedReader Reader=NewBufferedReader (NewInputStreamReader (system.in));    System.out.println (); System.out.println ("Server sent" + Chain.length + "certificate (s):");    System.out.println (); MessageDigest SHA1= Messagedigest.getinstance ("SHA1"); MessageDigest MD5= Messagedigest.getinstance ("MD5");  for(inti = 0; i < chain.length; i++) {X509Certificate cert=Chain[i]; System.out.println ("" + (i + 1) + "Subject" +Cert.getsubjectdn ()); System.out.println ("Issuer" +Cert.getissuerdn ());        Sha1.update (cert.getencoded ()); System.out.println ("SHA1" +tohexstring (Sha1.digest ()));        Md5.update (cert.getencoded ()); System.out.println ("MD5" +tohexstring (Md5.digest ()));    System.out.println (); } System.out.println ("Enter certificate to add to trusted KeyStore or ' Q ' to quit: [1]"); String Line=reader.readline (). Trim (); intK; Try{k= (Line.length () = = 0)? 0:integer.parseint (line)-1; } Catch(NumberFormatException e) {System.out.println ("KeyStore not Changed"); return; } x509certificate cert=Chain[k]; String alias= host + "-" + (k + 1);    Ks.setcertificateentry (alias, cert); OutputStream out=NewFileOutputStream ("Jssecacerts");    Ks.store (out, passphrase);    Out.close ();    System.out.println ();    SYSTEM.OUT.PRINTLN (CERT);    System.out.println (); System.out.println ("Added certificate to KeyStore ' Jssecacerts ' using alias ' + alias + '"); }    Private Static Final Char[] hexdigits = "0123456789abcdef". ToCharArray (); Private StaticString tohexstring (byte[] bytes) {StringBuilder SB=NewStringBuilder (Bytes.length * 3);  for(intb:bytes) {b&= 0xFF; Sb.append (Hexdigits[b>> 4]); Sb.append (Hexdigits[b& 15]); Sb.append (‘ ‘); }    returnsb.tostring (); }    Private Static classSavingtrustmanagerImplementsX509trustmanager {Private FinalX509trustmanager TM; Privatex509certificate[] chain; Savingtrustmanager (X509trustmanager tm) { This. TM =TM; }     Publicx509certificate[] Getacceptedissuers () {Throw Newunsupportedoperationexception (); }     Public voidcheckclienttrusted (x509certificate[] chain, String authtype)throwscertificateexception {Throw Newunsupportedoperationexception (); }     Public voidcheckservertrusted (x509certificate[] chain, String authtype)throwscertificateexception { This. Chain =chain;    Tm.checkservertrusted (chain, authtype); }    }}

2. Execute Java installcert hostname such as

Java Installcert ecc.fedora.redhat.com

You will see the following information:

Java installcert ecc.fedora.redhat.comLoading keystore/usr/jdk/instances/jdk1.5.0/jre/lib/security/cacerts ... Opening connection to ecc.fedora.redhat.com:443...starting SSL handshake...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 Targetat com.sun.net.ssl.internal.ssl.Alerts.getSSLException (alerts.java:150) at Com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal (sslsocketimpl.java:1476) at Com.sun.net.ssl.internal.ssl.Handshaker.fatalSE (handshaker.java:174) at Com.sun.net.ssl.internal.ssl.Handshaker.fatalSE (handshaker.java:168) at Com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate (clienthandshaker.java:846) at Com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage (clienthandshaker.java:106) at Com.sun.net.ssl.internal.ssl.Handshaker.processLoop (handshaker.java:495) at Com.sun.net.ssl.internal.ssl.Handshaker. Process_record (handshaker.java:433) at Com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord (Sslsocketimpl.java : 815) at Com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake (sslsocketimpl.java:1025) at Com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake (sslsocketimpl.java:1038) at Installcert.main ( installcert.java:63) caused By:sun.security.validator.ValidatorException:PKIX path building failed: Sun.security.provider.certpath.SunCertPathBuilderException:unable to find valid certification path to requested Targetat Sun.security.validator.PKIXValidator.doBuild (pkixvalidator.java:221) at Sun.security.validator.PKIXValidator.engineValidate (pkixvalidator.java:145) at Sun.security.validator.Validator.validate (validator.java:203) at Com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted (x509trustmanagerimpl.java:172) at Installcert$savingtrustmanager.checkservertrusted (installcert.java:158) at Com.sun.net.ssl.internal.ssl.JsseX509TrustManager.checkServerTrusted (SSLContextimpl.java:320) at Com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate (Clienthandshaker.java : 839) ... 7 morecaused by:sun.security.provider.certpath.SunCertPathBuilderException:unable to find valid certification path to r equested targetat Sun.security.provider.certpath.SunCertPathBuilder.engineBuild (suncertpathbuilder.java:236) at Java.security.cert.CertPathBuilder.build (certpathbuilder.java:194) at Sun.security.validator.PKIXValidator.doBuild (pkixvalidator.java:216) ... Moreserver sent 2 certificate (s): 1 Subject cn=ecc.fedora.redhat.com, o=example.com, c=us Issuer cn=certificate Shac K, o=example.com, C=us SHA1 2e 7f 9b the same as 2e 5d 8f 6b 2d 5e e4 D8 E9 C7 MD5 dd D1 A8, D7 6c 4b A7 3d D0 2 Subject cn=certificate Shack, o=example.com, c=us Issuer cn=certificate Shack, O=examp le.com, C=us SHA1 fb A7 C4 4e 3b 0e E3 2c 2f E1 A1 A6 MD5-a0-4d-2 F 6d 98 2cTER certificate to add to trusted KeyStore or ' Q ' to quit: [1] 

3. Enter 1, and then enter directly, a certificate named ' Jssecacerts ' will be generated in the corresponding directory. Copy the certificate to the $java_home/jre/lib/security directory, or use the following method

System.setproperty ("Javax.net.ssl.trustStore", "d:\\uta\\doc_e_health_xml\\keystore\\jssecacerts");

Note: To restart your application server, the certificate can be used because it is statically loaded.

Httpsclient Fetch Certificate

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.