在Ubuntu系統中,Swagger的數據加密主要圍繞傳輸層加密、接口身份核驗、數據完整性校驗及敏感信息保護等維度展開,以下是具體實施步驟:
HTTPS是Swagger數據傳輸的基礎加密手段,通過SSL/TLS協議對客戶端與服務器之間的通信進行加密,防止數據被竊聽或篡改。
/etc/ssl/certs/
目錄);server {
listen 443 ssl;
server_name yourdomain.com;
ssl_certificate /etc/ssl/certs/your_cert.pem;
ssl_certificate_key /etc/ssl/certs/your_key.key;
# 其他配置...
}
配置完成后,強制Swagger UI通過HTTPS訪問(如將HTTP請求重定向至HTTPS)。通過RSA非對稱加密實現API接口的身份驗證,確保只有持有合法私鑰的客戶端能訪問敏感接口。
public_key.pem
、私鑰private_key.pem
),公鑰公開,私鑰嚴格保管;securityDefinitions
配置,強制接口使用RSA加密:securityDefinitions:
RSA:
type: apiKey
name: Authorization
in: header
description: RSA加密的授權令牌
使用哈希算法生成數據的唯一“指紋”,驗證數據在傳輸過程中是否被篡改。
param1=value1¶m2=value2
)與時間戳、隨機數拼接,計算SHA-256哈希值;X-Data-Hash
)發送給服務端;import java.security.MessageDigest;
public class HashUtil {
public static String sha256(String input) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(input.getBytes("UTF-8"));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
hexString.append(String.format("%02x", b));
}
return hexString.toString();
}
}
這種方式能有效防止數據被篡改,確保傳輸內容的完整性。對于Swagger文檔中涉及的敏感信息(如數據庫連接字符串、API密鑰、用戶隱私數據),使用AES對稱加密算法進行加密存儲和傳輸。
/etc/secret/
目錄,權限設置為600
);application.yml
);import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AESUtil {
public static String encrypt(String plainText, String key, String iv) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes("UTF-8"));
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
byte[] encrypted = cipher.doFinal(plainText.getBytes("UTF-8"));
return Base64.getEncoder().encodeToString(encrypted);
}
}
通過這種方式,即使Swagger文檔泄露,敏感信息也無法被直接獲取。springfox.documentation.swagger.v2.path
)將Swagger UI路徑設置為復雜路徑(如/api-docs/internal
),避免直接暴露在公網;springfox.documentation.enabled=false
),僅在開發或測試環境中啟用;以上方法需結合實際場景選擇使用,例如傳輸層加密(HTTPS)是基礎,接口身份核驗(RSA)和數據完整性校驗(SHA-256)適用于敏感接口,敏感信息加密(AES)則針對存儲和傳輸中的隱私數據。通過多層防護,可有效提升Ubuntu環境下Swagger的數據安全性。