SoFunction
Updated on 2025-04-12

Springboot implements the example code of https two-way transmission protocol

Two-way transmission protocol concept

1.1. One-way authentication

  • We usually visit a website, such as Baidu. This is a one-way TLS certification.
  • The specific process is:
    • The server sends the certificate to the client.
    • After the client verifies that the certificate is valid, the client and the server negotiate a symmetric encryption key.
    • Encrypted by the server's private key and sent to the client.
    • After receiving it, the client decrypts the symmetric key with the public key. Then we start encrypting the transmitted data with a symmetric key.
  • feature:
    • The server does not verify the legitimacy of the client and does not refuse anyone. Most websites are of this type.
    • Only the client checks the legitimacy of the server side.

1.2. Two-way certification

  • Sometimes in some scenarios where security requirements are high, the server also needs to verify the legitimacy of the client.
  • The specific process is:
    • After the client verifies the legitimacy of the server certificate, the client needs to bring its own certificate and send it to the server.
    • After the server receives the certificate, it compares whether the server trusts the client's certificate in the trust chain.
    • If trusted, the server verify that the client is legal.
    • If the certificate is not on the trusted list on the server, service is denied.
  • This actually establishes a two-way authentication TLS transmission channel. That is, mutual verification certificate.

1.3. Asymmetric encryption interaction process

  • If you are using asymmetric encryption, then you have two pairs of public and private keys between you and the third party, each holding the other party's public key and your own private key. In network communication, we usually use our own private key to sign the message, and use the public key provided by a third party to encrypt the part of the message that involves security and privacy. Then the third party will use our public key to verify the message. After the verification is passed, we will use their own private key to encrypt and partially decrypt the message;

1.4. csr file

  • CSR is a Certificate Signing Request. To obtain an SSL certificate, you need to create a CSR file and submit it to the Certificate Authority (CA). CSR contains the public key used to issue certificates, the name information used to identify (Distinguished Name) (such as domain names), authenticity and integrity protection (such as digital signatures), and usually generates CSR from a web server;
  • As long as the certificate applicant submits the CSR file to the certificate authority, the certificate authority uses its root certificate private key signature to generate the certificate public key file, that is, the certificate issued to the user.

1.5. Certificate generation process

# 1. Generate client csr and private key key. After executing this instruction, the csr file and private key key will be generated.openssl req -new -nodes -sha256 -newkey rsa:2048 -keyout  -out 

# After generating the csr file, send the csr file to Party A, and Party A issues it to us
# When you access the Party A's interface, you will always carry and use local private keys for file and data encryption during transmission;

2. Use springboot to implement https two-way transmission protocol instance

2.1. Configure the certificate and private key paths

  • Configure the certificate and private key paths in the configuration file so that the project can be accessed;

2.2. Calling the request method

 // Call method    resp = (true, POST, url, req);

2.3. ApiService layer method

  @Override
    public String request(Boolean ssl, HttpMethod method, String url, String reqBody) throws Exception {
        // Call the request method below        return request(ssl, method, url, null, reqBody);
    }

    // Two-way authentication request    @Override
    public String request(Boolean ssl, HttpMethod method, String url, MultiValueMap<String, String> params,
            String reqBody)
            throws Exception {
        ("request url to server =====> {}", url);
        ("request body to server =====> {}", reqBody);
        // Add request header according to actual requirements        HttpHeaders headers = new HttpHeaders();
        ("token", "");

        ResponseEntity<String> resp = (ssl, url, method, headers, params, reqBody);
        String respBody = ();
        ("resp body from server =====> {}", respBody);
        return respBody;
    }

2.4. Methods in sslService class

        @Override
        public ResponseEntity<String> request(Boolean ssl, String url, HttpMethod method, HttpHeaders headers,
                        MultiValueMap<String, String> params, String reqBody) throws Exception {

                HttpsClient client = !ssl ? new HttpsClient(ssl)
                                : new HttpsClient(ssl, "Certificate Path", "Private Key Path");
                return (client, url, method, headers, params, reqBody);

        }

2.5. HTTPS communication bidirectional authentication tool class

        /**
          * @Description //HTTPS communication bidirectional authentication tool class
          **/

        @Data
        public class HttpsClient {
        
            // true - enable two-way authentication, false - not enabled            private boolean ssl;
            // Server public key            private String serverPem;
            // Client private key            private String clientSK;

            public HttpsClient() {
            }

            public HttpsClient(Boolean ssl) {
                 = ssl;
            }

            public HttpsClient(Boolean ssl, String serverPem, String clientSK) {
                 = ssl;
                 = serverPem;
                 = clientSK;
            }

}

2.6. Methods in RestClientUtil class

public static ResponseEntity<String> request(HttpsClient client, String url, HttpMethod method,
            HttpHeaders httpHeaders,
            MultiValueMap<String, String> params,
            String reqBody) throws Exception {
        ("Content-Type", "application/json; charset=utf-8");
        HttpEntity<?> requestEntity = new HttpEntity<>(reqBody, httpHeaders);

        UriComponentsBuilder builder = (url).queryParams(params);
//        UriComponentsBuilder builder = (url).queryParams(params);
        RestTemplate rest = ()
                ? new RestTemplate((client))
                : new RestTemplate(generateHttpRequestFactory());
        return ((), method, requestEntity, );
    }

  /**
      * Ignore SSL certificates
      *
      * @return
      */
    private static HttpComponentsClientHttpRequestFactory generateHttpRequestFactory() {

        TrustStrategy acceptingTrustStrategy = (x509Certificates, authType) -> true;

        SSLContext sslContext = null;

        try {

            sslContext = ().loadTrustMaterial(null, acceptingTrustStrategy).build();

        } catch (NoSuchAlgorithmException e) {

            ();

        } catch (KeyManagementException e) {

            ();

        } catch (KeyStoreException e) {

            ();

        }

        SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
                new NoopHostnameVerifier());

        HttpClientBuilder httpClientBuilder = ();

        (connectionSocketFactory);

        CloseableHttpClient httpClient = ();

        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();

        (httpClient);

        return factory;
    }

2.7. Methods in HttpsClientUtil class

 public static HttpComponentsClientHttpRequestFactory rsaHttpComponentsClientHttpRequestFactory(HttpsClient client)
            throws Exception {
        // Get the httpClient object to prevent repeated creation - read the certificate information, no other operations are done after the object is generated, so it is not locked        if (httpClient == null) {
            httpClient = createCloseableHttpClientByRsa(client);
        }
        HttpComponentsClientHttpRequestFactory httpsFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
//        (5000);
//        (5000);
        (60 * 1000);
        (60 * 1000);
        return httpsFactory;
    }

This is the article about springboot's example code to implement the https two-way transmission protocol. For more related springboot https two-way transmission content, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!