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

速覽!Spring Boot 3.3 快速實(shí)現(xiàn) API 加密的最佳實(shí)踐

開發(fā) 前端
通過本文,我們了解了 RSA 加密的基本原理,并結(jié)合 SpringBoot3.3 快速實(shí)現(xiàn)了 API 數(shù)據(jù)的加解密。在實(shí)際生產(chǎn)環(huán)境中,RSA 加密能夠有效保護(hù)敏感信息的安全傳輸。

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

RSA 加密算法簡介

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

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

服務(wù)器端收到加密數(shù)據(jù)后,使用 RSA 私鑰解密得到原始數(shù)據(jù)。

解密后的數(shù)據(jù)再由服務(wù)器進(jìn)行進(jìn)一步的業(yè)務(wù)處理。

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

運(yùn)行效果:

圖片圖片

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

接下來,我們將結(jié)合 SpringBoot 實(shí)現(xiàn)基于 RSA 加密的 API 數(shù)據(jù)加密傳輸。

項(xiàng)目依賴配置

在項(xiàng)目中首先需要配置 pom.xml 文件以引入相關(guān)依賴:

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 加密的公鑰和私鑰,保證后端可以正常解密前端的加密數(shù)據(jù)。

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

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

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

這會(huì)生成一個(gè) private_key.pem 文件,文件中包含 -----BEGIN PRIVATE KEY----- 和 -----END PRIVATE KEY-----。

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

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

這會(huì)生成一個(gè) public_key.pem 文件,包含公鑰內(nèi)容。

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

MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC1...

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

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

啟動(dòng)類

注意:啟動(dòng)類 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 來讀取加密相關(guān)的配置信息。我們使用 Lombok 的注解來簡化代碼,實(shí)現(xiàn) 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;
}

后端代碼實(shí)現(xiàn)

實(shí)體類

package com.icoderoad.rsa.encrypt.entity;

import lombok.Data;

@Data
public class User {

	private String name;
	private String message;
}

Controller 需要接收前端發(fā)送的加密 JSON 數(shù)據(jù),并通過 RSA 進(jìn)行解密處理。這里修改了前端傳輸?shù)臄?shù)據(jù)格式,并使用 @RequestBody 解析 JSON 格式的數(shù)據(jù)。

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) {
		// 獲取解密后的數(shù)據(jù)
		String name = user.getName();
		String message = user.getMessage();

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

前端代碼實(shí)現(xiàn)

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

在 src/main/resources/templates 目錄下創(chuàng)建 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">提交加密數(shù)據(jù)</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(); // 防止按鈕默認(rèn)提交

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

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

前端加密邏輯說明

在上述代碼中,前端通過 btoa 模擬了數(shù)據(jù)加密,實(shí)際生產(chǎn)環(huán)境中應(yīng)使用成熟的前端 RSA 加密庫,例如 jsencrypt 來完成 RSA 加密操作。頁面通過 jQuery 提交加密后的數(shù)據(jù)至后端。

運(yùn)行項(xiàng)目

  1. 啟動(dòng) SpringBoot 項(xiàng)目后,訪問 http://localhost:8080。
  2. 輸入姓名和信息,點(diǎn)擊“提交加密數(shù)據(jù)”,頁面將通過 jQuery 發(fā)起 POST 請求,并傳輸加密后的數(shù)據(jù)。
  3. 后端接收到加密數(shù)據(jù)后,通過 RSA 解密工具解密,并返回解密結(jié)果。

結(jié)語

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

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

責(zé)任編輯:武曉燕 來源: 路條編程
相關(guān)推薦

2024-10-11 11:46:40

2024-05-13 13:13:13

APISpring程序

2018-04-09 14:26:06

Go語法實(shí)踐

2025-05-06 07:04:23

MyBatis技巧框架

2016-12-27 08:49:55

API設(shè)計(jì)策略

2024-03-08 10:50:44

Spring技術(shù)應(yīng)用程序

2013-06-13 09:21:31

RESTful APIRESTfulAPI

2024-11-06 11:33:09

2024-10-30 08:05:01

Spring參數(shù)電子簽章

2024-10-08 09:27:04

SpringRESTfulAPI

2017-03-13 14:09:19

RESTful API實(shí)踐

2024-09-05 09:35:58

CGLIBSpring動(dòng)態(tài)代理

2018-12-04 09:00:00

API安全性令牌

2023-11-07 07:08:57

2022-06-04 12:25:10

解密加密過濾器

2021-03-09 13:18:53

加密解密參數(shù)

2025-01-17 09:11:51

2014-07-29 09:25:39

加密密鑰管理云加密

2024-09-26 08:48:42

SpringAPITogglz

2023-04-14 12:23:15

點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號

主站蜘蛛池模板: 久久久国产一区 | 青春草在线 | 99热精品久久 | 久久久精品一区 | 中文字幕 国产 | 精品日韩| 久久久久网站 | av中文字幕网站 | 99久久99| 免费三级网 | 中国大陆高清aⅴ毛片 | 欧美亚洲另类在线 | 精品日韩一区二区 | 久久99蜜桃综合影院免费观看 | 亚洲久草视频 | 欧美精品久久久久久久久老牛影院 | 中文在线一区 | 亚洲人成在线播放 | 国产91久久久久久久免费 | 欧美精品一区三区 | 成人av播放 | 成人免费福利视频 | 国产精品国产精品国产专区不卡 | 欧美中文字幕在线观看 | 日本中文字幕在线视频 | 国产精品欧美精品 | 一本在线 | 欧美极品在线 | 91xxx在线观看| 国产精品久久亚洲 | 国产真实精品久久二三区 | 九九综合| 在线观看视频91 | 精品国产不卡一区二区三区 | 国产第二页 | 男女免费观看在线爽爽爽视频 | 成人免费视频网站在线看 | 欧美成人a∨高清免费观看 91伊人 | 日韩一区二区在线观看视频 | 欧美精品一区二区三区在线播放 | 国产伦精品一区二区三区四区视频 |