成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

速覽!Spring Boot 3.3 快速實現 API 加密的最佳實踐

開發 前端
通過本文,我們了解了 RSA 加密的基本原理,并結合 SpringBoot3.3 快速實現了 API 數據的加解密。在實際生產環境中,RSA 加密能夠有效保護敏感信息的安全傳輸。

景(如支付、登錄認證等),API 的數據傳輸面臨著信息泄露的風險。因此,在這些場景下,數據加密顯得尤為重要。為了提高安全性,RSA 加密算法作為非對稱加密的一種典型實現,廣泛應用于 API 加密場景中。本文將深入介紹 RSA 加密的基本原理,并結合 SpringBoot3.3,使用 rsa-encrypt-body-spring-boot 快速實現 API 數據加解密。

RSA 加密算法簡介

RSA 加密是一種非對稱加密算法,具有公鑰和私鑰的密鑰對。公鑰用于加密數據,而私鑰用于解密。加密和解密的具體流程如下:

  1. 生成密鑰對:RSA 通過數學算法生成一對密鑰:公鑰(Public Key)和私鑰(Private Key)。
  2. 加密數據:前端(或客戶端)使用服務器提供的公鑰將敏感數據進行加密。由于加密過程不可逆,只有擁有私鑰的服務器才能解密這些數據。
  3. 傳輸加密數據:客戶端將加密后的數據通過 API 發送至后端服務器。
  4. 解密數據:

服務器端收到加密數據后,使用 RSA 私鑰解密得到原始數據。

解密后的數據再由服務器進行進一步的業務處理。

RSA 的優勢在于公鑰可以公開分發,不需要像對稱加密算法一樣保證密鑰的安全性。同時,只有服務器端持有私鑰,能夠有效避免數據在傳輸過程中被竊取和篡改。

運行效果:

圖片圖片

若想獲取項目完整代碼以及其他文章的項目源碼,且在代碼編寫時遇到問題需要咨詢交流,歡迎加入下方的知識星球。

接下來,我們將結合 SpringBoot 實現基于 RSA 加密的 API 數據加密傳輸。

項目依賴配置

在項目中首先需要配置 pom.xml 文件以引入相關依賴:

pom.xml 配置*

<?xml versinotallow="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.3.4</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.icoderoad</groupId>
	<artifactId>rsa-encrypt</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>rsa-encrypt</name>
	<description>Demo project for Spring Boot</description>
	
	<properties>
		<java.version>17</java.version>
	</properties>
	<dependencies>
		
		<!-- RSA 加密依賴 -->
	    <dependency>
	        <groupId>cn.shuibo</groupId>
	        <artifactId>rsa-encrypt-body-spring-boot</artifactId>
	        <version>1.0.1.RELEASE</version>
	    </dependency>
	
	    <!-- Lombok 依賴 -->
	    <dependency>
	        <groupId>org.projectlombok</groupId>
	        <artifactId>lombok</artifactId>
	        <scope>provided</scope>
	    </dependency>
	
	    <!-- Thymeleaf 依賴 -->
	    <dependency>
	        <groupId>org.springframework.boot</groupId>
	        <artifactId>spring-boot-starter-thymeleaf</artifactId>
	    </dependency>
	
	    <!-- Web 依賴 -->
	    <dependency>
	        <groupId>org.springframework.boot</groupId>
	        <artifactId>spring-boot-starter-web</artifactId>
	    </dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

application.yml 配置

在 application.yml 中配置 RSA 加密的公鑰和私鑰,保證后端可以正常解密前端的加密數據。

rsa:
  encrypt:
    open: true # 是否開啟加密 true or false
    showLog: true # 是否打印加解密log true or false
    timestampCheck: true # 是否開啟時間戳檢查 true or false
    publicKey: |-
      MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArw2n5D...
    privateKey: |-
      MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKcw...

** 使用 OpenSSL 生成 RSA 密鑰對**

  1. 生成 RSA 私鑰(private key): 運行以下命令生成一個 2048 位的私鑰:
openssl genpkey -algorithm RSA -out private_key.pem -pkeyopt rsa_keygen_bits:2048

這會生成一個 private_key.pem 文件,文件中包含 -----BEGIN PRIVATE KEY----- 和 -----END PRIVATE KEY-----。

從私鑰生成公鑰(public key): 使用以下命令生成公鑰:

openssl rsa -pubout -in private_key.pem -out public_key.pem

這會生成一個 public_key.pem 文件,包含公鑰內容。

移除頭尾標識符,獲得純 Base64 內容: 打開 private_key.pem 和 public_key.pem 文件,手動移除頭尾標識符(如 -----BEGIN PRIVATE KEY----- 和 -----END PRIVATE KEY-----),并將中間的內容保存下來。這個內容是純粹的 Base64 編碼后的密鑰。私鑰的格式看起來會像這樣(去掉換行符后):

MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC1...

替換 application.yml 中的密鑰: 將得到的純 Base64 內容替換到你的 application.yml 文件中:

rsa:
  encrypt:
    publicKey: |
      MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArw2n5D...
    privateKey: |
      MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKcw...

啟動類

注意:啟動類 RsaEncryptApplication 中添加@EnableSecurity注解

package com.icoderoad.rsa.encrypt;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import cn.shuibo.annotation.EnableSecurity;

@EnableSecurity
@SpringBootApplication
public class RsaEncryptApplication {

	public static void main(String[] args) {
		SpringApplication.run(RsaEncryptApplication.class, args);
	}

}

配置讀取類

通過 @ConfigurationProperties 來讀取加密相關的配置信息。我們使用 Lombok 的注解來簡化代碼,實現 Getter 和 Setter。

package com.icoderoad.rsa.encrypt.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import lombok.Data;

@Data
@Component
@ConfigurationProperties(prefix = "encrypt.rsa")
public class RsaProperties {
    private String publicKey;
    private String privateKey;
}

后端代碼實現

實體類

package com.icoderoad.rsa.encrypt.entity;

import lombok.Data;

@Data
public class User {

	private String name;
	private String message;
}

Controller 需要接收前端發送的加密 JSON 數據,并通過 RSA 進行解密處理。這里修改了前端傳輸的數據格式,并使用 @RequestBody 解析 JSON 格式的數據。

package com.icoderoad.rsa.encrypt.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.icoderoad.rsa.encrypt.config.RsaProperties;
import com.icoderoad.rsa.encrypt.entity.User;

import cn.shuibo.annotation.Decrypt;

@RestController
@RequestMapping("/api/demo")
public class DemoController {

	@Autowired
	private RsaProperties rsaProperties;

	@GetMapping("/publicKey")
	public String getPublicKey() {
		// 返回配置中的公鑰
		return rsaProperties.getPublicKey();
	}

	@Decrypt
	@PostMapping("/encryptData")
	public String receiveEncryptedData(@RequestBody User user) {
		// 獲取解密后的數據
		String name = user.getName();
		String message = user.getMessage();

		return "接收到的加密數據解密數據為: Name=" + name + ", Message=" + message;
	}
}

前端代碼實現

我們通過 Thymeleaf 模板引擎構建頁面,并使用 jQuery 和 Bootstrap 來處理前端加密邏輯。

在 src/main/resources/templates 目錄下創建 index.html 文件:

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>API 加密測試</title>
    <!-- 引入 Bootstrap 和 jQuery 的 CDN -->
    <link  rel="stylesheet">
    <script src="https://cdn.bootcss.com/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/bootstrap/4.5.0/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="container mt-5">
    <h1 class="text-center mb-4">加密 API 測試</h1>
    <form id="encryptForm" class="shadow p-4 rounded bg-light">
        <div class="form-group">
            <label for="name">姓名</label>
            <input type="text" class="form-control" id="name" placeholder="輸入姓名" required>
        </div>
        <div class="form-group">
            <label for="message">信息</label>
            <input type="text" class="form-control" id="message" placeholder="輸入信息" required>
        </div>
        <button type="button" class="btn btn-primary btn-block">提交加密數據</button>
    </form>
    <div id="result" class="mt-4"></div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jsencrypt/3.0.0/jsencrypt.min.js"></script>
<script>
$(document).ready(function() {
    // 獲取公鑰
    $.get("/api/demo/publicKey", function(publicKey) {
        const encrypt = new JSEncrypt();
        
        encrypt.setPublicKey('-----BEGIN PUBLIC KEY-----' + publicKey + '-----END PUBLIC KEY-----');

        $("#encryptForm button").click(function(event) {
            event.preventDefault(); // 防止按鈕默認提交

            // 獲取用戶輸入
            const name = $("#name").val();
            const message = $("#message").val();
            var user = {"name": name, "message": message};
            // 加密數據
            const encryptedData = encrypt.encrypt(JSON.stringify(user));

            // 使用 AJAX 提交加密數據
            $.ajax({
                url: "/api/demo/encryptData", // API 端點
                method: "POST",
                contentType: "application/json",
                data: encryptedData,
                success: function(response) {
                    console.log("成功:", response);
                    $("#result").html(`<div class="alert alert-success">成功: ${response}</div>`); // 顯示返回的解密結果
                },
                error: function(error) {
                    console.error("錯誤:", error);
                    $("#result").html(`<div class="alert alert-danger">提交失敗,請重試!</div>`);
                }
            });
        });
    });
});
</script>
</body>
</html>

前端加密邏輯說明

在上述代碼中,前端通過 btoa 模擬了數據加密,實際生產環境中應使用成熟的前端 RSA 加密庫,例如 jsencrypt 來完成 RSA 加密操作。頁面通過 jQuery 提交加密后的數據至后端。

運行項目

  1. 啟動 SpringBoot 項目后,訪問 http://localhost:8080。
  2. 輸入姓名和信息,點擊“提交加密數據”,頁面將通過 jQuery 發起 POST 請求,并傳輸加密后的數據。
  3. 后端接收到加密數據后,通過 RSA 解密工具解密,并返回解密結果。

結語

通過本文,我們了解了 RSA 加密的基本原理,并結合 SpringBoot3.3 快速實現了 API 數據的加解密。在實際生產環境中,RSA 加密能夠有效保護敏感信息的安全傳輸。然而,RSA 也存在一些限制,如加密數據長度受限、性能開銷較大等問題。因此,對于大規模數據傳輸,可以結合對稱加密和非對稱加密(如 RSA + AES)來提高系統的安全性和效率。

對于 API 安全性的提升,除了加密傳輸,其他安全措施(如接口簽名、白名單 IP 過濾等)也應配合使用,全面提高系統的防護能力。

責任編輯:武曉燕 來源: 路條編程
相關推薦

2024-10-11 11:46:40

2024-05-13 13:13:13

APISpring程序

2018-04-09 14:26:06

Go語法實踐

2025-05-06 07:04:23

MyBatis技巧框架

2016-12-27 08:49:55

API設計策略

2024-03-08 10:50:44

Spring技術應用程序

2024-11-06 11:33:09

2013-06-13 09:21:31

RESTful APIRESTfulAPI

2024-10-30 08:05:01

Spring參數電子簽章

2024-10-08 09:27:04

SpringRESTfulAPI

2017-03-13 14:09:19

RESTful API實踐

2024-09-05 09:35:58

CGLIBSpring動態代理

2023-11-07 07:08:57

2018-12-04 09:00:00

API安全性令牌

2022-06-04 12:25:10

解密加密過濾器

2021-03-09 13:18:53

加密解密參數

2025-01-17 09:11:51

2024-09-26 08:48:42

SpringAPITogglz

2014-07-29 09:25:39

加密密鑰管理云加密

2023-04-14 12:23:15

點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 日本综合在线观看 | 久久精品色欧美aⅴ一区二区 | 欧美午夜精品久久久久久浪潮 | 国产日韩久久 | 久久成人国产精品 | 伊人久久精品 | av国产精品 | 日韩欧美三区 | 国产精品免费在线 | 欧美精品欧美精品系列 | 国产精品7777777 | 亚洲高清在线 | 四虎影院在线观看av | 午夜欧美一区二区三区在线播放 | 欧美伊人影院 | 91看片免费 | 日韩精品人成在线播放 | 欧美视频免费在线 | 亚洲精品乱码久久久久久9色 | 99精品99久久久久久宅男 | 九九热九九 | 午夜精品久久久久久久久久久久久 | 91原创视频在线观看 | 亚洲视频一区在线观看 | 久久午夜视频 | 日本特黄a级高清免费大片 国产精品久久性 | 亚洲精品视频在线观看视频 | 国产三级一区二区 | 久久久久综合 | 欧美一区二区三区,视频 | 北条麻妃视频在线观看 | 欧美一区免费 | 亚洲精品日韩一区二区电影 | 国产一区二区三区免费观看视频 | 国产精品免费av | 亚洲国产一区二区三区, | 天天欧美| 日韩中文字幕在线观看 | 午夜av一区二区 | 国产激情在线 | 九九久久国产精品 |