Home  >  Article  >  Java  >  How SpringBoot implements api encryption

How SpringBoot implements api encryption

WBOY
WBOYforward
2023-05-15 23:10:05825browse

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:yisu.com. If there is any infringement, please contact admin@php.cn delete