search
HomeJavajavaTutorialHow SpringBoot implements api encryption

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>

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);
    }
}

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私钥 软件生成

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;
}

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();
}

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私钥 软件生成

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>

2、后台增加解密方法

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

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);
 }
 })
}

真刀真枪

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>

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);
    }
})

2、解密方法必须 @RequestBody

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

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
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
What are the advantages of using bytecode over native code for platform independence?What are the advantages of using bytecode over native code for platform independence?Apr 30, 2025 am 12:24 AM

Bytecodeachievesplatformindependencebybeingexecutedbyavirtualmachine(VM),allowingcodetorunonanyplatformwiththeappropriateVM.Forexample,JavabytecodecanrunonanydevicewithaJVM,enabling"writeonce,runanywhere"functionality.Whilebytecodeoffersenh

Is Java truly 100% platform-independent? Why or why not?Is Java truly 100% platform-independent? Why or why not?Apr 30, 2025 am 12:18 AM

Java cannot achieve 100% platform independence, but its platform independence is implemented through JVM and bytecode to ensure that the code runs on different platforms. Specific implementations include: 1. Compilation into bytecode; 2. Interpretation and execution of JVM; 3. Consistency of the standard library. However, JVM implementation differences, operating system and hardware differences, and compatibility of third-party libraries may affect its platform independence.

How does Java's platform independence support code maintainability?How does Java's platform independence support code maintainability?Apr 30, 2025 am 12:15 AM

Java realizes platform independence through "write once, run everywhere" and improves code maintainability: 1. High code reuse and reduces duplicate development; 2. Low maintenance cost, only one modification is required; 3. High team collaboration efficiency is high, convenient for knowledge sharing.

What are the challenges in creating a JVM for a new platform?What are the challenges in creating a JVM for a new platform?Apr 30, 2025 am 12:15 AM

The main challenges facing creating a JVM on a new platform include hardware compatibility, operating system compatibility, and performance optimization. 1. Hardware compatibility: It is necessary to ensure that the JVM can correctly use the processor instruction set of the new platform, such as RISC-V. 2. Operating system compatibility: The JVM needs to correctly call the system API of the new platform, such as Linux. 3. Performance optimization: Performance testing and tuning are required, and the garbage collection strategy is adjusted to adapt to the memory characteristics of the new platform.

How does the JavaFX library attempt to address platform inconsistencies in GUI development?How does the JavaFX library attempt to address platform inconsistencies in GUI development?Apr 30, 2025 am 12:01 AM

JavaFXeffectivelyaddressesplatforminconsistenciesinGUIdevelopmentbyusingaplatform-agnosticscenegraphandCSSstyling.1)Itabstractsplatformspecificsthroughascenegraph,ensuringconsistentrenderingacrossWindows,macOS,andLinux.2)CSSstylingallowsforfine-tunin

Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Apr 29, 2025 am 12:23 AM

JVM works by converting Java code into machine code and managing resources. 1) Class loading: Load the .class file into memory. 2) Runtime data area: manage memory area. 3) Execution engine: interpret or compile execution bytecode. 4) Local method interface: interact with the operating system through JNI.

Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Apr 29, 2025 am 12:21 AM

JVM enables Java to run across platforms. 1) JVM loads, validates and executes bytecode. 2) JVM's work includes class loading, bytecode verification, interpretation execution and memory management. 3) JVM supports advanced features such as dynamic class loading and reflection.

What steps would you take to ensure a Java application runs correctly on different operating systems?What steps would you take to ensure a Java application runs correctly on different operating systems?Apr 29, 2025 am 12:11 AM

Java applications can run on different operating systems through the following steps: 1) Use File or Paths class to process file paths; 2) Set and obtain environment variables through System.getenv(); 3) Use Maven or Gradle to manage dependencies and test. Java's cross-platform capabilities rely on the JVM's abstraction layer, but still require manual handling of certain operating system-specific features.

See all articles

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!