The new experience of using HTTPS in Android to verify the validity of service certificates

Source: Internet
Author: User

 Packagecom.cetcs.logreport.utils;ImportAndroid.content.Context;Importorg.apache.http.conn.ssl.SSLSocketFactory;ImportJava.io.BufferedInputStream;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.net.Socket;Importjava.net.UnknownHostException;Importjava.security.InvalidKeyException;ImportJava.security.KeyStore;Importjava.security.NoSuchAlgorithmException;Importjava.security.NoSuchProviderException;Importjava.security.SignatureException;Importjava.security.cert.CertificateException;Importjava.security.cert.CertificateFactory;Importjava.security.cert.X509Certificate;ImportJavax.net.ssl.SSLContext;ImportJavax.net.ssl.TrustManager;ImportJavax.net.ssl.X509TrustManager;/*** * Parsing server certificate classes, parsing server-side certificate Serv.crt, where the Server.crt file is a self-signed certificate generated using * OpenSSL **/ Public classSslverifylogservercrtsocketfactoryextendsSslsocketfactory {Private Static FinalString TAG = "Ssltrustallsocketfactory"; PrivateSslcontext Mctx; Privatecontext Context;  Publicsslverifylogservercrtsocketfactory (String crtname, KeyStore Truststore, context context)throwsThrowable {Super(Truststore);  This. Context =context; Try{InputStream Certinputstream=NewBufferedinputstream (Context.getassets (). Open (Crtname)); Certificatefactory certificatefactory= Certificatefactory.getinstance ("the"); FinalX509Certificate servercertificate =(X509Certificate) certificatefactory.generatecertificate (Certinputstream); Mctx= Sslcontext.getinstance ("TLS"); Mctx.init (NULL,Newtrustmanager[]{NewX509trustmanager () {@Override Public voidCheckclienttrusted (x509certificate[] chain, String authtype)throwscertificateexception {} @Override Public voidCheckservertrusted (x509certificate[] x509certificates, String authtype)throwscertificateexception {if(X509Certificates = =NULL){                                Throw  NewIllegalArgumentException ("checkservertrusted x509certificates is null"); }                            if(X509certificates.length < 0){                                Throw  NewIllegalArgumentException ("checkservertrusted x509certificates is null"); }                             for(X509Certificate cert:x509certificates) {cert.checkvalidity (); Try{cert.verify (Servercertificate.getpublickey ()); } Catch(nosuchalgorithmexception e) {e.printstacktrace (); } Catch(InvalidKeyException e) {e.printstacktrace (); } Catch(nosuchproviderexception e) {e.printstacktrace (); } Catch(signatureexception e) {e.printstacktrace (); } }} @Override Publicx509certificate[] Getacceptedissuers () {return NewX509certificate[0]; }                    }},                    NULL); } Catch(Exception ex) {}} @Override Publicsocket Createsocket (socket socket, String host,intPortBooleanautoClose)throwsIOException, unknownhostexception {returnmctx.getsocketfactory (). Createsocket (socket, host, port, AutoClose); } @Override PublicSocket Createsocket ()throwsIOException {returnmctx.getsocketfactory (). Createsocket (); }    //The first parameter is the name of the server certificate for example: SERVER.CRT, the second parameter is the context of the app     Public Staticsslsocketfactory getsocketfactory (String crtname,context Context) {Try {            if(Crtname = =NULL|| "". Equalsignorecase (Crtname)) {                Throw  NewIllegalArgumentException ("Getsocketfactory crtname is null"); }            if(Context = =NULL){                Throw  NewIllegalArgumentException ("Getsocketfactory context is null"); } InputStream Certinputstream=NewBufferedinputstream (Context.getassets (). Open (Crtname)); Certificatefactory certificatefactory= Certificatefactory.getinstance ("the"); X509Certificate servercertificate=(X509Certificate) certificatefactory.generatecertificate (Certinputstream); //generate a KeyStore that protects the server certificateString Keystoretype =Keystore.getdefaulttype (); KeyStore KeyStore=keystore.getinstance (Keystoretype); Keystore.load (NULL,NULL); String alias=Servercertificate.getsubjectx500principal (). GetName ();            Keystore.setcertificateentry (alias, servercertificate); //Generate SslsocketfactorySslsocketfactory factory =Newsslverifylogservercrtsocketfactory (Crtname,keystore,context); returnFactory; } Catch(Throwable e) {e.printstacktrace (); }        return NULL; }}

Requirements use: To implement client-to-server verification, the legality of the authentication server certificate, when HTTPS in the handshake protocol is returned to the client's certificate should be the same as the domain name saved in the client's local certificate should be the same, stating that the certificate returned by the server to ensure that the local certificate is the same, Indicates that the server is legal

        Try {            = "Server.crt"; = Sslverifylogservercrtsocketfactory.getsocketfactory (crtname, mcontext);                          // Strict verification of the host's valid domain name             Sf.sethostnameverifier (sslsocketfactory.strict_hostname_verifier); return New Defaulthttpclient (CCM, params);

Where SERVER.CRT is the certificate stored in the mobile app such as the Assert directory, is the certificate that the app locally guarantees, the certificate must be exactly the same as the certificate configured in the background such as the Tomacat server, for the client to verify the legality of the server certificate, A certificate was saved in the mobile app client

Mcontext is the context of the activity or contextual phone, if the client and the server in the process of establishing HTTPS, if the server returned to the client's certificate domain name and the application of the local saved certificate resolves the domain name is the same, stating that the server is legitimate.

If the client establishes the HTTPS protocol with the server, does not verify the legality of the server, and trusts all the servers
 Packagecom.cetcs.logreport.utils;/*** Created by Wei.yuan on 2016/8/2. * * This class is primarily used for individual validation of server certificates*/Importorg.apache.http.conn.ssl.SSLSocketFactory;Importjava.io.IOException;ImportJava.lang.reflect.Field;Importjava.net.InetAddress;ImportJava.net.Socket;Importjava.net.UnknownHostException;Importjava.security.KeyManagementException;ImportJava.security.KeyStore;Importjava.security.KeyStoreException;Importjava.security.NoSuchAlgorithmException;Importjava.security.UnrecoverableKeyException;Importjava.security.cert.CertificateException;Importjava.security.cert.X509Certificate;ImportJavax.net.ssl.SSLContext;ImportJavax.net.ssl.TrustManager;ImportJavax.net.ssl.X509TrustManager; Public classSslsocketfactoryexextendssslsocketfactory {sslcontext sslcontext= Sslcontext.getinstance ("TLS");  PublicSslsocketfactoryex (KeyStore Truststore)throwsnosuchalgorithmexception, Keymanagementexception, Keystoreexception, unrecoverablekeyexception {
    Super(Truststore); //set up a trustmanager that trusts everythingTrustManager TM =NewX509trustmanager () { Publicx509certificate[] Getacceptedissuers () {//return new x509certificate[]{};                return NULL; } @Override Public voidCheckclienttrusted (x509certificate[] arg0, String arg1)throwscertificateexception {//TODO auto-generated Method Stub} @Override Public voidCheckservertrusted (x509certificate[] chain, String authtype)throwscertificateexception {//TODO auto-generated Method Stub            }        }; Sslcontext.init (NULL,NewTrustmanager[] {TM},Newjava.security.SecureRandom ()); } @Override PublicSocket Createsocket (socket socket, String host,intPortBooleanautoClose)throwsIOException, unknownhostexception {injecthostname (socket, host); returnsslcontext.getsocketfactory (). Createsocket (socket, host, port, AutoClose); } @Override PublicSocket Createsocket ()throwsIOException {returnsslcontext.getsocketfactory (). Createsocket (); }    Private voidinjecthostname (socket socket, String host) {Try{Field field= InetAddress.class. Getdeclaredfield ("HostName"); Field.setaccessible (true);        Field.set (Socket.getinetaddress (), host); } Catch(Exception ignored) {} }}

Tips for use:
   KeyStore Truststore = keystore.getinstance (Keystore.getdefaulttype ());            Truststore.load (nullnull);             New Sslsocketfactoryex (truststore);            Sf.sethostnameverifier (sslsocketfactory.allow_all_hostname_verifier);

This is generally a use of experience

The new experience of using HTTPS in Android to verify the validity of service certificates

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.