Android Security Encryption: HTTPS programming detailed _android

Source: Internet
Author: User
Tags rfc static class asymmetric encryption

Android security encryption feature article index

      • Android Secure encryption: Symmetric encryption
      • Android Secure encryption: Asymmetric encryption
      • Android Secure encryption: Message digest Digest
      • Android Security Encryption: Digital signatures and digital certificates
      • Android Secure encryption: HTTPS programming

The above learning all content, symmetric encryption, asymmetric encryption, message digest, digital signature and other knowledge is to understand the work of digital certificates as a preliminary knowledge. Digital certificate is the ultimate weapon in cryptography, is the crystallization of the wisdom of human thousands of years history, only after understanding the working principle of digital certificate, can we understand the secure communication mechanism of HTTPS protocol. It will eventually be handy in the SSL development process.

In addition, the two knowledge points of symmetric encryption and message digest can be used separately.

Knowledge Point Series:

Digital certificates use all the knowledge you have learned

    1. Symmetric encryption and asymmetric encryption are used to achieve the secret key exchange, after which the two parties use the secret key for symmetric encrypted communication.
    2. Message digest and asymmetric encryption to achieve digital signature, the root certificate authority to sign the target certificate, at the time of verification, the root certificate with the public key to verify it. If the checksum succeeds, the certificate is trusted.
    3. The Keytool tool can create certificates, then submit them to the root certification authority for direct use of self-signed certificates, as well as output the RFC format information for certificates.
    4. Digital signature technology realizes the guarantee of identity authentication and data integrity.
    5. The encryption technology guarantees the confidentiality of the data, the message digest algorithm guarantees the integrity of the data, the high efficiency of symmetric encryption guarantees the reliability of the processing, and the digital signature technology guarantees the non-repudiation of the operation.

Through the above content of learning, we should be able to grasp the following knowledge points:

    1. Basics: Bit bits, bytes, characters, character encodings, incoming transformations, IO
    2. Know how to use symmetric encryption to solve problems in actual development
    3. Know symmetric encryption, asymmetric encryption, message digest, digital signature, digital certificate is to solve the problem of what happened
    4. Understanding the SSL communication process
    5. How to request HTTPS interface in actual development

Overview

SSL (Secure Sockets Layer Security Sockets Layer), developed by Netscape (Netscape) to secure data transmission over the Internet, using data encryption (encryption) technology, Ensures that data is not intercepted and tapped during transmission over the network. General specifications for the safety of the bit of the standard, the United States has introduced a 128 bit of higher safety standards, but restricted exit. SSL can be supported as long as the 3.0 version is i.e. or Netscape browser.

TLS(transport Layer Secure Transport Layer Security) is used to provide confidentiality and data integrity between two communication applications. TLS is a standardized product of SSL, with 1.0, 1.1, 1.2 three versions, with the default of 1.0. TLS1.0 and SSL3.0 almost no
There is a difference, in fact we are now using TLS, but because of the history of the use of the term SSL.

SSL Communication Simple diagram:

SSL Communication Detail Diagram:

When requesting the use of a self-signed certificate for Web site data, such as a passenger service page requesting 12306: https://kyfw.12306.cn/otn/, the following error is reported because the client's root certification authority does not recognize the certificate error message: Unable to find Valid certification path to requested target

Solution 1

A certificate is not trustworthy, is determined by the TrustManager, so we only need to customize a nothing to do trustmanager can, the server to show all the certificates do not check, all release.

public static void Main (string[] args) throws Exception {//Protocol Transport Layer Security TLS (Transport layer Secure) sslcontext Sslcontext = SS
Lcontext.getinstance ("TLS");
Create trust Manager (TrustManager is responsible for verifying that the book is trustworthy) trustmanager[] tm = new Trustmanager[]{new Emptyx509trustmanager ()};
Initializes the SSL context object Sslcontext.init (NULL, TM, NULL) using a custom trust manager; Set up a global sslsocketfactory factory (which affects all SSL links) httpsurlconnection.setdefaultsslsocketfactory (

 Sslcontext.getsocketfactory ());
 URL url = new URL ("https://www.baidu.com");
 URL url = new URL ("https://kyfw.12306.cn/otn/");
 Httpsurlconnection conn = (httpsurlconnection) url.openconnection ();
 InputStream in = Conn.getinputstream ();
 System.out.println (Util.inputstream2string (in)); /** * Custom A trust manager does not do anything, all certificates do not check, all release/private static class Emptyx509trustmanager implements x509trustmanager{@ Override public void checkclienttrusted (x509certificate[] chain, String authtype) throws certificateexception {} @Ov Erride public void checkservertrusted (x509certificate[) ChaiN, String authtype) throws certificateexception {} @Override public x509certificate[] Getacceptedissuers () {return
 Null

 }
}

Solution 2

12306 the certificate is presented by the Chinese iron group Srca to him, so the Srca certificate is able to identify 12306 of the certificate, so only need to SRCA certificate into the system KeyStore, and then to trustmanagerfactory for initialization, The Srca can be added to the root certification authority, after the verification, Srca 12306 certificate verification can pass the certification.

There are two ways to use this solution: one is to use the Srca.cer file directly, and the other is to use the document in RFC format to write it in the code.

12306 RFC format for certificates (note to remember to manually add two line breaks) private static final String CERT_12306_RFC = "-----BEGIN certificate-----\ n" + "MIICMJC Cagogawibagiibyzr5/jkh6qwdqyjkozihvcnaqefbqawrzelmakga1uebhmcq04xktan "+" bgnvbaotifnpbm9yywlsienlcnrpzmljyxrpb24gqxv0ag9yaxr5mq0wcwydvqqdewrtuknbmb4x "+" DTA5MDUYNTA2NTYWMFOXDTI5MDUYMDA2NTYWMFOWRZELMAKGA1UEBHMCQ04XKTANBGNVBAOTIFNP "+" BM9YYWLSIENLCNRPZMLJYXRPB24GQXV0AG9YAXR5MQ0WCWYDVQQDEWRTUKNBMIGFMA0GCSQGSIB3 "+" DQEBAQUAA4GNADCBIQKBGQDMPBNEB34P0GVLKZ6T72/OOBA4MX2K/EZRWFFNUK8E5JKDH+9BGCB2 "+" 9bsotqpqtbxxwpxioz8ejyuo3bfr5pq8ovntolks2rs5bdmhoi4sujcki5eliqtyww/xgy5ifqv6 "+" D4Pw9QvOUcdRVSbPWo1DwMmH75It6pk /rarifhejwwidaqabo4gomiglmb8ga1udiwqymbaafhle "+" tne34lkdq+ 3huyhmy4usaenymawga1udewqfmambaf8wlgydvr0fbccwjtajocggh4ydahr0cdov "+" Lze5mi4xnjguos4xndkvy3jsms5jcmwwcwydvr0pbaqdagh+mb0ga1uddgqwbbr5xrz3t+jsg0pt "+" X1gitgoflabdwdanbgkqhkig9w0baqufaaobgqdgram2u/of1lbong2bnnqtgcvabxivjf8lkpav "+" 23xq96hu8xfgszmjs6u00whai7zp0q208rsuft9wdq9ee///vohzr6tebg9qfypsohkbrhxqenvq "+" og555s+c3ejaavenctems3n/m5hzbrjaoffn3qoydao1q8btguoi+2849a== "+"-----End certificate-----\ n "; public static void Main (string[] args) throws Exception {//Using Transport Layer Security Protocol TLS (Transport layer secure) Sslcontext Sslcontext
 = Sslcontext.getinstance ("TLS");
Use the form of the Srca.cer file//fileinputstream certinputstream = new FileInputStream (new file ("Srca.cer"));
Certificate Bytearrayinputstream certinputstream = new Bytearrayinputstream (Cert_12306_rfc.getbytes ()) can also be used in the form of an RFC string.
Initializes the KeyStore to import the certificate KeyStore KeyStore = keystore.getinstance (Keystore.getdefaulttype ());
Parameter null indicates the use of the system default KeyStore, or other keystore (which require the Srca.cer certificate to be imported into KeyStore) keystore.load (null); Create a certificate through a stream certificate certificate = certificatefactory.getinstance ("X.509"). Generatecertificate (CertInputStream)
;
Import Srca.cer This certificate into the KeyStore, alias is called Srca keystore.setcertificateentry ("Srca", certificate); Set up to use KeyStore for certificate validation trustmanagerfactory trustmanagerfactory = trustmanagerfactory. getinstance (
Trustmanagerfactory.getdefaultalgorithm ()); TrustManagerfactory.init (KeyStore);
With our set of TrustManager to do SSL communication protocol verification, that is, certificate verification sslcontext.init (NULL, trustmanagerfactory.gettrustmanagers (), NULL);
Httpsurlconnection.setdefaultsslsocketfactory (Sslcontext. getsocketfactory ());
URL url = new URL ("https://kyfw.12306.cn/otn/");
Httpsurlconnection conn = (httpsurlconnection) url.openconnection ();
InputStream in = Conn.getinputstream ();
System.out.println (Util.inputstream2string (in));

 }

HTTPS request in Android:

Take the Scra.cer file to the assets or raw directory, or use the RFC format of the certificate directly, the following procedure is the same as the Java Engineering code

Bytearrayinputstream in = new Bytearrayinputstream ("RFC". GetBytes ());
Certificatefactory CF = Certificatefactory.getinstance ("X.509");
InputStream cainput = new Bufferedinputstream (New FileInputStream ("LOAD-DER.CRT"));
Certificate CA;
 try {CA = cf.generatecertificate (cainput);
System.out.println ("ca=" + (X509Certificate) CA). Getsubjectdn ();
finally {cainput.close ();}
String Keystoretype = Keystore.getdefaulttype ();
KeyStore KeyStore = keystore.getinstance (Keystoretype);
Keystore.load (null, NULL);

Keystore.setcertificateentry ("Ca", CA);
String tmfalgorithm = Trustmanagerfactory.getdefaultalgorithm ();
Trustmanagerfactory TMF = trustmanagerfactory.getinstance (tmfalgorithm);

Tmf.init (KeyStore);
Sslcontext context = sslcontext.getinstance ("TLS");

Context.init (NULL, tmf.gettrustmanagers (), NULL);
URL url = new URL ("https://certs.cac.washington.edu/CAtest/");
Httpsurlconnection URLConnection = (httpsurlconnection) url.openconnection (); Urlconnection.setsslsocketfactory (context. Getsocketfactory ());
InputStream in = Urlconnection.getinputstream ();

 Copyinputstreamtooutputstream (in, System.out);

Bidirectional certificate Validation

Certificatefactory certificatefactory = certificatefactory.getinstance ("X.509");
KeyStore KeyStore = keystore.getinstance (Keystore.getdefaulttype ());
Keystore.load (null);

Sslcontext Sslcontext = sslcontext.getinstance ("TLS");
Trustmanagerfactory trustmanagerfactory = trustmanagerfactory.
 GetInstance (Trustmanagerfactory.getdefaultalgorithm ());
Trustmanagerfactory.init (KeyStore);

Initialize KeyStore
KeyStore clientkeystore = keystore.getinstance (Keystore.getdefaulttype ());
Clientkeystore.load (Getassets (). Open ("Client.bks"), "123456". ToCharArray ());

Keymanagerfactory keymanagerfactory = keymanagerfactory.getinstance (Keymanagerfactory.getdefaultalgorithm ());
Keymanagerfactory.init (Clientkeystore, "123456". ToCharArray ());

Sslcontext.init (Keymanagerfactory.getkeymanagers (), Trustmanagerfactory.gettrustmanagers (), New SecureRandom ());

Nogotofail

Network traffic Security Testing tool, Google's Open source project: Https://github.com/google/nogotofail

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.