ocelot网关增加请求自动加解密
方案概述
面向 API 网关的 AES + RSA 混合加解密 方案,包含 NuGet 依赖、Ocelot 注册与配置、CORS、后端中间件,以及可直接运行的 HTML Demo。
另:CORS实际并未起到作用,可以移除。
加密模型
采用 AES-256 加密业务数据 + RSA 加密 AES 密钥 的混合加密:
| 环节 | 算法 | 说明 |
|---|---|---|
| 请求体 / 响应体 | AES-256-CBC / PKCS7 | 固定 16 字节全 0 IV(与后端 CryptoHelper 对齐) |
| 请求 Get 参数 | AES-256-CBC / PKCS7 | 前端将整段 query 串 AES 加密后放入参数 q(即 ?q=密文),后端解密后还原为明文参数 |
| AES 密钥 | RSA PKCS#1 v1.5 | 请求用 公钥 加密 AES 密钥;响应用 公钥 加密随机 AES 密钥,前端用 私钥 解密 |
| 密钥编码 | Base64 | AES 密钥为 32 字节随机数的 Base64;密文亦为 Base64 |
GET 与 POST 复用同一把 AES 密钥(由
X-Encrypted-Key携带):POST 用它加密 Body,GET 用它加密q参数。GET 请求无 Body,后端会跳过 Body 解密,仅还原 query。
交互流程
┌──────────┐ ┌──────────────┐
│ 浏览器 │ │ 网关 Gateway │
└────┬─────┘ └──────┬───────┘
│ 生成随机 AES-256 密钥 (Base64) │
│ AES 加密请求体 -> cipherText(Base64) │
│ RSA 公钥加密 AES 密钥 -> encKey(Base64) │
│ ── POST body=cipherText ───────────────────────────▶ │
│ Header: X-Encrypted: true │ RequestDecryptMiddleware
│ Header: X-Encrypted-Key: encKey │ ├ RSA 私钥解出 AES 密钥
│ │ ├ AES 解密请求体(Body 为空则跳过)
│ │ └ AES 解密 q 参数并还原明文 query
│ │
│ ◀── body=respCipherText ──────────────────────────── │ ResponseEncryptMiddleware
│ Header: X-Encrypted: true │ ├ 随机 AES 密钥
│ Header: X-Encrypted-Key: respEncKey │ ├ AES 加密响应体
│ RSA 私钥解出 respKey │ └ RSA 公钥加密 AES 密钥
│ AES 解密得到响应明文 │
GET 请求(参数加密)流程:
┌──────────┐ ┌──────────────┐
│ 浏览器 │ │ 网关 Gateway │
└────┬─────┘ └──────┬───────┘
│ 生成随机 AES-256 密钥 (Base64) │
│ AES 加密整段 query -> qCipher(Base64) │
│ RSA 公钥加密 AES 密钥 -> encKey(Base64) │
│ ── GET /api/xxx/yyy?q=qCipher ─────────────────────▶ │ RequestDecryptMiddleware
│ Header: X-Encrypted: true │ ├ RSA 私钥解出 AES 密钥
│ Header: X-Encrypted-Key: encKey │ ├ Body 为空,跳过 Body 解密
│ │ └ AES 解密 q -> 还原 QueryString
│ ◀── body=respCipherText ──────────────────────────── │ ResponseEncryptMiddleware
│ Header: X-Encrypted: true │ ├ 随机 AES 密钥
│ Header: X-Encrypted-Key: respEncKey │ ├ AES 加密响应体
│ RSA 私钥解出 respKey,AES 解密得到响应明文 │ └ RSA 公钥加密 AES 密钥
请求/响应头约定
| Header | 方向 | 值 | 说明 |
|---|---|---|---|
X-Encrypted |
请求 & 响应 | true / false |
标记数据是否加密 |
X-Encrypted-Key |
请求 & 响应 | Base64 | RSA 加密后的 AES 密钥 |
Header 名称可通过配置
Crypto:EncryptedRequestHeader/EncryptedResponseHeader/EncryptedKeyHeader修改。
请求参数约定(GET)
| 参数 | 方向 | 值 | 说明 |
|---|---|---|---|
q |
请求 | Base64 | AES 加密后的整段 query 串(如 PageIndex=1&PageSize=20 加密后的密文) |
参数名固定为
q(CryptoOptions.EncryptedQueryParam常量)。前端发送GET /api/xxx/yyy?q=密文,后端解密后还原为标准 query(PageIndex=1&PageSize=20),后续业务按普通参数取值即可。
NuGet 依赖
项目 .csproj 需要以下包(加解密本身使用 .NET BCL 的 System.Security.Cryptography,无需额外包):
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<LangVersion>12.0</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Ocelot" Version="24.0.0" />
<PackageReference Include="Ocelot.Provider.Consul" Version="24.0.0" />
</ItemGroup>
</Project>
说明:
- 加解密:仅用
System.Security.Cryptography(Aes、RSA),无需引入第三方加密库。- CORS:使用 ASP.NET Core 内置
Microsoft.AspNetCore.Cors(框架自带)。- Ocelot:网关路由必需,
Ocelot.Provider.Consul用于服务发现。
配置项
appsettings.json
{
"Crypto": {
"Enable": true,
"EnableRequestDecrypt": true,
"EnableResponseEncrypt": true,
"RsaPublicKey": "-----BEGIN PUBLIC KEY-----...-----END PUBLIC KEY-----",
"RsaPrivateKey": "-----BEGIN PRIVATE KEY-----...-----END PRIVATE KEY-----",
"EncryptedRequestHeader": "X-Encrypted",
"EncryptedResponseHeader": "X-Encrypted",
"EncryptedKeyHeader": "X-Encrypted-Key",
"AesMode": "CBC"
}
}
⚠️ 重要:
RsaPrivateKey的 PEM 头必须与内容格式一致。
若私钥内容为 PKCS#8,头必须是-----BEGIN PRIVATE KEY-----(不是-----BEGIN RSA PRIVATE KEY-----),否则 .NETImportFromPem会抛ASN1 corrupted data。
CryptoOptions(配置绑定类)
namespace Gateway.Middleware.Crypto
{
/// <summary>
/// 加密配置项
/// </summary>
public class CryptoOptions
{
public bool Enable { get; set; } = false;
/// <summary>
/// 是否启用请求解密
/// </summary>
public bool EnableRequestDecrypt { get; set; } = false;
/// <summary>
/// 是否启用响应加密
/// </summary>
public bool EnableResponseEncrypt { get; set; } = false;
/// <summary>
/// RSA 私钥(用于解密 AES 密钥)
/// </summary>
public string RsaPrivateKey { get; set; } = string.Empty;
/// <summary>
/// RSA 公钥(用于加密 AES 密钥返回给前端)
/// </summary>
public string RsaPublicKey { get; set; } = string.Empty;
/// <summary>
/// 请求中表示数据已加密的 Header 名称
/// </summary>
public const string EncryptedRequestHeader = "X-Encrypted";
/// <summary>
/// 响应中表示数据已加密的 Header 名称
/// </summary>
public const string EncryptedResponseHeader = "X-Encrypted";
/// <summary>
/// 请求中传递 RSA 加密后的 AES 密钥的 Header 名称
/// </summary>
public const string EncryptedKeyHeader = "X-Encrypted-Key";
/// <summary>
/// Get 参数中承载加密数据的参数名(前端将整个 query 加密后放入该参数)
/// </summary>
public const string EncryptedQueryParam = "q";
/// <summary>
/// AES 模式(默认 CBC)
/// </summary>
public AesMode AesMode { get; set; } = AesMode.CBC;
}
/// <summary>
/// AES 模式
/// </summary>
public enum AesMode
{
/// <summary>CBC 模式</summary>
CBC,
/// <summary>ECB 模式</summary>
ECB,
/// <summary>GCM 模式</summary>
GCM
}
}
加解密核心帮助类
Middleware/Crypto/CryptoHelper.cs:
using System;
using System.Security.Cryptography;
using System.Text;
namespace Gateway.Middleware.Crypto
{
/// <summary>
/// AES+RSA 混合加密帮助类
/// </summary>
public static class CryptoHelper
{
private static readonly byte[] _aesIvFixed = new byte[16]; // 固定 IV,ECB 模式不用
#region AES
/// <summary>
/// 生成 AES 密钥(32字节 = 256位)
/// </summary>
public static string GenerateAesKey()
{
var bytes = new byte[32];
using var rng = RandomNumberGenerator.Create();
rng.GetBytes(bytes);
return Convert.ToBase64String(bytes);
}
/// <summary>
/// AES 加密
/// </summary>
/// <param name="plainText">明文</param>
/// <param name="key">Base64 编码的 AES 密钥</param>
/// <param name="mode">加密模式</param>
/// <returns>Base64 编码的密文</returns>
public static string AesEncrypt(string plainText, string key, AesMode mode = AesMode.CBC)
{
if (string.IsNullOrEmpty(plainText)) return plainText;
using var aes = Aes.Create();
aes.Key = Convert.FromBase64String(key);
aes.Padding = PaddingMode.PKCS7;
switch (mode)
{
case AesMode.ECB:
aes.Mode = CipherMode.ECB;
break;
case AesMode.GCM:
return AesEncryptGcm(plainText, aes.Key);
case AesMode.CBC:
default:
aes.Mode = CipherMode.CBC;
aes.IV = _aesIvFixed;
break;
}
using var encryptor = aes.CreateEncryptor();
var plainBytes = Encoding.UTF8.GetBytes(plainText);
var encrypted = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
return Convert.ToBase64String(encrypted);
}
/// <summary>
/// AES 解密
/// </summary>
/// <param name="cipherText">Base64 编码的密文</param>
/// <param name="key">Base64 编码的 AES 密钥</param>
/// <param name="mode">加密模式</param>
/// <returns>明文</returns>
public static string AesDecrypt(string cipherText, string key, AesMode mode = AesMode.CBC)
{
if (string.IsNullOrEmpty(cipherText)) return cipherText;
using var aes = Aes.Create();
aes.Key = Convert.FromBase64String(key);
aes.Padding = PaddingMode.PKCS7;
switch (mode)
{
case AesMode.ECB:
aes.Mode = CipherMode.ECB;
break;
case AesMode.GCM:
return AesDecryptGcm(cipherText, aes.Key);
case AesMode.CBC:
default:
aes.Mode = CipherMode.CBC;
aes.IV = _aesIvFixed;
break;
}
using var decryptor = aes.CreateDecryptor();
var cipherBytes = Convert.FromBase64String(cipherText);
var decrypted = decryptor.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);
return Encoding.UTF8.GetString(decrypted);
}
// AesEncryptGcm / AesDecryptGcm:格式 Nonce + Cipher + Tag 拼接后 Base64(略)
private static string AesEncryptGcm(string plainText, byte[] key) { /* 见源码 */ throw new NotImplementedException(); }
private static string AesDecryptGcm(string cipherText, byte[] key) { /* 见源码 */ throw new NotImplementedException(); }
#endregion
#region RSA
/// <summary>
/// RSA 加密(公钥加密 AES 密钥)
/// </summary>
/// <param name="plainText">明文(AES 密钥 Base64)</param>
/// <param name="publicKeyPem">PEM 格式 RSA 公钥</param>
/// <returns>Base64 编码的密文</returns>
public static string RsaEncrypt(string plainText, string publicKeyPem)
{
using var rsa = RSA.Create();
rsa.ImportFromPem(publicKeyPem);
var plainBytes = Encoding.UTF8.GetBytes(plainText);
var encrypted = rsa.Encrypt(plainBytes, RSAEncryptionPadding.Pkcs1);
return Convert.ToBase64String(encrypted);
}
/// <summary>
/// RSA 解密(私钥解密 AES 密钥)
/// </summary>
/// <param name="cipherText">Base64 编码的密文</param>
/// <param name="privateKeyPem">PEM 格式 RSA 私钥</param>
/// <returns>明文(AES 密钥 Base64)</returns>
public static string RsaDecrypt(string cipherText, string privateKeyPem)
{
using var rsa = RSA.Create();
rsa.ImportFromPem(privateKeyPem);
var cipherBytes = Convert.FromBase64String(cipherText);
var decrypted = rsa.Decrypt(cipherBytes, RSAEncryptionPadding.Pkcs1);
return Encoding.UTF8.GetString(decrypted);
}
#endregion
}
}
中间件
请求解密中间件
Middleware/Crypto/RequestDecryptMiddleware.cs:
using System;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace Gateway.Middleware.Crypto
{
/// <summary>
/// 请求解密中间件
/// 前端使用 RSA 公钥加密 AES 密钥后放入 Header,
/// 用 AES 加密请求体(或 GET 的 q 参数)后发送;本中间件自动解密还原。
/// </summary>
public class RequestDecryptMiddleware
{
private readonly RequestDelegate _next;
private readonly CryptoOptions _options;
public RequestDecryptMiddleware(RequestDelegate next, IOptions<CryptoOptions> options)
{
_next = next;
_options = options.Value;
}
public async Task Invoke(HttpContext context)
{
if (!_options.EnableRequestDecrypt)
{
await _next(context);
return;
}
// 检查请求是否加密
var encryptedHeader = context.Request.Headers[CryptoOptions.EncryptedRequestHeader].ToString();
if (string.IsNullOrEmpty(encryptedHeader) || encryptedHeader != "true")
{
await _next(context);
return;
}
// 获取 RSA 加密后的 AES 密钥
var encryptedKey = context.Request.Headers[CryptoOptions.EncryptedKeyHeader].ToString();
if (string.IsNullOrEmpty(encryptedKey))
{
context.Response.StatusCode = StatusCodes.Status400BadRequest;
await context.Response.WriteAsync("缺少加密密钥 Header");
return;
}
try
{
// 读取原始请求体
context.Request.EnableBuffering();
using var memoryStream = new MemoryStream();
await context.Request.Body.CopyToAsync(memoryStream);
var bodyBytes = memoryStream.ToArray();
context.Request.Body.Position = 0;
// RSA 解密得到 AES 密钥
var aesKey = CryptoHelper.RsaDecrypt(encryptedKey, _options.RsaPrivateKey);
// AES 解密请求体(GET 请求 Body 为空则跳过)
if (bodyBytes.Length > 0)
{
var cipherText = Encoding.UTF8.GetString(bodyBytes);
var plainText = CryptoHelper.AesDecrypt(cipherText, aesKey, _options.AesMode);
// 替换请求体为解密后的内容
var plainBytes = Encoding.UTF8.GetBytes(plainText);
context.Request.Body = new MemoryStream(plainBytes);
context.Request.ContentLength = plainBytes.Length;
}
// 解密 Get 参数:前端将整个 query 加密后放入参数 q,解密后还原为明文参数
var encryptedQuery = context.Request.Query[CryptoOptions.EncryptedQueryParam].ToString();
if (!string.IsNullOrEmpty(encryptedQuery))
{
var plainQuery = CryptoHelper.AesDecrypt(encryptedQuery, aesKey, _options.AesMode);
context.Request.QueryString = new QueryString("?" + plainQuery);
}
await _next(context);
}
catch (Exception ex)
{
context.Response.StatusCode = StatusCodes.Status400BadRequest;
await context.Response.WriteAsync($"请求解密失败: {ex.Message}");
}
}
}
}
响应加密中间件
Middleware/Crypto/ResponseEncryptMiddleware.cs:
using System;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace Gateway.Middleware.Crypto
{
/// <summary>
/// 响应加密中间件
/// 后端生成随机 AES 密钥加密响应体,
/// 再用 RSA 公钥加密 AES 密钥放入 Header;前端收到后用 RSA 私钥解出 AES 密钥,再解密响应体。
/// </summary>
public class ResponseEncryptMiddleware
{
private readonly RequestDelegate _next;
private readonly CryptoOptions _options;
public ResponseEncryptMiddleware(RequestDelegate next, IOptions<CryptoOptions> options)
{
_next = next;
_options = options.Value;
}
public async Task Invoke(HttpContext context)
{
if (!_options.EnableResponseEncrypt)
{
await _next(context);
return;
}
// 临时替换 Response.Body 来捕获输出
using var memoryStream = new MemoryStream();
var originalBody = context.Response.Body;
context.Response.Body = memoryStream;
try
{
await _next(context);
}
finally
{
context.Response.Body = originalBody;
}
if (memoryStream.Length == 0)
{
return;
}
// 原始响应内容
var plainBytes = memoryStream.ToArray();
var plainText = Encoding.UTF8.GetString(plainBytes);
try
{
// 生成随机 AES 密钥
var aesKey = CryptoHelper.GenerateAesKey();
// AES 加密响应数据
var cipherText = CryptoHelper.AesEncrypt(plainText, aesKey, _options.AesMode);
// RSA 加密 AES 密钥
var encryptedKey = CryptoHelper.RsaEncrypt(aesKey, _options.RsaPublicKey);
// 设置响应 Header
context.Response.Headers[CryptoOptions.EncryptedResponseHeader] = "true";
context.Response.Headers[CryptoOptions.EncryptedKeyHeader] = encryptedKey;
// 写入加密后的响应体
var cipherBytes = Encoding.UTF8.GetBytes(cipherText);
context.Response.ContentLength = cipherBytes.Length;
await context.Response.Body.WriteAsync(cipherBytes);
}
catch (Exception)
{
// 加密失败时回退返回原始数据
context.Response.Headers[CryptoOptions.EncryptedResponseHeader] = "false";
await context.Response.Body.WriteAsync(plainBytes);
}
}
}
}
启动注册(Program.cs)
顺序很关键:CORS → 加解密中间件 → 其他中间件 → Ocelot。
加解密中间件必须在 Ocelot 之前,才能作为最外层包装所有转发请求/响应;CORS 必须最靠前,预检 OPTIONS 才能被短路,避免落入 Ocelot 报UnableToFindDownstreamRouteError。
using Gateway.Middleware.Crypto;
using Microsoft.Extensions.Options;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using Ocelot.Provider.Consul;
var builder = WebApplication.CreateBuilder(args);
// Add Ocelot configuration
builder.Configuration.AddJsonFile("configuration.json", optional: false, reloadOnChange: true);
// 配置加密选项
builder.Services.Configure<CryptoOptions>(builder.Configuration.GetSection("Crypto"));
// 配置 CORS,允许携带自定义加密头(X-Encrypted / X-Encrypted-Key)的跨域请求
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(policy =>
{
policy.SetIsOriginAllowed(_ => true)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.WithExposedHeaders("X-Encrypted", "X-Encrypted-Key");
});
});
builder.Services.AddControllers();
builder.Services.AddOcelot(builder.Configuration).AddConsul();
var app = builder.Build();
// CORS 必须最先注册,预检 OPTIONS 在此直接短路返回,避免落入 Ocelot 导致路由匹配失败
app.UseCors();
// ===== 加密中间件必须最先注册,才能作为最外层包装所有请求/响应 =====
var cryptoOption = app.Services.GetService<IOptions<CryptoOptions>>();
if (cryptoOption != null && cryptoOption.Value != null && cryptoOption.Value.Enable)
{
app.UseMiddleware<ResponseEncryptMiddleware>();
app.UseMiddleware<RequestDecryptMiddleware>();
}
app.UseRouting();
app.UseResponseCaching();
app.MapControllers();
app.UseEndpoints(f => { });
app.UseWebSockets();
app.UseOcelot().Wait();
app.Run();
Ocelot 注册与配置
服务注册(Program.cs)
// 注册 Ocelot + Consul 服务发现
builder.Services.AddOcelot(builder.Configuration).AddConsul();
// 管线末端启用 Ocelot
app.UseOcelot().Wait();
路由配置(configuration.json)
Ocelot 按 UpstreamPathTemplate 匹配并转发到 Consul 中注册的下游服务。关键点:上游 UpstreamHttpMethod 必须显式包含 OPTIONS,否则跨域预检会因匹配不到路由而失败。
{
"Routes": [
{
"DownstreamPathTemplate": "/api/Common/{url}",
"DownstreamScheme": "http",
"UpstreamPathTemplate": "/api/Common/{url}",
"UpstreamHttpMethod": [ "Get", "Post", "Options" ],
"UseServiceDiscovery": true,
"ServiceName": "CommonService",
"LoadBalancerOptions": {
"Type": "RoundRobin"
}
},
{
"DownstreamPathTemplate": "/api/Other/{url}",
"DownstreamScheme": "http",
"UpstreamPathTemplate": "/api/Other/{url}",
"UpstreamHttpMethod": [ "Get", "Post", "Options" ],
"UseServiceDiscovery": true,
"ServiceName": "OtherService",
"LoadBalancerOptions": {
"Type": "RoundRobin"
}
}
],
"GlobalConfiguration": {
"ServiceDiscoveryProvider": {
"Type": "Consul"
}
}
}
若同源访问(页面与接口同域),浏览器不会发预检 OPTIONS,此时可不加
Options;
若跨域访问,必须加上Options,并由 CORS 中间件返回Access-Control-Allow-Headers。
CORS
后端 CORS
见「启动注册(Program.cs)」中的 AddCors + app.UseCors()。要点:
WithExposedHeaders("X-Encrypted", "X-Encrypted-Key"):让前端 JS 能读取响应里的加密头。AllowAnyHeader():允许请求携带自定义加密头,预检响应会回显Access-Control-Allow-Headers。UseCors()放在管线最前,预检 OPTIONS 在此直接返回 204 + CORS 头,不再进 Ocelot。
Nginx 反向代理(可选)
若前置 Nginx,需保证 自定义头透传,并让预检由后端 CORS 处理(不要用 if ($request_method = 'OPTIONS') return 204;,因为 add_header 不会作用于 return 生成的响应,会导致预检缺少 CORS 头):
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
location /api {
proxy_pass http://127.0.0.1:7000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# CORS 由后端中间件统一处理;如确需在 Nginx 兜底,可加:
# add_header Access-Control-Allow-Origin "*" always;
# add_header Access-Control-Allow-Headers "Content-Type,Authorization,X-Encrypted,X-Encrypted-Key" always;
# add_header Access-Control-Expose-Headers "X-Encrypted,X-Encrypted-Key" always;
}
}
推荐做法:页面与接口走同源(例如页面放 Nginx
html目录、接口用相对路径/api/...),彻底避免预检,最省心。
HTML Demo
将以下文件放到 Nginx 的 html 目录(或任意静态服务器),浏览器打开即可测试。
关键实现说明:
- 浏览器
WebCrypto的RSA-OAEP与后端RSAEncryptionPadding.Pkcs1不兼容,因此 Demo 用 BigInt 手写 PKCS#1 v1.5 加解密,并自行解析 PEM(SubjectPublicKeyInfo / PKCS#8)。 - AES 使用
WebCrypto的AES-CBC,IV 为 16 字节全 0,与后端CryptoHelper._aesIvFixed对齐。 - 默认请求地址用相对路径
/api/xxx/xxx,与页面同源,避免跨域预检。 - 私钥默认留空,使用时填入即可自动解密响应。
- POST:AES 加密 Body;GET:AES 加密整段 query 放入参数
q(?q=密文),二者复用同一把随机 AES 密钥(X-Encrypted-Key携带)。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>接口加解密请求 Demo</title>
<style>
* { box-sizing: border-box; }
body { font-family: "Segoe UI", "Microsoft YaHei", sans-serif; background: #f5f6f8; margin: 0; padding: 24px; color: #1f2329; }
.wrap { max-width: 880px; margin: 0 auto; }
h1 { font-size: 20px; margin: 0 0 4px; }
.sub { color: #8a9099; font-size: 13px; margin-bottom: 20px; }
.card { background: #fff; border: 1px solid #e5e6eb; border-radius: 8px; padding: 18px 20px; margin-bottom: 16px; }
label { display: block; font-size: 13px; font-weight: 600; margin: 12px 0 6px; }
label:first-child { margin-top: 0; }
input, textarea { width: 100%; padding: 9px 11px; font-size: 13px; font-family: inherit; border: 1px solid #d0d3d9; border-radius: 6px; outline: none; background: #fbfbfc; }
textarea { resize: vertical; min-height: 110px; font-family: Consolas, Monaco, monospace; }
button { margin-top: 16px; padding: 10px 22px; font-size: 14px; font-weight: 600; color: #fff; background: #3370ff; border: none; border-radius: 6px; cursor: pointer; }
button:hover { background: #245bdb; }
button:disabled { background: #a8b6d6; cursor: not-allowed; }
pre { background: #1e1e1e; color: #d4d4d4; padding: 14px; border-radius: 6px; font-family: Consolas, Monaco, monospace; font-size: 12.5px; line-height: 1.6; overflow: auto; max-height: 340px; margin: 0; white-space: pre-wrap; word-break: break-all; }
.status { font-size: 13px; font-weight: 600; margin-bottom: 10px; }
.ok { color: #17a34a; }
.err { color: #e11d48; }
.tag { display:inline-block; padding:1px 8px; border-radius:4px; font-size:12px; background:#eef2ff; color:#3370ff; margin-right:8px; }
.hint { font-size:12px; color:#8a9099; margin-top:6px; }
</style>
</head>
<body>
<div class="wrap">
<h1>接口加解密请求 Demo</h1>
<div class="sub">AES-256-CBC + RSA(PKCS1) 混合加密 · 对齐后端 RequestDecrypt / ResponseEncrypt 中间件</div>
<div class="card">
<label>接口地址</label>
<input id="url" value="/api/xxx/xxx" />
<label>RSA 公钥(PEM,后端 Crypto:RsaPublicKey)</label>
<textarea id="pubkey" placeholder="-----BEGIN PUBLIC KEY-----...-----END PUBLIC KEY-----"></textarea>
<label>请求体 JSON(明文)</label>
<textarea id="payload">{
"key": "value"
}</textarea>
<label>RSA 私钥(PEM,后端 Crypto:RsaPrivateKey,可选;填写后自动解密加密响应)</label>
<textarea id="privkey" placeholder="-----BEGIN PRIVATE KEY-----...-----END PRIVATE KEY-----"></textarea>
<button id="send">发送加密请求</button>
<div class="hint">请求头 X-Encrypted: true,X-Encrypted-Key 携带 RSA 加密后的 AES 密钥,Body 为 AES 加密后的 Base64 密文。</div>
</div>
<div class="card">
<label>GET 接口地址(不含参数)</label>
<input id="getUrl" value="/api/common/FileBucket/GetList" />
<label>GET 明文参数(query 串,不含 ?)</label>
<input id="getQuery" value="PageIndex=1&PageSize=20" />
<div class="hint">前端将整段 query 用 AES 加密后放入参数 <b>q</b>,即 <code>?q=密文</code>;后端解密后还原为明文参数。</div>
<button id="sendGet">发送加密 GET 请求</button>
</div>
<div class="card">
<div class="status" id="status">等待请求…</div>
<div style="margin-bottom:10px"><span class="tag">请求</span><span id="reqInfo"></span></div>
<pre id="reqOut">—</pre>
<div style="margin:14px 0 10px"><span class="tag">响应(原始)</span><span id="resInfo"></span></div>
<pre id="resOut">—</pre>
<div style="margin:14px 0 10px"><span class="tag">响应(解密后)</span><span id="decInfo"></span></div>
<pre id="decOut">—</pre>
</div>
</div>
<script>
/* ---------- 工具:Base64 / PEM ---------- */
function b64ToBytes(b64) {
const bin = atob(b64.replace(/\s+/g, ''));
const out = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
return out;
}
function bytesToB64(bytes) {
let bin = '';
const chunk = 0x8000;
for (let i = 0; i < bytes.length; i += chunk) {
bin += String.fromCharCode.apply(null, bytes.subarray(i, i + chunk));
}
return btoa(bin);
}
function strToBytes(s) { return new TextEncoder().encode(s); }
function bytesToStr(b) { return new TextDecoder().decode(b); }
/* ---------- AES-256-CBC / PKCS7,固定 16 字节全 0 IV(对齐后端) ---------- */
async function importAesKey(rawKey) {
return crypto.subtle.importKey('raw', rawKey, { name: 'AES-CBC' }, false, ['encrypt', 'decrypt']);
}
async function aesEncrypt(plainText, rawKey) {
const key = await importAesKey(rawKey);
const iv = new Uint8Array(16);
const ct = await crypto.subtle.encrypt({ name: 'AES-CBC', iv }, key, strToBytes(plainText));
return bytesToB64(new Uint8Array(ct));
}
async function aesDecrypt(cipherB64, rawKey) {
const key = await importAesKey(rawKey);
const iv = new Uint8Array(16);
const pt = await crypto.subtle.decrypt({ name: 'AES-CBC', iv }, key, b64ToBytes(cipherB64));
return bytesToStr(new Uint8Array(pt));
}
/* ---------- 解析 RSA 公钥(SubjectPublicKeyInfo PEM),取 n/e ---------- */
function pemToDer(pem) {
const body = pem.replace(/-----BEGIN [^-]+-----/, '')
.replace(/-----END [^-]+-----/, '')
.replace(/\s+/g, '');
return b64ToBytes(body);
}
function parseRsaPublicKey(pem) {
const der = pemToDer(pem);
let pos = 0;
function readLen() {
let len = der[pos++];
if (len & 0x80) {
const n = len & 0x7f; len = 0;
for (let i = 0; i < n; i++) len = (len << 8) | der[pos++];
}
return len;
}
function readSeq() {
if (der[pos++] !== 0x30) throw new Error('DER: 期望 SEQUENCE');
return readLen();
}
function skipTlv() { pos++; const len = readLen(); pos += len; }
readSeq(); // 外层 SubjectPublicKeyInfo
skipTlv(); // AlgorithmIdentifier
if (der[pos++] !== 0x03) throw new Error('DER: 期望 BIT STRING');
readLen();
pos++; // 忽略未使用位
readSeq(); // 内层 RSAPublicKey SEQUENCE
if (der[pos++] !== 0x02) throw new Error('DER: 期望 INTEGER n');
const nLen = readLen();
const nStart = pos;
let n = 0n;
for (let i = 0; i < nLen; i++) n = (n << 8n) | BigInt(der[pos++]);
let k = nLen;
while (k > 0 && der[nStart + (nLen - k)] === 0x00) k--;
if (der[pos++] !== 0x02) throw new Error('DER: 期望 INTEGER e');
const eLen = readLen();
let e = 0n;
for (let i = 0; i < eLen; i++) e = (e << 8n) | BigInt(der[pos++]);
return { n, e, k };
}
/* ---------- 解析 RSA 私钥(兼容 PKCS#1 与 PKCS#8),取 n/e/d ---------- */
function parseRsaPrivateKey(pem) {
const der = pemToDer(pem);
let pos = 0;
function readLen() {
let len = der[pos++];
if (len & 0x80) {
const n = len & 0x7f; len = 0;
for (let i = 0; i < n; i++) len = (len << 8) | der[pos++];
}
return len;
}
function readInt() {
if (der[pos++] !== 0x02) throw new Error('DER: 期望 INTEGER');
const len = readLen();
let v = 0n;
for (let i = 0; i < len; i++) v = (v << 8n) | BigInt(der[pos++]);
return { v, len };
}
function readSeq() { if (der[pos++] !== 0x30) throw new Error('DER: 期望 SEQUENCE'); return readLen(); }
function skipTlv() { pos++; const len = readLen(); pos += len; }
readSeq(); // 外层 SEQUENCE
// 检测 PKCS#8:version(02 01 00) 后紧跟 AlgorithmIdentifier SEQUENCE
if (der[pos] === 0x02 && der[pos + 3] === 0x30) {
readInt(); // version
skipTlv(); // AlgorithmIdentifier
if (der[pos++] !== 0x04) throw new Error('DER: 期望 OCTET STRING');
readLen(); // 进入 OCTET STRING 内容
readSeq(); // 内层 RSAPrivateKey SEQUENCE
}
readInt(); // version
const nInt = readInt(); // n
const eInt = readInt(); // e
const dInt = readInt(); // d
const k = nInt.len - (nInt.len > 1 && (nInt.v >> BigInt(8 * (nInt.len - 1))) === 0n ? 1 : 0);
return { n: nInt.v, e: eInt.v, d: dInt.v, k };
}
function bytesToBigInt(bytes) { let v = 0n; for (const b of bytes) v = (v << 8n) | BigInt(b); return v; }
function bigIntToBytes(v, len) { const out = new Uint8Array(len); for (let i = len - 1; i >= 0; i--) { out[i] = Number(v & 0xffn); v >>= 8n; } return out; }
function modPow(base, exp, mod) { let r = 1n; base %= mod; while (exp > 0n) { if (exp & 1n) r = (r * base) % mod; exp >>= 1n; base = (base * base) % mod; } return r; }
/* ---------- RSA PKCS#1 v1.5 加解密 ---------- */
function rsaEncryptPkcs1(pub, messageBytes) {
const k = pub.k;
if (messageBytes.length > k - 11) throw new Error('RSA 明文过长');
const ps = new Uint8Array(k - 3 - messageBytes.length);
crypto.getRandomValues(ps);
for (let i = 0; i < ps.length; i++) if (ps[i] === 0) ps[i] = 1;
const em = new Uint8Array(k);
em[0] = 0x00; em[1] = 0x02;
em.set(ps, 2);
em[2 + ps.length] = 0x00;
em.set(messageBytes, 3 + ps.length);
const m = bytesToBigInt(em);
return bigIntToBytes(modPow(m, pub.e, pub.n), k);
}
function rsaDecryptPkcs1(priv, cipherBytes) {
const m = modPow(bytesToBigInt(cipherBytes), priv.d, priv.n);
const em = bigIntToBytes(m, priv.k);
if (em[0] !== 0x00 || em[1] !== 0x02) throw new Error('PKCS#1 解密格式错误');
let i = 2;
while (i < em.length && em[i] !== 0x00) i++;
return em.slice(i + 1);
}
/* ---------- 主流程 ---------- */
const $ = id => document.getElementById(id);
$('send').onclick = async () => {
const btn = $('send'); btn.disabled = true;
$('status').className = 'status'; $('status').textContent = '请求中…';
$('reqOut').textContent = '—'; $('resOut').textContent = '—'; $('decOut').textContent = '—';
$('reqInfo').textContent = ''; $('resInfo').textContent = ''; $('decInfo').textContent = '';
try {
const url = $('url').value.trim();
const pem = $('pubkey').value;
const payload = $('payload').value;
// 生成随机 AES-256 密钥
const rawKey = crypto.getRandomValues(new Uint8Array(32));
const aesKeyB64 = bytesToB64(rawKey);
// AES 加密请求体
const cipherText = await aesEncrypt(payload, rawKey);
// RSA 公钥加密 AES 密钥(Base64 字符串)
const pub = parseRsaPublicKey(pem);
const encKey = bytesToB64(rsaEncryptPkcs1(pub, strToBytes(aesKeyB64)));
// 发送
const headers = {
'Content-Type': 'application/json',
'accept': 'text/plain',
'X-Encrypted': 'true',
'X-Encrypted-Key': encKey
};
$('reqInfo').textContent = `AES Key: ${aesKeyB64}`;
$('reqOut').textContent = JSON.stringify(headers, null, 2) + '\n\n' + cipherText;
const res = await fetch(url, { method: 'POST', headers, body: cipherText });
const resText = await res.text();
const resEncrypted = res.headers.get('X-Encrypted');
const resKey = res.headers.get('X-Encrypted-Key');
// 原始响应展示
$('resOut').textContent = resText;
$('resInfo').textContent = `HTTP ${res.status}` + (resEncrypted === 'true' ? ' · 已加密' : '');
// 解密后的响应展示
let decrypted = null;
let decMsg = '';
if (resEncrypted === 'true' && resKey) {
const privPem = $('privkey').value.trim();
if (privPem) {
try {
const priv = parseRsaPrivateKey(privPem);
const respAesKeyB64 = bytesToStr(rsaDecryptPkcs1(priv, b64ToBytes(resKey)));
decrypted = await aesDecrypt(resText, b64ToBytes(respAesKeyB64));
try { decrypted = JSON.stringify(JSON.parse(decrypted), null, 2); } catch (_) { }
decMsg = `解密成功 · HTTP ${res.status}`;
$('status').className = res.ok ? 'status ok' : 'status err';
$('status').textContent = `HTTP ${res.status} ${res.statusText}`;
} catch (e) {
decMsg = `解密失败: ${e.message}`;
$('status').className = 'status err';
$('status').textContent = `HTTP ${res.status} · 响应解密失败`;
}
} else {
decMsg = '响应已加密,请在上方填写 RSA 私钥以自动解密';
$('status').className = 'status ok';
$('status').textContent = `HTTP ${res.status} · 响应加密(未填私钥,无法解密)`;
}
} else {
decrypted = resText;
try { decrypted = JSON.stringify(JSON.parse(decrypted), null, 2); } catch (_) { }
decMsg = '响应未加密(直接展示)';
$('status').className = res.ok ? 'status ok' : 'status err';
$('status').textContent = `HTTP ${res.status} ${res.statusText}`;
}
$('decInfo').textContent = decMsg;
$('decOut').textContent = decrypted !== null ? decrypted : '—';
} catch (e) {
$('status').className = 'status err';
$('status').textContent = '请求失败: ' + e.message;
$('decInfo').textContent = '';
$('decOut').textContent = e.stack || String(e);
} finally {
btn.disabled = false;
}
};
/* ---------- GET 请求:整段 query 加密后放入参数 q ---------- */
$('sendGet').onclick = async () => {
const btn = $('sendGet'); btn.disabled = true;
$('status').className = 'status'; $('status').textContent = '请求中…';
$('reqOut').textContent = '—'; $('resOut').textContent = '—'; $('decOut').textContent = '—';
$('reqInfo').textContent = ''; $('resInfo').textContent = ''; $('decInfo').textContent = '';
try {
const baseUrl = $('getUrl').value.trim();
const plainQuery = $('getQuery').value.trim();
const pem = $('pubkey').value;
// 1. 生成随机 AES-256 密钥
const rawKey = crypto.getRandomValues(new Uint8Array(32));
const aesKeyB64 = bytesToB64(rawKey);
// 2. AES 加密整段 query
const cipherText = await aesEncrypt(plainQuery, rawKey);
// 3. RSA 公钥加密 AES 密钥
const pub = parseRsaPublicKey(pem);
const encKey = bytesToB64(rsaEncryptPkcs1(pub, strToBytes(aesKeyB64)));
// 4. 组装请求:?q=密文
const url = baseUrl + '?q=' + encodeURIComponent(cipherText);
const headers = {
'accept': 'text/plain',
'X-Encrypted': 'true',
'X-Encrypted-Key': encKey
};
$('reqInfo').textContent = `AES Key: ${aesKeyB64} · 明文 query: ${plainQuery}`;
$('reqOut').textContent = JSON.stringify(headers, null, 2) + '\n\nGET ' + url;
const res = await fetch(url, { method: 'GET', headers });
const resText = await res.text();
const resEncrypted = res.headers.get('X-Encrypted');
const resKey = res.headers.get('X-Encrypted-Key');
$('resOut').textContent = resText;
$('resInfo').textContent = `HTTP ${res.status}` + (resEncrypted === 'true' ? ' · 已加密' : '');
let decrypted = null;
let decMsg = '';
if (resEncrypted === 'true' && resKey) {
const privPem = $('privkey').value.trim();
if (privPem) {
try {
const priv = parseRsaPrivateKey(privPem);
const respAesKeyB64 = bytesToStr(rsaDecryptPkcs1(priv, b64ToBytes(resKey)));
decrypted = await aesDecrypt(resText, b64ToBytes(respAesKeyB64));
try { decrypted = JSON.stringify(JSON.parse(decrypted), null, 2); } catch (_) { }
decMsg = `解密成功 · HTTP ${res.status}`;
$('status').className = res.ok ? 'status ok' : 'status err';
$('status').textContent = `HTTP ${res.status} ${res.statusText}`;
} catch (e) {
decMsg = `解密失败: ${e.message}`;
$('status').className = 'status err';
$('status').textContent = `HTTP ${res.status} · 响应解密失败`;
}
} else {
decMsg = '响应已加密,请在上方填写 RSA 私钥以自动解密';
$('status').className = 'status ok';
$('status').textContent = `HTTP ${res.status} · 响应加密(未填私钥,无法解密)`;
}
} else {
decrypted = resText;
try { decrypted = JSON.stringify(JSON.parse(decrypted), null, 2); } catch (_) { }
decMsg = '响应未加密(直接展示)';
$('status').className = res.ok ? 'status ok' : 'status err';
$('status').textContent = `HTTP ${res.status} ${res.statusText}`;
}
$('decInfo').textContent = decMsg;
$('decOut').textContent = decrypted !== null ? decrypted : '—';
} catch (e) {
$('status').className = 'status err';
$('status').textContent = '请求失败: ' + e.message;
$('decInfo').textContent = '';
$('decOut').textContent = e.stack || String(e);
} finally {
btn.disabled = false;
}
};
</script>
</body>
</html>
常见问题(排障清单)
| 现象 | 原因 | 解决 |
|---|---|---|
后端收不到 X-Encrypted / X-Encrypted-Key |
跨域预检失败,正式请求未发出 | 页面与接口同源(用相对路径),或后端/ Nginx 正确返回 Access-Control-Allow-Headers |
| 预检 204 但无 CORS 头 | Nginx 用 if ($request_method = 'OPTIONS') return 204;,add_header 不作用于 return 响应 |
去掉该 if,交给后端 CORS 处理;或在 if 内也加 add_header |
请求解密失败: ASN1 corrupted data. |
私钥 PEM 头与内容格式不符(头是 RSA PRIVATE KEY,内容是 PKCS#8) |
头改为 -----BEGIN PRIVATE KEY----- |
GET 请求参数解密后仍是 q=... / 业务取不到参数 |
未带 X-Encrypted: true 或未带 X-Encrypted-Key,中间件直接放行 |
确保加密请求同时带上这两个 Header;q 用同一 AES 密钥加密 |
| GET 请求 400 且提示解密失败 | q 密文未 URL 编码,+ / = 等字符在 query 中被转义/截断 |
前端 encodeURIComponent(cipherText) 后再拼接 ?q= |
Ocelot 报 UnableToFindDownstreamRouteError ... OPTIONS |
路由 UpstreamHttpMethod 未包含 Options,且 UseCors 未前置 |
路由加 "Options",并把 app.UseCors() 放在管线最前 |
| 响应 500 / 空 | 下游微服务未启动(Consul 服务发现失败) | 启动对应下游服务,确认 Consul 注册正常 |
| 浏览器无法读取响应加密头 | 未暴露响应头 | 后端 WithExposedHeaders("X-Encrypted","X-Encrypted-Key") |
| JSON 文件被加了 BOM 导致启动报错 | 用编辑器/PowerShell 写文件时写入 BOM | 以 UTF-8 无 BOM 保存 |
文件清单
| 文件 | 作用 |
|---|---|
Middleware/Crypto/CryptoOptions.cs |
加密配置项与 AES 模式枚举(含 EncryptedQueryParam = q 常量) |
Middleware/Crypto/CryptoHelper.cs |
AES / RSA 加解密核心工具 |
Middleware/Crypto/RequestDecryptMiddleware.cs |
请求解密中间件(Body + GET 的 q 参数) |
Middleware/Crypto/ResponseEncryptMiddleware.cs |
响应加密中间件 |
Program.cs |
CORS、加解密中间件、Ocelot 注册与顺序 |
configuration.json |
Ocelot 路由(含 Options 方法) |
appsettings.json |
Crypto 配置(公钥/私钥/Header 名/模式) |
crypto-demo.html |
浏览器端加解密 Demo(POST Body + GET q 参数) |
联系我:ivesbao@163.com

浙公网安备 33010602011771号