JavaWeb~ajax cross-domain problem/socket construction request/Https protocol/asymmetric encryption process/certificate mechanism

Solve jax cross domain problem

The following code, we use ajax to initiate an http request.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
    //基于jQuery 里面的ajax 来进行使用

    $.ajax({
     
        //$是jQuery中已经定义好了的一个对象(变量)

        // jQuery中的所有的api都是$对象的方法
        type:'GET',
        url:'https://www.baidu.com',
        success:function (data,status) {
     
     
            //data就是响应的body,status 就是响应的状态码
            console.log(status);
            console.log(data);
        }
    });
</script>
</body>
</html>

When we change the url in the above code to Baidu's url and run it again, the following situation will occur.
insert image description here
This is the cross-domain problem.
That is, in order to ensure security, ajax requires that the page that initiates the ajax request and the server that accepts the ajax request should be under the same domain name/address.
If the domain name corresponding to the page that initiates the request (assume domain name A) and the domain name of the server that accepts the request (assume domain name B) are different, it is considered to be a sequential cross-domain request.
ajax by default does not allow cross-domain access.
In the above code, domain name A corresponds to the local domain name, while domain name B is Baidu's domain name, and the two are different. It is considered to be cross-domain and an error is reported.
In the last blog, we used ajax to request a cloud server. Although accessing the cloud server on a local page is also a cross-domain access, the last cloud server has undergone special processing, which has solved the restriction that ajax cannot cross-domain.
The processing is as follows:
insert image description here
Configure cross-domain in the server code to allow local access to the server.

socket construct http request

The HTTP protocol is also based on TCP, but on the basis of TCP, a string is constructed and sent according to the format agreed by HTTP. We can "assemble" strings and send requests through sockets in Java.
code show as below:

import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class HttpClient {
    
    
    private Socket socket;
    private String ip;
    private int port;
    public  HttpClient(String ip,int port) throws IOException {
    
    
       this.ip=ip;
       this.port=port;
        socket=new Socket(ip,port);

    }

    public String get(String url) throws IOException {
    
    
        StringBuilder request=new StringBuilder();
        //构造首行
        request.append("GET"+url+"HTTP/1.1\n");
        //构造请求头header
        request.append("Host:"+ip+":"+port+"\n");
        //构造空行
        request.append("\n");

        //GET 请求不需要body

        OutputStream outputStream=socket.getOutputStream();
        //OutputStream 是一个字节流 ,以字节为单位进行写入
        // 因此需要把StringBuilder 转换成一个字节数组
        outputStream.write(request.toString().getBytes());

        //读取响应
        InputStream inputStream=socket.getInputStream();
        //创建一个1M大小的缓冲区,用来存放响应数据
        byte[] buffer=new byte[1024*1024];

        //n 表示实际读到的字符串
        int n=inputStream.read(buffer);

        return new String(buffer,0,n);

    }

    public String post(String url,String body) throws IOException {
    
    
        StringBuilder request=new StringBuilder();
        //构造首行
        request.append("POST"+url+"HTTP/1.1\n");

        //构造header
        request.append("Host:"+ip+":"+port+"\n");
        request.append("Context-type:text/plain\n");
        request.append("Content-Length:"+body.getBytes().length+"\n");


        //构造空行
        request.append("\n");
        //构造body
        request.append(body);

        //发送请求

        OutputStream outputStream=socket.getOutputStream();
        outputStream.write(request.toString().getBytes());
        //读取响应
        InputStream inputStream=socket.getInputStream();
        byte[] buffer=new byte[1024*1024];
        int n=inputStream.read(buffer);
        return new String(buffer,0,n,"utf-8");
    }

    public static void main(String[] args) throws IOException {
    
    
        HttpClient httpClient=new HttpClient("42.192.83.143",8089);
        String resp= httpClient.get("/AjaxMockServer/info");
        System.out.println(resp);
    }
}

HTTPS protocol

What is the
HTTPS full name of HTTPS ( Hypertext Transfer Protocol over Secure Socket Layer, Hypertext Security Transfer Protocol), HTTPS is a transmission protocol for secure communication over the network, the protocol is based on the HTTP protocol, introduces an encryption layer, and uses SSL/TLS to encrypt data packets.
The main function of HTTPS is to provide authentication for website servers to protect the privacy and integrity of data transmission.

Data encryption related concepts

Plaintext: The actual data to be transmitted
Ciphertext: The message after
encryption Encryption: Turning plaintext into ciphertext
Decryption: Turning ciphertext into plaintext
Key (yao, four tones): In the process of encryption and decryption, an intermediate data to assist in this process, such data is called a key

How HTTPS works

In order to ensure 数据the security, it needs to be encrypted, so in the network transmission, the plaintext is no longer directly transmitted , but the encrypted ciphertext is transmitted .

There are many ways to encrypt, but the whole can be divided into two categories: 对称加密and非对称加密

Symmetric encryption :
Symmetric encryption is actuallyWith only one key, plaintext and ciphertext can be converted into each other.

Example:

We can use the XOR operation to implement a simple symmetric encryption. Set the plaintext to 8888 and the key to 1234, and XOR the two to get the ciphertext 9834. The XOR of the ciphertext and the key can be decrypted to get the plaintext 8888

Through symmetric encryption, we can protect the data. Even if a hacker invades the router, only the ciphertext content of the request can be obtained.
insert image description here
The above method is good, but there is a defect, that is, how to agree on the key? We can only let the client generate a key first, and then when the client connects to the server, pass the key to the server and let the server save it.
But if the hacker intercepts the key when the server and client connect, how can the data be kept safe? We can encrypt the key and transmit the key of the key.
But this leads to the chicken-and-egg problem, and it is impossible to keep encrypting, so we enter asymmetric encryption.

Asymmetric encryption :

Asymmetric encryption isThrough a pair of keys , the plaintext and the ciphertext are converted into each other.
These two keys, one is called 公钥and the other is called 私钥.

The plaintext is encrypted by the public key and becomes ciphertext.
Decrypt the ciphertext with the private key and turn it into plaintext.
You can also use the reverse to
encrypt the plaintext with the private key and turn it into ciphertext.
The ciphertext is decrypted by the public key and becomes plaintext.

The public key and private key here can be compared to a mailbox in real life~ The public key is like the lock on the mailbox, and the private key is like the key that makes the lock

Disadvantages of asymmetric encryption :
very slow, much slower than symmetric encryption

Asymmetric encryption process

The server sends the public key (the public key) directly to the client. After the client obtains the public key, it encrypts the key with the public key and sends it to the server, and the server obtains the key by decrypting the private key. After that, the message of receiving the key is encrypted by the key and sent to the client. After the client receives it, it uses the key to transmit data with the client through symmetric encryption.
insert image description here
Summary :

  • The server and client connect and send the public key to the client.
  • The client generates a key locally, encrypts it with the public key, and sends it to the server.
  • Since the intermediate network devices (such as routers, etc.) do not have a private key, even if the data is intercepted, the internal data cannot be restored, and there is no way to obtain the symmetric key.
  • The server decrypts with its own private key, restores the key sent by the client, and then uses this key to encrypt the response data and return it to the client.
  • Subsequent client and server communications can only be encrypted using symmetric encryption.

Why continue to use symmetric encryption when asymmetric encryption has been introduced? ?
Because 对称加密the consumption of resources and the running speed are far lower 非对称加密, in actual situations, the data that the client and the server interact with are very large. If all use asymmetric encryption, the overall transmission speed will be very slow. Therefore, we only need to let the server obtain the key through asymmetric encryption, and then use symmetric encryption to improve the transmission efficiency.

Problems that remain

How does the client get it 公钥?
How to ensure that what the client obtains 公钥is authentic and reliable, not forged by hackers? ?

Anyone can generate a pair of public key and private key, not only the server can generate it, but hackers can generate it themselves

Suppose the following scenario, a hacker hacked into an intermediate network device and generated a pair of public pub2and private keys by himself pri2. The server generated the public pub1and private keys pri1. The server requests the public key from the server through the intermediate device, and the server returns the public key pub1, which is intercepted by the hacker, and the hacker sends the forged public key pub2 to the client.
insert image description here
Next, the client pub2encrypts the ciphertext and transmits the ciphertext to the intermediate device. The hacker can then pri2decrypt the ciphertext to obtain the real key, and then continue to pub1encrypt the ciphertext and send it to the server pri1. got the key. At this time, although the server got the key, the hacker also got the key without knowing it. Therefore, the subsequent encrypted transmission of data is useless, and hackers can directly obtain all plaintext data.
This is also called 中间人攻击.
insert image description here
So how to solve this problem? ?
To solve this problem, 证书机制.

Certificate mechanism

When the client and server connect for the first time, the server returns a certificate to the client.
This certificate contains not only the public key , but also the identity information of the website .

Workflow :

The server first generates a pair of public key and private key, and then applies for a certificate from a third-party agency, and then the server puts the public key into the certificate and sends the certificate to the client. Even if a hacker invades an intermediate device and obtains a certificate, it is very difficult for a hacker to forge a certificate because the verification of the certificate is very strict. Even if the certificate is forged, the client can go to a third-party organization for verification. Therefore, the client can successfully get the real public key, and then encrypt the key and send it to the server. Since the hacker does not have the private key, the intercepted data cannot be deciphered. Therefore, the server can successfully obtain the encrypted key.

This ensures the security of asymmetric encryption.
insert image description here

This process is also the handshake process of SSL/TLS

Certificate content :
The certificate can be regarded as a structured string, which contains the following information:

  • Certificate issuing authority
  • Certificate validity period
  • public key
  • certificate owner
  • sign

Certificate verification:

  • Determine whether the validity period of the certificate has expired
  • Determine whether the certificate issuing authority is trustworthy
  • Determine whether the certificate has been tampered with (this judgment process is more complicated and will not be introduced here)

View the certificate in the browser :
Chrome browser, open the settings in the upper right corner, search for the certificate, on the Manage Certificates page, click Trusted Root Certification Authorities, you can see the certificate information in the current browser.
insert image description here

Summarize

There are three sets of keys involved in the entire working process of HTTPS
第一组(非对称加密): used to verify whether the certificate has been tampered with. The server holds the private key (the private key is obtained when the certificate is registered), and the client holds the
public key (the operating system contains a trusted What are the CA certification authorities, and also hold the corresponding public key). The server uses this private key to
encrypt the signature of the certificate. The client decrypts the public key to obtain the signature of the certificate, so as to verify whether the content of the certificate has been tampered with.
第二组(非对称加密): used for negotiation to generate a symmetric encryption key. The server generates this set of private key-public key pairs, and then passes the public key
to the client through a certificate. Then the client uses this public key to encrypt the generated symmetric encryption key, It is transmitted to the server, and the server
obtains the symmetric encryption key by decrypting the private key.
第三组(对称加密): The subsequent data transmitted by the client and the server are encrypted and decrypted by this symmetric key.

Reference article:
https://leheavengame.com/article/622e001dcbba634f3982e4cb

Guess you like

Origin blog.csdn.net/Merciful_Lion/article/details/123486719