Android Network programming series one javasecurity Jsse (SSL/TLS)

Source: Internet
Author: User
Tags hmac asymmetric encryption cipher suite

Pick to:Java security has been in Java for a long time and it is a very important and independent section, containing a lot of knowledge points, common md5,digitalsignature and so on, and Android in the Java seurity outside, Expanded a android.security package, which provides keychain in this package. It contains the main three important specifications: Javacryptography Extension (JCE), the JCE contains the contents of the decryption, key exchange, message digest (messages Digest, such as MD5, etc.), key management and so on. Most of the content involved in this article belongs to the Jsse category, and Jsse contains the Java layer of SSL/TLS. Simply put, you can create a SSL/TLS socket using Jsse.    Javaauthentication and Authorization Service (Jaas), Jssa and authentication/authorization related, this part of the content in the client contact will be less. In the above three sub-modules or specifications, the JCE is the big head of Javasecurity, the other two sub-modules Jsse and Jaas rely on it, such as SSL/TLS in the process of working with a key to the data encryption and decryption, then the creation and use of the key depends on the JCE sub-module. However, this article will focus on the SSL/TLS protocol in the main Jsse section, focusing on the security of the SSL/TLS protocol and the details of the communication, while comparing and supporting this application in Android or Java programs. A: Introduction    SSL (Secure Socket Layer) that is: Secured sockets layers,  It is developed by netscape  to guarantee secure transport protocols in  web, The aim is to provide confidentiality, authentication, and data integrity assurance for network communications, using data encryption   (encryption)   technology to ensure that data is not intercepted and tapped during transmission over the network. It has been widely used to authenticate and encrypt data transfer between the  Web  browser and server. The  SSL  protocol is located between the  TCP/IP  protocol and various application layer protocols, providing security support for data communication. First, SSL has become an industry standard for secure Internet communications.      ssl initially several versions (SSL 1.0, SSL2.0, SSL 3.0) were designed and maintained by Netscape, starting with version 3.1, the SSL protocol was formally taken over by the Internet Engineering Task Force (IETF) and renamed to TLS ( Transport Layer Security), the development has been the TLS 1.0, TLS1.1, TLS1.2 these several versions.   As the TLS name says, the SSL/TLS protocol only guarantees transport layer security. At the same time, SSL/TLS cannot be used to protect multi-hop (multi-hop) end-to-end communication, but only point-to-point communication, due to the Protocol's own characteristics (digital certificate mechanism). The security objectives that the   SSL/TLS protocol can provide include the following:  authentication-authentication of server-side and client identities with digital certificates, protection against identity forgery, ensuring that data is sent to the correct   client and server   confidentiality- Protect against third-party eavesdropping   integrity with encryption-protect data integrity with message authentication codes (macs), prevent message tampering   replay protection-prevent replay attacks by using implicit serial numbers   to achieve these security objectives, ssl/ The TLS protocol is designed as a two-stage protocol, which is divided into the handshake phase and the application phase of the:  handshake phase, also known as the negotiation stage, in this phase, the client and server will authenticate the identity of the other (relying on the PKI system, the use of digital certificates for identity authentication), and negotiate the use of communication security parameters, Cipher suites and Mastersecret. All keys used for subsequent communications are generated through Mastersecret.   After the handshake phase is complete, enter the application phase. In the application phase, both parties use the handshake phase to negotiate a good key into theSecure communication. The         SSL/TLS protocol has a highly modular architecture that is divided into many sub-protocols, as shown in:


Handshake protocol: Including negotiate security parameters and cipher suite, server Authentication (optional client authentication), key exchange;

CHANGECIPHERSPEC protocol: A message indicates that the handshake protocol has been completed;

Alert protocol: Some exceptions to the Handshake protocol error alert, divided into fatal and warning two levels, fatal type of error will directly interrupt the SSL link, and warning level of the error SSL link can continue, but will give an error warning;

Record protocol: Includes fragmentation of messages, compression, message authentication and integrity protection, encryption, and so on. II: SSL/TSL protocol ProcessSSL/TSL protocol can be divided into the following two types: 1> one-way authentication client and server-side only one-sided authentication is: The client needs the server-side certificate authentication, and the service side does not require client certificate authentication. At first, the client will send a greeting message with the version, encryption system, compression algorithm and other related information, the server received, to the client to confirm the selected version, encryption system and so on information. The server will then send its own certificate containing information such as the public key to the client, the client obtains the public key, the data to be sent will be encrypted, and sent to the server. Upon receipt of the server, the received client-side encrypted data is decrypted with the local private key. The data is then applied on both sides of the communication to generate an encryption key for communication between the two sides. Next, you can start the communication process on both sides. 2&gt Two-way authentication bidirectional authentication and one-way basic similar, but several authentication links. Since it is two-way authentication, it also means that the server needs to obtain the client side certificate to obtain the clients ' public key. The client then sends a data encrypted with its own private key to the server, which is then authenticated with the public key it obtains after it is received by the server.   Other links are the same as the one-way. is a typical TLS 1.0 protocol interaction process as shown in: Each SSL/TLS link starts with a handshake, and the handshake process contains a sequence of messages to negotiate security parameters, cipher suites, identity authentication, and key exchange.     The messages in the handshake must occur in a predefined order, or a potential security threat will arise. Clientsayhi: First the client sends such a message with a list of cipher suites supported by clients, a list of the highest SSL/TLS protocol versions, a list of cryptographic algorithm types, and compression algorithms, among other things required for communication between the server and the client.
In addition, a random number is included in the Clientsayhi, which consists of 4 bytes of the current GMT Unix time and 28 randomly selected bytes, a total of 32 bytes. This random number is used in the server-side public key generation process. The Clientsayhi may also contain TLS extensions that are supported by the client. (TLS extensions can be used to enrich the functionality of the TLS protocol or to enhance the security of the Protocol)
Serversayhi: The SERVERSAYHI message is returned when the server is accepted. The server selects the items it supports from the list of cipher suites, SSL/TLS versions, cryptographic algorithms, etc. provided by the client in the CLIENTSAYHI message and includes its selection in the Serversayhi to inform the client. The SSL protocol is then established based on the type of cipher suite selected by the server, the SSL/TLS protocol version, and the encryption algorithm. Serversayhi also contains a random number, the same 4+28 byte type, generated by the server.
Certificate: Both the client and the server can send a certificate message to prove their identity, but typically the client certificate is not used. Server generally after Serversayhi will send a certificate message, the certificate contains the data encryption algorithm type, server side of the generated random number and public key information, customer use the server passed the certificate to extract relevant information to verify the legitimacy of the server, The legitimacy of the server includes whether the certificate expires, whether the CA that issued the server certificate is reliable, if the public key of the publisher's certificate correctly unlocks the publisher's digital signature for the server certificate, and whether the domain name on the server certificate matches the actual domain name of the server. If the legitimacy verification is not passed, the communication will be disconnected; The current mainstream certificate format is the X509 certificate format, with the use of the certificates of the first edition containing versions 1 and version 32, where the V1 version of the certificate has a security risk, and does not support TLS extension, is gradually deprecated. Most of the SSL certificates that are used now are V3 versions. The certificate also comes with a key corresponding to the negotiated key exchange algorithm.
Serverkeyexchange: This message is issued by the server only when the following encryption algorithm is used (that is, when the server side chooses one of the algorithms listed below in the cryptographic algorithm list provided by the client side, Next the server will continue to send a serverkeyexchange message): Rsa_export (only if the server's public key is greater than 512bit), Dhe_dss, Dhe_dss_export, Dhe_rsa, Dhe_rsa_ When EXPORT and Dh_anon use other key exchange algorithms, the server cannot send this message. The Serverkeyexchange message carries the additional parameter information required by the corresponding cryptographic algorithm, which in the future will be further upgraded to the cryptographic algorithm on the client side with the servery-side conventions. At the same time, these parameters need to be signed.
Certificaterequest: This message is usually a two-way authentication when the authentication client is required. The message contains the type of certificate and the list of acceptable CAs.

Serversayhidone: The server sends this message indicating that the key exchange information for the server part has been sent, waiting for the client's message to continue with the next steps. This message is used only as a reminder and does not contain data fields.
Clientkeyexchange: This message contains data related to the selected key exchange algorithm. Before this, the client randomly generates a "symmetric password", which is a temporary key (key) for subsequent communication, with 48 bytes, the first 2 bytes representing the highest protocol version supported by the client, and the next 46 bytes being randomly selected. The secret key and the client side public key are simultaneously called the server side public key that is contained in the previous certificate or in the Serverkeyexchange, then it is sent to the servers with the Clientkeyexchange message. The server will use its own private key to decrypt the "symmetric password", which will be used as the data encryption algorithm in communication later, to ensure the security of data transmission. If the selected key exchange algorithm is DH or dhe, there are two possible cases: implicit DH exposure value: Included in the certificate message; Show DH exposure Value: The exposed value is part of this message.
Certificateverify: This message is used to prove that the client has the private key of the client certificate that was submitted before, when the two-way authentication is used, the message will carry a client with its own private key to produce a number, after the server receives this data,  The public key that was previously received by the client is decrypted for verification. CHANGECIPHERSPEC protocol: The client side then sends a message indicating that the handshake protocol has been completed and switched to the encryption mode;
Finished: Indicates the end of the handshake phase. This is the first message to be protected with a negotiated algorithm and key. Because it is a message encrypted with a negotiated key, it can be used to confirm the key that has been negotiated. The finished message also contains a verify_data domain that can be used to verify information that was sent and received before. The Verify_data field is the output of a PRF function (pseudo-random functions). The input of this pseudo-random function is: (1) Two hash values: one SHA-1, one MD5, all messages exchanged during the previous handshake Cryptographic hashing feature(Message digest), where the server can verify the integrity of the transmitted data based on the hash value and the MD5 value of the data, (2) The Mastersecret, generated by the preliminary master key. After the server side receives the client side Changecipherspec and finished message, then also sends a CHANGECIPHERSPEC message Surface server side also switched to the encryption mode, the handshake protocol ended. It will also send a finished indicating that the client has received a finished request to formally end the handshake.     In addition, finished messages cannot be sent before Changecipherspec. It is not difficult to find that the SSL/TSL communication protocol is actually the use of two algorithms: symmetric and asymmetric encryption. In the protocol handshake, both sides get each other's public key parsing data to generate and obtain the next communication key here is an asymmetric encryption process.     Next use the resulting communication key to decrypt the communication data, which is a symmetric encryption process. In addition, we also need to understand the following nouns:

key: belongs to the JCE category, can be divided into symmetric key and asymmetric key. The symmetric key is the secret key that the next communication parties use to encrypt the data, and the asymmetric key is the public key and the private key. Its internal representation is a class whose external representation is a bit string, and key is used to encrypt and decrypt data, like a key to unlock.

symmetric encryption (symmetric cryptography): is required on both sides of the same key to encrypt the decryption message algorithm, common key algorithm has Data Encryption Standard (DES), Triple-strength DES (3DES), Rivest Cipher 2 (RC2) and Rivest Cipher 4 (RC4). Because of the relatively high effectiveness of the symmetric algorithm, the sensitive data in the SSL session is encrypted by the process key algorithm.

Asymmetric Encryption (Asymmetric Cryptography): is the composition of the key is the public key private key pair (Key-pair), the public key is passed to the other party to save the private key itself. The public key private key algorithm is reciprocal, one to encrypt and the other to decrypt. Common algorithms are Rivest Shamir Adleman (RSA), Diffie-hellman (DH). The asymmetric algorithm is designed to be very slow, and it is to encrypt the communication that is only useful for a small amount of data encryption, such as encryption of the key, and not suitable for multi-volume data.

Cryptographic hashing function (cryptographic hash Functions): The cryptographic hash function is similar to the checksum function. The difference is that checksum is used to detect unexpected data changes while the former is used to detect intentional data corrections. The data is hashed to produce a small string of bits, and a small change in the data will result in a hash string change. When sending encrypted data, SSL applies cryptographic hashing to ensure data consistency, which is used to block third-party broken communication data integrity. The commonly used hashing algorithms for SSL are Message Digest 5 (MD5) and Secure hash Algorithm (SHA).

Message Authentication Code (MSGAuthentication code): message authentication code is similar to the cryptographic hash function, On the basis of the hash encryption machine it is necessary to connect the data generated by the key information and the cryptographic hashing function to the hash message authentication Code (HMAC). If a wants to make sure that the message to B is not corrected by C, he will do--a at the following pace first generates an HMAC value, and adds it to the original message. Encrypt the message body with the key that communicates between A and B, and then send it to B. B after the message is decrypted with the key, and then re-create an HMAC value on the communication data, compare the front and back two values to determine whether the message was corrected in transit.

DigitalSignature: When a cryptographic hash of a message is created, the hash value is encrypted with the sender's private key, and the result of the encryption is called a number.

Three: Practical Application Notes  This case is divided into two parts, one is the server, the other is the client.   The server prints out the received client data, which is a string sent by the print client. Server side:
void Initserver () {try {//Get secure environment for SSL protocol, or TLS Sslcont Ext Scontext = Sslcontext.                                 getinstance ("SSL"); Get JKS Algorithm format key memory-common with JKS, Jceks,and PKCS12. The function of the comparison is jceks KeyStore store = KeyStore.                                          getinstance ("JKS");                                          Assetmanager manager = Mcontext.getassets ();                                                                InputStream is = Manager.open ("Test_key_store"); Import the certificate into the KeyStore and configure it with an open password.                                           Sometimes we need to have a different type of secret key to store Store.load (IS, "Kevin"). ToCharArray ());                                           Is.close (); To manage multiple or multiple keystore, the concept of a key manager is introduced, which is to specifically manage multiple or multiple key memory keymanagerfactory factory = Keymanagerfactory.getins                               Tance (keymanagerfactory. Getdefaultalgorithm ());                                 Give each key Manager the placement of the KeyStore configuration a Get password Factory.init (store, "123456". Tochararra                                           Y ()); /** * Initializes the SSL protocol security environment.                      The init function has three parameters, the first is the Keymanager array, and the server side needs to use the saved private key in it to sign the certificate * The second is the TrustManager array, the third is the SecureRandom, which is used to create a random number                      * For the server side, it does not need to validate the client certificate, so it is clear that the first parameter is used to create the server socket, and the second parameter is used to create the client socket (also can not fill) */                                                                Scontext.init (factory.getkeymanagers (), NULL, NULL); The following is the configuration IP and port to link inetaddress address = inet4address.                                          Getlocalhost (); Sslserversocket ServerSocket = (sslserversocket) scontext.getserversocketfactory (). Createserversocket (8666,1,                                          address);                                          Socket socket = serversocket.accept (); InputStream in = Socket.getinputstrEAM ();                                           byte[] data = new byte[1024];                                          int count = in. Read (data); Log.                                           I ("TAG", "Data:" +new String (data, 0, count));                                           In.close ();                                           Socket.close ();                                   Serversocket.close (); } catch (NoSuchAlgorithmException e) {//TODO auto-generated catch block E.pri              Ntstacktrace (); } catch (Keystoreexception e) {//TODO auto-generated catch block E.printstack              Trace (); } catch (Certificateexception e) {//TODO auto-generated catch block e.printst              Acktrace ();                      } catch (IOException e) {//TODO auto-generated catch blockE.printstacktrace (); } catch (Unrecoverablekeyexception e) {//TODO auto-generated catch block e.pr              Intstacktrace (); } catch (Keymanagementexception e) {//TODO auto-generated catch block E.print              StackTrace (); }                     }
Client side:
void Initclient () {try {//Get secure environment for SSL protocol Sslcontext Scontext = Sslco ntext.                                 getinstance ("SSL"); Gets the BKS algorithm format of the KeyStore-android in the common format KeyStore store = KeyStore.                                          getinstance ("BKS");                                           Assetmanager manager = Mcontext.getassets ();                                                                Here is a certificate created using the Java-brought tool Keytool placed in the project assert file InputStream is = Manager.open ("Test_key_store"); Import the certificate into the KeyStore and configure it with an open password.                                           Sometimes we need to have a different type of secret key to store Store.load (IS, "Kevin"). ToCharArray ());                                                               Is.close (); Trustmanagerfactory trustmanagerfactory = trustmanagerfactory.getinstance (trustmanagerfactory. getDefaultAlgorithm                                                              ());  Initialize trustmanagerfactory to import the contents of the certificate into the Trustmanagerfactory.init (store); /** * Initializes the SSL protocol security environment. The init function has three parameters, the first is the Keymanager array, the second is the TrustManager array, and the third is the SecureRandom, which is used to create a random number of * for CL On the ient side, it needs to verify the server-side certificate, so it only needs to be able to go while the second parameter (also can not fill) */Scontext.init (NULL, TRUSTMANAGERFA                                                                Ctory. Gettrustmanagers (), NULL); The following is the configuration IP and port to link inetaddress address = inet4address.                                          Getlocalhost ();                                          Sslsocket socket = (sslsocket) scontext.getsocketfactory (). Createsocket (address, 8666);                                          OutputStream out = Socket.getoutputstream ();                                           String data = "Hello i ' m spencer but can call me Kevin";   Out.write (Data.getbytes ());                                        Out.close ();                                   Socket.close (); } catch (NoSuchAlgorithmException e) {//TODO auto-generated catch block E.pri              Ntstacktrace (); } catch (Keystoreexception e) {//TODO auto-generated catch block E.printstack              Trace (); } catch (Certificateexception e) {//TODO auto-generated catch block e.printst              Acktrace (); } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (              ); } catch (Keymanagementexception e) {//TODO auto-generated catch block E.print              StackTrace (); }                     }
Four: summary  Jsse Introduction is over. The content of the JCE will be sorted out later, there is no description of the above or in doubt can be said to discuss together!

Android Network programming series one javasecurity Jsse (SSL/TLS)

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.