Table of Contents
SpringBoot’s API encryption docking
Project introduction
What is RSA encryption
Encryption Practice
Practical preparation
real swords and real guns
解密实战
实战准备
真刀真枪
总结
项目坑点
Home Java javaTutorial How SpringBoot implements api encryption

How SpringBoot implements api encryption

May 15, 2023 pm 11:10 PM
api springboot

SpringBoot’s API encryption docking

In the project, in order to ensure the security of the data, we often encrypt the transmitted data. Commonly used encryption algorithms include symmetric encryption (AES) and asymmetric encryption (RSA). The blogger selected the simplest API encryption project on Code Cloud for the following explanation.

Please list our brightest project below

rsa-encrypt-body-spring-boot

Project introduction

This project uses RSA encryption method Encrypt the data returned by the API interface to make the API data more secure. Others cannot decipher the data provided. Spring Boot interface encryption can automatically encrypt and decrypt return values ​​and parameter values ​​through annotations.

What is RSA encryption

First of all, of course we understand RSA encryption

RSA encryption is an asymmetric encryption. Decryption can be accomplished without passing the key directly. This ensures the security of the information and avoids the risk of being cracked due to direct transmission of keys. It is a process of encryption and decryption using a pair of keys, called public key and private key respectively. There is a mathematical correlation between the two. The principle of this encryption algorithm is the difficulty of factoring a very large integer to ensure security. Usually individuals keep private keys and public keys are public (may be held by multiple people at the same time).

How SpringBoot implements api encryption

For example

Encryption and signature are both for security reasons, but they are slightly different. People often ask whether to use private keys or public keys for encryption and signatures? In fact, they are all confused about the role of encryption and signature. Simply put, encryption is to prevent information from being leaked, and signature is to prevent information from being tampered with. Here are 2 examples.

The first scene: On the battlefield, B wants to send a message to A, the content of which is a certain instruction.

The encryption process of RSA is as follows:

(1) A generates a pair of keys (public key and private key). The private key is not made public and A keeps it to himself. The public key is public and can be obtained by anyone.

(2) A passes its public key to B, and B uses A’s public key to encrypt the message.

(3) A receives the message encrypted by B and uses A's own private key to decrypt the message.

In this process, there are only two transmission processes. The first time is A transmitting the public key to B, and the second time B transmits the encrypted message to A. Even if they are intercepted by the enemy, there is no danger. , because only A’s private key can decrypt the message, preventing the leakage of the message content.

**Second scenario:**After A receives the message from B, it needs to reply "received".

The process of RSA signature is as follows:

(1) A generates a pair of keys (public key and private key). The private key is not made public and A keeps it to himself. The public key is public and can be obtained by anyone.

(2) A signs the message with its own private key to form a signature, and passes the signed message and the message itself to B.

(3) After B receives the message, it obtains A's public key to verify the signature. If the content of the signature is consistent with the message itself, it proves that the message is replied by A.

In this process, there are only two transmission processes. The first time is when A transfers the signed message and the message itself to B. The second time is when B obtains A's public key, even if they are intercepted by the enemy. , and there is no danger, because only A's private key can sign the message. Even if the message content is known, it cannot forge a signed reply to B, preventing the tampering of the message content.

However, combining the two scenarios, you will find that in the first scenario, although the intercepted message is not leaked, the intercepted public key can be used to encrypt the false instructions and then pass them to A. In the second scenario, although the intercepted message cannot be tampered with, the content of the message can be obtained using public key signature verification, which does not prevent leakage. Therefore, in practical applications, it should be used according to the situation. Encryption and signature can also be used at the same time. For example, A and B have their own set of public and private keys. When A wants to send a message to B, he first uses B's public key pair. The message is encrypted, and then A's private key is used to sign the encrypted message, so that it is neither leaked nor tampered with, and the security of the message is ensured.

Encryption Practice

Blogger, you have been using Bilibili so much, I already know what RSA does. Isn’t it Public key encryption, private key decryption, private key signature, public key signature verification

Practical preparation

1. Create a new springboot project

springboot_api_encryption

2. Introduce maven Yilai

<dependency>
    <groupId>cn.shuibo</groupId>
    <artifactId>rsa-encrypt-body-spring-boot</artifactId>
    <version>1.0.1.RELEASE</version>
</dependency>
Copy after login

3. Add the @EnableSecurity annotation to the startup class Application

@SpringBootApplication
@EnableSecurity
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
Copy after login

4. In application.yml or application.properties Add the RSA public key and private key in

The article on generating the public key and private key will release the generation tool

rsa:
  encrypt:
    open: false # 是否开启加密 true  or  false
    showLog: true # 是否打印加解密log true  or  false
    publicKey: # RSA公钥 软件生成
    privateKey: # RSA私钥 软件生成
Copy after login

5. Encrypt the API method in the Controller

@Encrypt
@GetMapping("/encryption")
public TestBean encryption(){
    TestBean testBean = new TestBean();
    testBean.setName("shuibo.cn");
    testBean.setAge(18);
    return testBean;
}
Copy after login

6. Decrypt the passed encryption parameters

Other java-side programs can use annotations. If it is vue, please use the RSA key to decrypt

@Decrypt
@PostMapping("/decryption")
public String Decryption(@RequestBody TestBean testBean){
    return testBean.toString();
}
Copy after login

real swords and real guns

1.Introducing maven

How SpringBoot implements api encryption

2、启动类添加注解

How SpringBoot implements api encryption

3、YML添加配置密钥

How SpringBoot implements api encryption

4、创建一个实体类

How SpringBoot implements api encryption

5、写一个对外API接口

How SpringBoot implements api encryption

6、启动项目

请求地址: http://localhost:8080/encryption

我们看到返回的数据未加密

How SpringBoot implements api encryption

7、修改

修改open为true 打开加密

rsa:
  encrypt:
    open: true # 是否开启加密 true  or  false
    showLog: true # 是否打印加解密log true  or  false
    publicKey: # RSA公钥 软件生成
    privateKey: # RSA私钥 软件生成
Copy after login

8、再次重启项目

请求地址: http://localhost:8080/encryption

我们看到返回的数据已加密

9、加密日志

How SpringBoot implements api encryption

解密实战

如果是其他springboot项目,跟前面一样。我们这儿就当客户端是springboot项目,其他的请使用RSA解密协议解密!

服务端有私密钥、跟公密钥

前端只需要公密钥就可以

实战准备

在原来的springboot基础上写一份解密方法

1、前端js解密方法

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jsencrypt/3.0.0-rc.1/jsencrypt.js"></script>
Copy after login

2、后台增加解密方法

/**
 * 解密
 * @param user
 * @return
 */
@PostMapping("/decryption")
@Decrypt
@ResponseBody
public String Decryption(@RequestBody User user){
    System.out.println(user.toString());
    return user.toString();
}
Copy after login

3、js方法

#公钥
 var PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAobhGH4WMwMvJRUlTxWrCVIOQtsHijAxPJNvAWAgq80ADpFEWrpbcGB9cKqp6XHRH4k/CVtCUZ7jm9UKwhaeAm18sKtcwe+M8JFNX6FSHpgde0o8C9S/QpcmLxf4iN7nGZ7P3ZTvMdmKUcdRMsVQnsydG2Bj6gRxP2+kexEebTeODbdM7dHlkxAL0RxGWmX/ZOBzsoWZw2gKcC0vxwyIZBGHUdImG2T3nEA+VMfK2Yqv3uSYukmlKP+0mjfhrTtLFDuTV1VER9BfryBMvpQCxLO4pqgZnXPd+SOQcZHZ2OL0wqo5OX1+GPYx7TNxz5Qi76pK//T2mH7s6X/BuyT21HQIDAQAB";

/**
 * 加密方法
 * @returns {PromiseLike<ArrayBuffer>}
 * @constructor
 */
function RSA_encryption(jsonData) {
 var encrypt = new JSEncrypt();
 encrypt.setPublicKey("-----BEGIN PUBLIC KEY-----" + PUBLIC_KEY + "-----END PUBLIC KEY-----");
 var encrypted = encrypt.encrypt(JSON.stringify(jsonData));
 console.log("加密前数据:%o", str);
 console.log("加密后数据:%o", encrypted);
 return encrypted;
}


/**
 * 提交方法
 */
function tijiao() {
 var str = {
 "name":"1223334",
 "password":"asd",
 age:1
 };
 $.ajax({
 url: "/decryption",
 type : "POST",
 contentType: "application/json;charset=utf-8",
 data : RSA_encryption(str) ,
 success : function(data) {
 alert(data);
 }
 })
}
Copy after login

真刀真枪

1、 Controller添加解密方法接口

How SpringBoot implements api encryption

2、前端页面引入js以及方法




    
    Title


加密传后端,后端解密

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jsencrypt/3.0.0-rc.1/jsencrypt.js"></script>
<script>
    var PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAobhGH4WMwMvJRUlTxWrCVIOQtsHijAxPJNvAWAgq80ADpFEWrpbcGB9cKqp6XHRH4k/CVtCUZ7jm9UKwhaeAm18sKtcwe+M8JFNX6FSHpgde0o8C9S/QpcmLxf4iN7nGZ7P3ZTvMdmKUcdRMsVQnsydG2Bj6gRxP2+kexEebTeODbdM7dHlkxAL0RxGWmX/ZOBzsoWZw2gKcC0vxwyIZBGHUdImG2T3nEA+VMfK2Yqv3uSYukmlKP+0mjfhrTtLFDuTV1VER9BfryBMvpQCxLO4pqgZnXPd+SOQcZHZ2OL0wqo5OX1+GPYx7TNxz5Qi76pK//T2mH7s6X/BuyT21HQIDAQAB";

    /**
     * 加密方法
     * @returns {PromiseLike<ArrayBuffer>}
     * @constructor
     */
    function RSA_encryption(jsonData) {
        var encrypt = new JSEncrypt();
        encrypt.setPublicKey("-----BEGIN PUBLIC KEY-----" + PUBLIC_KEY + "-----END PUBLIC KEY-----");
        var encrypted = encrypt.encrypt(JSON.stringify(jsonData));
        console.log("加密前数据:%o", jsonData);
        console.log("加密后数据:%o", encrypted);
        return encrypted;
    }

    /**
     * 提交方法
     */
    function tijiao() {
        var str = {
            "name":"1223334",
            "password":"asd",
            age:1
        };
            $.ajax({
                url: "/decryption",
                type : "POST",
                contentType: "application/json;charset=utf-8",
                data : RSA_encryption(str) ,
                success : function(data) {
                    alert(data);
                }
            })
    }


</script>

Copy after login

3、启动访问

http://localhost:8080

How SpringBoot implements api encryption

4、后台解密日志

How SpringBoot implements api encryption

总结

经过上面的接口加密解密操作。可以看出我们的接口如果没有公钥、或者私钥别人根本无法解密!这样就对API接口起到了很好的保护作用,防止别人抓包!

祝大家:每天学习一点,技术成长飞快

项目坑点

此项目的demo无法访问,难点就在前端如何加密回传到后台解密,此坑我带大家爬出来了!

以下是主意事项:

1、主意ajax的 contentType: “application/json;charset=utf-8”

$.ajax({
    url: "/decryption",
    type : "POST",
    contentType: "application/json;charset=utf-8",
    data : RSA_encryption(str) ,
    success : function(data) {
        alert(data);
    }
})
Copy after login

2、解密方法必须 @RequestBody

@PostMapping("/decryption")
@Decrypt
@ResponseBody
public String Decryption(@RequestBody User user){
    System.out.println(user.toString());
    return user.toString();
}
Copy after login

The above is the detailed content of How SpringBoot implements api encryption. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

How to crawl and process data by calling API interface in PHP project? How to crawl and process data by calling API interface in PHP project? Sep 05, 2023 am 08:41 AM

How to crawl and process data by calling API interface in PHP project? 1. Introduction In PHP projects, we often need to crawl data from other websites and process these data. Many websites provide API interfaces, and we can obtain data by calling these interfaces. This article will introduce how to use PHP to call the API interface to crawl and process data. 2. Obtain the URL and parameters of the API interface. Before starting, we need to obtain the URL of the target API interface and the required parameters.

SpringBoot+Dubbo+Nacos development practical tutorial SpringBoot+Dubbo+Nacos development practical tutorial Aug 15, 2023 pm 04:49 PM

This article will write a detailed example to talk about the actual development of dubbo+nacos+Spring Boot. This article will not cover too much theoretical knowledge, but will write the simplest example to illustrate how dubbo can be integrated with nacos to quickly build a development environment.

How to deal with Laravel API error problems How to deal with Laravel API error problems Mar 06, 2024 pm 05:18 PM

Title: How to deal with Laravel API error problems, specific code examples are needed. When developing Laravel, API errors are often encountered. These errors may come from various reasons such as program code logic errors, database query problems, or external API request failures. How to handle these error reports is a key issue. This article will use specific code examples to demonstrate how to effectively handle Laravel API error reports. 1. Error handling in Laravel

Oracle API Usage Guide: Exploring Data Interface Technology Oracle API Usage Guide: Exploring Data Interface Technology Mar 07, 2024 am 11:12 AM

Oracle is a world-renowned database management system provider, and its API (Application Programming Interface) is a powerful tool that helps developers easily interact and integrate with Oracle databases. In this article, we will delve into the Oracle API usage guide, show readers how to utilize data interface technology during the development process, and provide specific code examples. 1.Oracle

Oracle API integration strategy analysis: achieving seamless communication between systems Oracle API integration strategy analysis: achieving seamless communication between systems Mar 07, 2024 pm 10:09 PM

OracleAPI integration strategy analysis: To achieve seamless communication between systems, specific code examples are required. In today's digital era, internal enterprise systems need to communicate with each other and share data, and OracleAPI is one of the important tools to help achieve seamless communication between systems. This article will start with the basic concepts and principles of OracleAPI, explore API integration strategies, and finally give specific code examples to help readers better understand and apply OracleAPI. 1. Basic Oracle API

React API Call Guide: How to interact and transfer data with the backend API React API Call Guide: How to interact and transfer data with the backend API Sep 26, 2023 am 10:19 AM

ReactAPI Call Guide: How to interact with and transfer data to the backend API Overview: In modern web development, interacting with and transferring data to the backend API is a common need. React, as a popular front-end framework, provides some powerful tools and features to simplify this process. This article will introduce how to use React to call the backend API, including basic GET and POST requests, and provide specific code examples. Install the required dependencies: First, make sure Axi is installed in the project

Save API data to CSV format using Python Save API data to CSV format using Python Aug 31, 2023 pm 09:09 PM

In the world of data-driven applications and analytics, APIs (Application Programming Interfaces) play a vital role in retrieving data from various sources. When working with API data, you often need to store the data in a format that is easy to access and manipulate. One such format is CSV (Comma Separated Values), which allows tabular data to be organized and stored efficiently. This article will explore the process of saving API data to CSV format using the powerful programming language Python. By following the steps outlined in this guide, we will learn how to retrieve data from the API, extract relevant information, and store it in a CSV file for further analysis and processing. Let’s dive into the world of API data processing with Python and unlock the potential of the CSV format

See all articles