Java get HTTPS Web site certificate

Source: Internet
Author: User
Tags sha1

ImportJava.io.BufferedReader;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.OutputStream;ImportJava.security.KeyStore;Importjava.security.MessageDigest;Importjava.security.cert.CertificateException;Importjava.security.cert.X509Certificate;ImportJavax.net.ssl.SSLContext;Importjavax.net.ssl.SSLException;ImportJavax.net.ssl.SSLSocket;Importjavax.net.ssl.SSLSocketFactory;ImportJavax.net.ssl.TrustManager;Importjavax.net.ssl.TrustManagerFactory;ImportJavax.net.ssl.X509TrustManager; /*** Obtain the required Java certificate from the website, and pass in the domain name when calling. */ Public classZS { 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); }      }    }  

Java get HTTPS Web site certificate

Related Article

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.