Compare commits

...
Author SHA1 Message Date
qaiu 922e762273 docs: 增加 SECURITY.md 安全政策
在仓库根目录添加中英文安全政策,说明私密漏洞报告渠道,以及安全修复面向最新稳定版本。
2026-12-04 08:31:55 +08:00
qaiu 4c48e992da fix: match browser UTF-8 AES key bytes for auth params (#321) 2026-12-04 03:35:55 +08:00
qaiu 76aaa7d214 fix: isolate server-side donation credentials and rotate auth defaults (#320) 2026-12-04 03:09:45 +08:00
20 changed files with 334 additions and 126 deletions

No files matched your search

+2 -2
View File
@@ -25,8 +25,8 @@ body:
id: version id: version
attributes: attributes:
label: 版本号 label: 版本号
description: 页面上的版本,或发布包名里的版本,例如 0.4.14。 description: 页面上的版本,或发布包名里的版本,例如 0.4.15。
placeholder: "0.4.14" placeholder: "0.4.15"
validations: validations:
required: true required: true
- type: dropdown - type: dropdown
+2 -2
View File
@@ -25,8 +25,8 @@ body:
id: version id: version
attributes: attributes:
label: 版本号 label: 版本号
description: 例如 0.4.14。不确定就写获取方式。 description: 例如 0.4.15。不确定就写获取方式。
placeholder: "0.4.14" placeholder: "0.4.15"
validations: validations:
required: true required: true
- type: dropdown - type: dropdown
+7 -9
View File
@@ -1,12 +1,10 @@
## 更新内容 ## v0.4.15
- 蓝奏密码页跨站 ajax(#316): - 浏览器与服务端以相同的 UTF-8 密钥字节处理临时认证,兼容 16、24 和 32 字节的密钥。
- 密码页请求 ajax 时补齐与浏览器一致的跨站头:`Origin` 和 `Sec-Fetch-Site: cross-site`。原先空 body 会被报成空响应,甚至触发 NPE;现在空 body 不再按空响应处理。 - 临时认证不再使用发行包里的公共密钥。未手动配置的服务实例每次启动生成随机密钥,只记录来源和指纹。保留旧发行包配置的实例也会自动迁移。
- 2026-11-29 14:19 Asia/Shanghai 在 249 用 `792d721` 解析 `https://wwaov.lanzouw.com/iNUOu4hbih4h`(密码 `1t54`),得到 `2311.exe` / 64.9 M / 68052582 字节,直链主机 `exe2.webgetstore.com`。只解析直链,没有完整下载文件体。 - 捐赠池默认关闭。显式启用后,受支持的网盘使用服务端选号,不再向前端提供捐赠账号。已保存的捐赠记录不会删除。
- 123 单文件分享下载改为 v2 App-Version 149(#313)。 - 清理网页和文档中的公共密钥。需要网页个人认证、外部客户端或多实例共享密钥的自建站,须显式配置和安全分发 `server.authEncryptKey`。
- Maven 解析器模块版本改为 10.2.7。不使用 10.2.6:Maven Central 已有 `cn.qaiu:parser:10.2.6`,发布时间早于 #313 / #316。
## 限制 ### 升级提醒
- 蓝奏加密分享的云端验证只解析了直链,没有完整下载并核对文件体。 旧公共密钥生成的 `auth` 参数不再兼容。升级后请核对部署配置,并视部署情况清理过往解析缓存和轮换捐赠凭据。
- 本说明中的版本号变更,不等于已经把 parser 发布到 Maven Central。发布时需要发 10.2.7,不是 10.2.6。
+11 -6
View File
@@ -163,14 +163,13 @@ GET /json/getFileList?url={分享链接}&pwd={密码}
- `your_host` 替换为您的域名或 IP - `your_host` 替换为您的域名或 IP
### 认证参数(v0.2.1+) ### 认证参数(v0.2.1+)
[可以使用在线认证参数加密](https://qaiu.top/nfd-auth.html)
部分网盘需要登录后的 Cookie 或 Authorization 才能下载。可通过 `auth` 参数传递认证信息: 部分网盘需要登录后的 Cookie 或 Authorization 才能下载。可通过 `auth` 参数传递认证信息:
**参数格式**:`auth` 参数值为 AES 加密后的 JSON 字符串,经过 Base64 编码和 URL 编码 **参数格式**:`auth` 参数值为 AES 加密后的 JSON 字符串,经过 Base64 编码和 URL 编码
**加密方式**: **加密方式**:
- 算法:AES/ECB/PKCS5Padding - 算法:AES/ECB/PKCS5Padding
- 密钥:`nfd_auth_key2026`(16字节) - 密钥:由自建服务显式配置并通过安全渠道交给可信客户端(无公共默认值)
- 流程:JSON → AES加密 → Base64 → URL编码 - 流程:JSON → AES加密 → Base64 → URL编码
**JSON 结构**: **JSON 结构**:
@@ -199,14 +198,20 @@ GET /json/getFileList?url={分享链接}&pwd={密码}
GET /parser?url={分享链接}&pwd={密码}&auth={加密后的认证参数} GET /parser?url={分享链接}&pwd={密码}&auth={加密后的认证参数}
``` ```
> 💡 提示:Web 界面已内置认证配置功能,可自动处理加密过程,无需手动构造参数。 > 💡 提示:自建站的可信客户端可在网页中填写其显式配置的服务认证密钥;网页不会获取或保存服务端密钥。
> [可以使用在线认证参数加密](https://qaiu.top/nfd-auth.html) > 不要在不受信任的站点输入服务密钥或网盘凭据。
#### 升级与捐赠开关
- 没有手动配置密钥(包括升级后仍保留旧发布包默认配置)的实例,在每次启动时自动生成进程随机密钥。启动日志只记录来源和指纹,不输出原文。重启后,之前用进程密钥生成的认证参数会失效。
- 要让可信浏览器、外部工具或多实例使用同一密钥,显式配置 `server.authEncryptKey`,通过安全渠道分发;不要使用旧发布包默认值。
- 捐赠默认关闭。仅设置 `server.enableDonatedAccounts: true` 且启用数据库后,才允许提交和服务端选用捐赠账号。关闭不删除已有记录。旧的浏览器取号接口已移除。仅 123 云盘、小飞机和蓝奏优享可使用服务端捐赠池;需要在下载响应携带账号请求头的网盘暂不开放。
#### 密钥作用说明 #### 密钥作用说明
- `server.authEncryptKey` - `server.authEncryptKey`
- 作用:用于 `auth` 参数的 AES 加解密 - 作用:用于 `auth` 参数的 AES 加解密
- 要求:16位(AES-128) - 要求:16、24 或 32 个 UTF-8 字节
- `server.donatedAccountFailureTokenSignKey` - `server.donatedAccountFailureTokenSignKey`
- 作用:用于“捐赠账号失败计数 token”的 HMAC 签名/验签 - 作用:用于“捐赠账号失败计数 token”的 HMAC 签名/验签
@@ -474,7 +479,7 @@ docker run --rm -v /var/run/docker.sock:/var/run/docker.sock containrrr/watchtow
> 注意: netdisk-fast-download.service中的ExecStart的路径改为实际路径 > 注意: netdisk-fast-download.service中的ExecStart的路径改为实际路径
```shell ```shell
cd ~ cd ~
wget -O netdisk-fast-download.zip https://github.com/qaiu/netdisk-fast-download/releases/download/v0.4.14/netdisk-fast-download-linux-amd64.zip wget -O netdisk-fast-download.zip https://github.com/qaiu/netdisk-fast-download/releases/download/v0.4.15/netdisk-fast-download-linux-amd64.zip
unzip netdisk-fast-download.zip unzip netdisk-fast-download.zip
cd netdisk-fast-download cd netdisk-fast-download
bash service-install.sh bash service-install.sh
+107
View File
@@ -0,0 +1,107 @@
[English](#security-policy) | [简体中文](#安全政策)
# Security Policy
Thank you for helping keep netdisk-fast-download (NFD) and its users safe.
## Supported Versions
Security fixes are provided for the latest stable release. Older releases are not actively maintained and generally do not receive security backports. Users are strongly encouraged to upgrade to the latest stable release.
| Version | Supported |
| --- | --- |
| Latest stable release | ✅ |
| Older releases | ❌ |
## Reporting a Vulnerability
Please report suspected security vulnerabilities privately through [GitHub Private Vulnerability Reporting](https://github.com/qaiu/netdisk-fast-download/security/advisories/new). Do not disclose unpatched vulnerabilities in public Issues, Pull Requests, Discussions, or other public channels.
Please include the following information where possible:
- Affected version or commit
- Vulnerability description, affected component, and potential impact
- Reproduction steps or a minimal proof of concept
- Relevant configuration, logs, and deployment details, with sensitive information redacted
Do not include real credentials, authentication keys, API tokens, or personal data in your report. Test only systems you own or are authorized to test.
## Scope
This policy applies to security vulnerabilities in the official NFD project, including authentication, authorization, credential handling, and other security-sensitive functionality.
Ordinary bugs, upstream API changes, and compatibility issues without a security impact should be reported through [GitHub Issues](https://github.com/qaiu/netdisk-fast-download/issues). Issues caused solely by third-party services, unofficial modifications, or unsafe deployment configurations are generally outside the scope of this policy. However, vulnerabilities in NFD's default configuration or its handling of third-party services remain in scope.
## Security Response and Disclosure
Security reports are handled on a best-effort basis, taking into account severity, impact, and maintainer availability. We aim to assess reports, develop appropriate fixes or mitigations, and coordinate public disclosure with reporters where possible. No fixed response or remediation timeframe is guaranteed.
## Security Best Practices
- Keep NFD and its dependencies up to date.
- Use HTTPS and restrict access to sensitive administrative interfaces.
- Protect authentication keys, API tokens, and cloud-drive credentials; never expose them in public logs, frontend bundles, or diagnostic reports.
- Enable only the services and optional features you need.
- Revoke or rotate potentially compromised credentials promptly.
## Security Advisories
For published vulnerabilities, affected versions, fixes, and mitigation guidance, see [GitHub Security Advisories](https://github.com/qaiu/netdisk-fast-download/security/advisories) and [Release Notes](https://github.com/qaiu/netdisk-fast-download/releases).
## Acknowledgments
We appreciate everyone who responsibly reports vulnerabilities and helps improve the security of NFD.
---
# 安全政策
感谢你帮助维护 netdisk-fast-download(NFD)及其用户的安全。
## 支持的版本
安全修复面向最新稳定版本。历史版本不再主动维护,原则上不提供安全补丁回移。强烈建议用户及时升级至最新稳定版本。
| 版本 | 是否支持 |
| --- | --- |
| 最新稳定版 | ✅ |
| 历史版本 | ❌ |
## 漏洞报告
请通过 [GitHub 私密漏洞报告](https://github.com/qaiu/netdisk-fast-download/security/advisories/new) 渠道提交疑似安全漏洞。请勿在公开 Issue、Pull Request、Discussion 或其他公开渠道披露尚未修复的漏洞。
请尽可能提供以下信息:
- 受影响的版本或提交
- 漏洞描述、受影响组件及潜在影响
- 复现步骤或最小概念验证
- 相关配置、日志及部署信息(请先脱敏)
请勿在报告中包含真实账号凭据、认证密钥、API 令牌或个人数据。请仅在自己拥有或已获得授权的环境中进行安全测试。
## 适用范围
本政策适用于 NFD 官方项目中的安全漏洞,包括身份认证、访问控制、凭据处理及其他涉及安全的功能。
不涉及安全影响的普通缺陷、上游接口变更及兼容性问题,请通过 [GitHub Issues](https://github.com/qaiu/netdisk-fast-download/issues) 反馈。仅由第三方服务、非官方修改或不安全部署配置引起的问题,原则上不属于本政策的适用范围。但 NFD 默认配置或第三方服务处理逻辑中存在的安全漏洞仍在适用范围内。
## 安全响应与披露
维护者将根据漏洞严重程度、影响范围及可用时间尽力处理安全报告,包括漏洞评估、制定修复或缓解措施,并尽可能与报告人协调公开披露。不承诺固定的响应或修复时限。
## 安全最佳实践
- 及时更新 NFD 及其依赖组件。
- 使用 HTTPS,并限制敏感管理接口的访问权限。
- 妥善保管认证密钥、API 令牌及网盘凭据,切勿通过公开日志、前端构建产物或诊断报告泄露。
- 仅启用实际需要的服务及可选功能。
- 及时撤销或轮换可能泄露的凭据。
## 安全公告
已公开的漏洞、影响版本、修复及缓解措施,请参阅 [GitHub 安全公告](https://github.com/qaiu/netdisk-fast-download/security/advisories) 和 [版本发布说明](https://github.com/qaiu/netdisk-fast-download/releases)。
## 致谢
感谢所有负责任地报告漏洞并帮助提升 NFD 安全性的研究人员与社区成员。
+1 -1
View File
@@ -28,7 +28,7 @@
**加密方式**: **加密方式**:
- 算法:AES/ECB/PKCS5Padding - 算法:AES/ECB/PKCS5Padding
- 密钥:`nfd_auth_key2026`(16字节) - 密钥:由自建服务显式配置并通过安全渠道交给可信客户端(无公共默认值)
- 流程:JSON → AES加密 → Base64 → URL编码 - 流程:JSON → AES加密 → Base64 → URL编码
**JSON 结构**: **JSON 结构**:
+8 -7
View File
@@ -33,8 +33,8 @@ URL解码 → Base64解码 → AES解密 → JSON对象
### 加密配置 ### 加密配置
- **加密算法**: AES/ECB/PKCS5Padding - **加密算法**: AES/ECB/PKCS5Padding
- **密钥长度**: 16位(128位) - **密钥长度**: 16、24 或 32 个 UTF-8 字节
- **默认密钥**: `nfd_auth_key2026`(可在 `app-dev.yml` 中通过 `server.authEncryptKey` 配置) - **密钥**: 没有公共默认值。需要对接的可信客户端应使用自建服务显式配置的 `server.authEncryptKey`。
### 密钥作用说明(重要) ### 密钥作用说明(重要)
@@ -43,7 +43,7 @@ URL解码 → Base64解码 → AES解密 → JSON对象
1. `server.authEncryptKey` 1. `server.authEncryptKey`
- 用途:加解密 `auth` 参数(前端/调用方传入的认证信息) - 用途:加解密 `auth` 参数(前端/调用方传入的认证信息)
- 影响范围:`/parser`、`/json/parser`、`/v2/linkInfo` 等接口中的 `auth` 参数 - 影响范围:`/parser`、`/json/parser`、`/v2/linkInfo` 等接口中的 `auth` 参数
- 注意:这是 **AES 对称加密密钥**,要求 16 位 - 注意:这是 **AES 对称加密密钥**,要求 16、24 或 32 字节
2. `server.donatedAccountFailureTokenSignKey` 2. `server.donatedAccountFailureTokenSignKey`
- 用途:签名和验签“捐赠账号失败计数 token”(用于防伪造、失败计数) - 用途:签名和验签“捐赠账号失败计数 token”(用于防伪造、失败计数)
@@ -194,7 +194,7 @@ AuthParam decoded = AuthParamCodec.decode(encrypted);
// 使用 CryptoJS 库 // 使用 CryptoJS 库
const CryptoJS = require('crypto-js'); const CryptoJS = require('crypto-js');
const AUTH_KEY = 'nfd_auth_key2026'; const AUTH_KEY = process.env.NFD_AUTH_ENCRYPT_KEY;
// 加密 // 加密
function encodeAuthParam(authObj) { function encodeAuthParam(authObj) {
@@ -234,7 +234,8 @@ from urllib.parse import quote, unquote
from Crypto.Cipher import AES from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad from Crypto.Util.Padding import pad, unpad
AUTH_KEY = b'nfd_auth_key2026' import os
AUTH_KEY = os.environ['NFD_AUTH_ENCRYPT_KEY'].encode('utf-8')
def encode_auth_param(auth_obj): def encode_auth_param(auth_obj):
"""加密认证参数""" """加密认证参数"""
@@ -323,8 +324,8 @@ if (auths != null) {
```yaml ```yaml
server: server:
# auth参数加密密钥(16位AES密钥) # auth参数加密密钥(16、24 或 32 字节)
authEncryptKey: 'your_custom_key16' # authEncryptKey: "" # 仅在可信客户端或多实例需共享密钥时显式配置
# 捐赠账号失败计数token签名密钥(HMAC) # 捐赠账号失败计数token签名密钥(HMAC)
# 建议使用较长随机字符串,并与 authEncryptKey 不同 # 建议使用较长随机字符串,并与 authEncryptKey 不同
@@ -72,7 +72,7 @@
## 使用说明 ## 使用说明
1. **编码流程**: JSON对象 → AES加密 → Base64编码 → URL编码 1. **编码流程**: JSON对象 → AES加密 → Base64编码 → URL编码
2. **加密配置**: AES/ECB/PKCS5Padding, 密钥: `nfd_auth_key2026` (16位) 2. **加密配置**: AES/ECB/PKCS5Padding, 密钥: 自建服务配置值(无公共默认值)
3. **接口调用**: `GET /parser?url={分享链接}&pwd={提取码}&auth={加密认证参数}` 3. **接口调用**: `GET /parser?url={分享链接}&pwd={提取码}&auth={加密认证参数}`
+1 -1
View File
@@ -17,7 +17,7 @@
</modules> </modules>
<properties> <properties>
<revision>0.4.14</revision> <revision>0.4.15</revision>
<java.version>17</java.version> <java.version>17</java.version>
<maven.compiler.source>17</maven.compiler.source> <maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target> <maven.compiler.target>17</maven.compiler.target>
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "nfd-web", "name": "nfd-web",
"version": "0.4.14", "version": "0.4.15",
"private": true, "private": true,
"scripts": { "scripts": {
"serve": "vue-cli-service serve", "serve": "vue-cli-service serve",
+24 -28
View File
@@ -51,7 +51,7 @@
<el-icon><Key /></el-icon> <el-icon><Key /></el-icon>
</el-button> </el-button>
</el-tooltip> </el-tooltip>
<el-tooltip content="捐赠网盘账号" placement="bottom"> <el-tooltip v-if="donatedAccountsEnabled" content="捐赠网盘账号" placement="bottom">
<el-button circle size="small" type="warning" @click="showDonateDialog = true"> <el-button circle size="small" type="warning" @click="showDonateDialog = true">
<el-icon><Present /></el-icon> <el-icon><Present /></el-icon>
</el-button> </el-button>
@@ -319,6 +319,10 @@
width="550px" width="550px"
:close-on-click-modal="false"> :close-on-click-modal="false">
<el-form :model="authConfig" label-width="100px" size="default"> <el-form :model="authConfig" label-width="100px" size="default">
<el-form-item label="服务认证密钥">
<el-input v-model="serverAuthKey" type="password" show-password
autocomplete="off" placeholder="自建站已配置的 authEncryptKey(仅本页内存)" />
</el-form-item>
<el-form-item label="网盘类型" required> <el-form-item label="网盘类型" required>
<el-select v-model="authConfig.panType" placeholder="请选择网盘类型" style="width: 100%" @change="onPanTypeChange"> <el-select v-model="authConfig.panType" placeholder="请选择网盘类型" style="width: 100%" @change="onPanTypeChange">
<el-option-group label="必须认证"> <el-option-group label="必须认证">
@@ -573,10 +577,6 @@
<el-form :model="donateConfig" label-width="100px" size="default"> <el-form :model="donateConfig" label-width="100px" size="default">
<el-form-item label="网盘类型" required> <el-form-item label="网盘类型" required>
<el-select v-model="donateConfig.panType" placeholder="请选择网盘类型" style="width: 100%" @change="onDonatePanTypeChange"> <el-select v-model="donateConfig.panType" placeholder="请选择网盘类型" style="width: 100%" @change="onDonatePanTypeChange">
<el-option-group label="必须认证">
<el-option label="夸克网盘 (QK)" value="QK" />
<el-option label="UC网盘 (UC)" value="UC" />
</el-option-group>
<el-option-group label="大文件需认证"> <el-option-group label="大文件需认证">
<el-option label="小飞机网盘 (FJ)" value="FJ" /> <el-option label="小飞机网盘 (FJ)" value="FJ" />
<el-option label="蓝奏优享 (IZ)" value="IZ" /> <el-option label="蓝奏优享 (IZ)" value="IZ" />
@@ -712,8 +712,10 @@ export default {
}, },
// 所有网盘的认证配置 { panType: config } // 所有网盘的认证配置 { panType: config }
allAuthConfigs: {}, allAuthConfigs: {},
serverAuthKey: '',
// 捐赠账号相关 // 捐赠账号相关
donatedAccountsEnabled: false,
showDonateDialog: false, showDonateDialog: false,
donateSubmitting: false, donateSubmitting: false,
donateConfig: { donateConfig: {
@@ -979,6 +981,10 @@ export default {
// 保存认证配置 // 保存认证配置
saveAuthConfig() { saveAuthConfig() {
if (![16, 24, 32].includes(new TextEncoder().encode(this.serverAuthKey).length)) {
this.$message.warning('个人认证需要自建站配置的服务认证密钥(16、24 或 32 个 UTF-8 字节)')
return
}
if (!this.authConfig.panType) { if (!this.authConfig.panType) {
this.$message.warning('请先选择网盘类型') this.$message.warning('请先选择网盘类型')
return return
@@ -1021,6 +1027,7 @@ export default {
ext5: '' ext5: ''
} }
this.allAuthConfigs = {} this.allAuthConfigs = {}
this.serverAuthKey = ''
localStorage.removeItem('nfd_auth_configs') localStorage.removeItem('nfd_auth_configs')
this.$message.success('所有认证配置已清除') this.$message.success('所有认证配置已清除')
this.showAuthConfigDialog = false this.showAuthConfigDialog = false
@@ -1040,31 +1047,15 @@ export default {
} }
}, },
// 生成加密的 auth 参数(优先使用个人配置,否则从后端随机获取捐赠账号) // 个人认证由可信客户端使用自建服务显式配置的密钥编码;捐赠凭据只在服务端使用。
async generateAuthParam() { async generateAuthParam() {
const panType = this.getCurrentPanType() const panType = this.getCurrentPanType()
if (!panType) return '' if (!panType) return ''
const config = this.allAuthConfigs[panType]
if (!config) return ''
const key = this.serverAuthKey
if (![16, 24, 32].includes(new TextEncoder().encode(key).length)) return ''
let config = null
// 优先使用个人配置
if (this.allAuthConfigs[panType]) {
config = this.allAuthConfigs[panType]
} else {
// 从后端随机获取捐赠账号(后端已加密,直接使用 encryptedAuth)
try {
const response = await axios.get(`${this.baseAPI}/v2/randomAuth`, { params: { panType } })
const encryptedAuth = response.data?.data?.encryptedAuth
if (encryptedAuth) {
return encryptedAuth
}
} catch (e) {
// no available donated account
}
return ''
}
// 个人配置:本地 AES 加密
const authObj = {} const authObj = {}
if (config.authType) authObj.authType = config.authType if (config.authType) authObj.authType = config.authType
if (config.username) authObj.username = config.username if (config.username) authObj.username = config.username
@@ -1079,7 +1070,7 @@ export default {
if (config.ext5) authObj.ext5 = config.ext5 if (config.ext5) authObj.ext5 = config.ext5
try { try {
const encrypted = this.aesEncrypt(JSON.stringify(authObj), 'nfd_auth_key2026') const encrypted = this.aesEncrypt(JSON.stringify(authObj), key)
return encodeURIComponent(encrypted) return encodeURIComponent(encrypted)
} catch (e) { } catch (e) {
console.error('生成认证参数失败:', e) console.error('生成认证参数失败:', e)
@@ -1719,7 +1710,11 @@ export default {
token: isPasswordAuth ? '' : (this.donateConfig.token || ''), token: isPasswordAuth ? '' : (this.donateConfig.token || ''),
remark: this.donateConfig.remark || '' remark: this.donateConfig.remark || ''
} }
await axios.post(`${this.baseAPI}/v2/donateAccount`, payload) const response = await axios.post(`${this.baseAPI}/v2/donateAccount`, payload)
if (response.data?.code !== 200) {
this.$message.error(response.data?.msg || '捐赠失败')
return
}
this.$message.success(`已捐赠 ${this.getPanDisplayName(this.donateConfig.panType)} 账号,感谢您的贡献!`) this.$message.success(`已捐赠 ${this.getPanDisplayName(this.donateConfig.panType)} 账号,感谢您的贡献!`)
// 重置表单 // 重置表单
@@ -1749,6 +1744,7 @@ export default {
} }
if (data && typeof data === 'object') { if (data && typeof data === 'object') {
this.donatedAccountsEnabled = data.enabled === true
// 兼容新结构: { active: {...}, inactive: {...} } // 兼容新结构: { active: {...}, inactive: {...} }
if (data.active && data.inactive) { if (data.active && data.inactive) {
if (data.active.total === undefined) { if (data.active.total === undefined) {
@@ -5,6 +5,7 @@ import cn.qaiu.db.pool.JDBCPoolInit;
import cn.qaiu.lz.common.cache.CacheConfigLoader; import cn.qaiu.lz.common.cache.CacheConfigLoader;
import cn.qaiu.lz.common.cache.CacheManager; import cn.qaiu.lz.common.cache.CacheManager;
import cn.qaiu.lz.common.interceptorImpl.RateLimiter; import cn.qaiu.lz.common.interceptorImpl.RateLimiter;
import cn.qaiu.lz.common.util.AuthParamCodec;
import cn.qaiu.lz.web.config.PlaygroundConfig; import cn.qaiu.lz.web.config.PlaygroundConfig;
import cn.qaiu.lz.web.service.DbService; import cn.qaiu.lz.web.service.DbService;
import cn.qaiu.lz.web.service.impl.ShoutServiceImpl; import cn.qaiu.lz.web.service.impl.ShoutServiceImpl;
@@ -90,6 +91,7 @@ public class AppMain {
* @param jsonObject 配置 * @param jsonObject 配置
*/ */
private static void exec(JsonObject jsonObject) { private static void exec(JsonObject jsonObject) {
AuthParamCodec.configure(jsonObject.getJsonObject(ConfigConstant.SERVER));
WebClientVertxInit.init(VertxHolder.getVertxInstance()); WebClientVertxInit.init(VertxHolder.getVertxInstance());
DatabindCodec.mapper().registerModule(new JavaTimeModule()); DatabindCodec.mapper().registerModule(new JavaTimeModule());
// 演练场配置要先加载,后续启动流程才能按开关决定是否注册动态解析器。 // 演练场配置要先加载,后续启动流程才能按开关决定是否注册动态解析器。
@@ -3,13 +3,18 @@ package cn.qaiu.lz.common.util;
import cn.qaiu.lz.web.model.AuthParam; import cn.qaiu.lz.web.model.AuthParam;
import cn.qaiu.util.AESUtils; import cn.qaiu.util.AESUtils;
import cn.qaiu.util.Base64Decoder; import cn.qaiu.util.Base64Decoder;
import cn.qaiu.vx.core.util.SharedDataUtil;
import io.vertx.core.json.JsonObject; import io.vertx.core.json.JsonObject;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.HexFormat;
/** /**
* 认证参数编解码工具类 * 认证参数编解码工具类
@@ -24,34 +29,56 @@ import java.nio.charset.StandardCharsets;
@Slf4j @Slf4j
public class AuthParamCodec { public class AuthParamCodec {
/**
* 默认加密密钥(16位)
*/
private static final String DEFAULT_ENCRYPT_KEY = "nfd_auth_key2026";
/**
* 配置中的密钥路径
*/
private static final String CONFIG_KEY_PATH = "authEncryptKey"; private static final String CONFIG_KEY_PATH = "authEncryptKey";
// 识别升级时保留下来的旧发行版配置;不再使用旧密钥。
private static final String RETIRED_KEY_SHA256 = "b2c23dd4619534db9831db32be8e699412f1de60138ac37234eaae827ff1bcf4";
private static final String PROCESS_RANDOM_KEY = generateKey();
private static volatile String encryptKey = PROCESS_RANDOM_KEY;
private AuthParamCodec() { private AuthParamCodec() {
// 工具类禁止实例化
} }
/** public static void configure(JsonObject serverConfig) {
* 获取加密密钥 String configuredKey = serverConfig.getString(CONFIG_KEY_PATH);
* 优先从配置文件读取,如果未配置则使用默认密钥 encryptKey = selectKey(configuredKey);
*/ log.info("authEncryptKey: source={}, fingerprint(SHA-256)={}",
public static String getEncryptKey() { encryptKey == PROCESS_RANDOM_KEY ? "generated (this process only)" : "configured",
try { fingerprint(encryptKey).substring(0, 12));
String configKey = SharedDataUtil.getJsonStringForServerConfig(CONFIG_KEY_PATH); }
if (StringUtils.isNotBlank(configKey)) {
return configKey; static String selectKey(String configuredKey) {
} if (StringUtils.isBlank(configuredKey) || RETIRED_KEY_SHA256.equals(fingerprint(configuredKey))) {
} catch (Exception e) { return PROCESS_RANDOM_KEY;
log.debug("从配置读取加密密钥失败,使用默认密钥: {}", e.getMessage());
} }
return DEFAULT_ENCRYPT_KEY; int length = configuredKey.getBytes(StandardCharsets.UTF_8).length;
if (length != 16 && length != 24 && length != 32) {
throw new IllegalArgumentException("server.authEncryptKey must be 16, 24, or 32 UTF-8 bytes");
}
return configuredKey;
}
static String generateKey() {
byte[] random = new byte[24];
new SecureRandom().nextBytes(random);
return Base64.getUrlEncoder().withoutPadding().encodeToString(random);
}
private static String fingerprint(String value) {
try {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256")
.digest(value.getBytes(StandardCharsets.UTF_8)));
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-256 unavailable", e);
}
}
private static SecretKeySpec asAesKey(String key) {
// Match CryptoJS: AES key lengths and values are defined by the full UTF-8 bytes.
return new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
}
public static String getEncryptKey() {
return encryptKey;
} }
/** /**
@@ -69,7 +96,7 @@ public class AuthParamCodec {
* 解码认证参数(指定密钥) * 解码认证参数(指定密钥)
* *
* @param encryptedAuth 加密后的认证参数字符串 * @param encryptedAuth 加密后的认证参数字符串
* @param key AES密钥(16位) * @param key AES 密钥(16、24 或 32 个 UTF-8 字节)
* @return AuthParam 对象,解码失败返回 null * @return AuthParam 对象,解码失败返回 null
*/ */
public static AuthParam decode(String encryptedAuth, String key) { public static AuthParam decode(String encryptedAuth, String key) {
@@ -85,15 +112,13 @@ public class AuthParamCodec {
} }
// 兼容 query 参数中 '+' 被还原为空格的情况 // 兼容 query 参数中 '+' 被还原为空格的情况
normalized = normalized.replace(' ', '+'); normalized = normalized.replace(' ', '+');
log.debug("认证参数规范化结果: {}", normalized);
// Step 2: Base64解码 // Step 2: Base64解码
byte[] base64Decoded = Base64Decoder.decode(normalized); byte[] base64Decoded = Base64Decoder.decode(normalized);
log.debug("Base64解码成功,长度: {}", base64Decoded.length); log.debug("Base64解码成功,长度: {}", base64Decoded.length);
// Step 3: AES解密 // Step 3: AES解密
String jsonStr = AESUtils.decryptByAES(base64Decoded, key); String jsonStr = AESUtils.decryptByAES(base64Decoded, asAesKey(key));
log.debug("AES解密结果: {}", jsonStr);
// Step 4: JSON解析 // Step 4: JSON解析
JsonObject json = new JsonObject(jsonStr); JsonObject json = new JsonObject(jsonStr);
@@ -102,9 +127,9 @@ public class AuthParamCodec {
return authParam; return authParam;
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
log.warn("认证参数Base64解码失败: {}", e.getMessage()); log.warn("认证参数格式无效");
} catch (Exception e) { } catch (Exception e) {
log.warn("认证参数解码失败: {}", e.getMessage()); log.warn("认证参数解码失败");
} }
return null; return null;
} }
@@ -124,7 +149,7 @@ public class AuthParamCodec {
* 编码认证参数(指定密钥) * 编码认证参数(指定密钥)
* *
* @param authParam 认证参数对象 * @param authParam 认证参数对象
* @param key AES密钥(16位) * @param key AES 密钥(16、24 或 32 个 UTF-8 字节)
* @return 加密后的字符串,编码失败返回 null * @return 加密后的字符串,编码失败返回 null
*/ */
public static String encode(AuthParam authParam, String key) { public static String encode(AuthParam authParam, String key) {
@@ -135,15 +160,12 @@ public class AuthParamCodec {
try { try {
// Step 1: 转换为JSON // Step 1: 转换为JSON
String jsonStr = authParam.toJsonObject().encode(); String jsonStr = authParam.toJsonObject().encode();
log.debug("JSON字符串: {}", jsonStr);
// Step 2: AES加密 + Base64编码 // Step 2: AES加密 + Base64编码
String base64Encoded = AESUtils.encryptBase64ByAES(jsonStr, key); String base64Encoded = AESUtils.encryptBase64ByAES(jsonStr, asAesKey(key));
log.debug("AES+Base64编码结果: {}", base64Encoded);
// Step 3: URL编码 // Step 3: URL编码
String urlEncoded = java.net.URLEncoder.encode(base64Encoded, StandardCharsets.UTF_8); String urlEncoded = java.net.URLEncoder.encode(base64Encoded, StandardCharsets.UTF_8);
log.debug("URL编码结果: {}", urlEncoded);
return urlEncoded; return urlEncoded;
@@ -6,6 +6,7 @@ import cn.qaiu.lz.web.service.DbService;
import cn.qaiu.parser.ParserCreate; import cn.qaiu.parser.ParserCreate;
import cn.qaiu.vx.core.util.ConfigConstant; import cn.qaiu.vx.core.util.ConfigConstant;
import cn.qaiu.vx.core.util.VertxHolder; import cn.qaiu.vx.core.util.VertxHolder;
import cn.qaiu.vx.core.util.SharedDataUtil;
import io.vertx.core.Future; import io.vertx.core.Future;
import io.vertx.core.MultiMap; import io.vertx.core.MultiMap;
import io.vertx.core.http.HttpServerRequest; import io.vertx.core.http.HttpServerRequest;
@@ -88,7 +89,7 @@ public class ParserAuthUtil {
public static void recordDonatedAccountFailureIfNeeded(DbService dbService, JsonObject otherParam, public static void recordDonatedAccountFailureIfNeeded(DbService dbService, JsonObject otherParam,
Throwable cause) { Throwable cause) {
if (!isLikelyAuthFailure(cause) || otherParam == null) { if (otherParam == null || !isLikelyAuthFailure(cause) || !isDonatedAccountsEnabled()) {
return; return;
} }
String donatedAccountToken = otherParam.getString("donatedAccountToken"); String donatedAccountToken = otherParam.getString("donatedAccountToken");
@@ -101,7 +102,7 @@ public class ParserAuthUtil {
public static void recordAutoDonatedFailureIfNeeded(DbService dbService, ShareLinkInfo shareLinkInfo, public static void recordAutoDonatedFailureIfNeeded(DbService dbService, ShareLinkInfo shareLinkInfo,
Throwable cause) { Throwable cause) {
if (shareLinkInfo == null || !isLikelyAuthFailure(cause)) { if (shareLinkInfo == null || !isLikelyAuthFailure(cause) || !isDonatedAccountsEnabled()) {
return; return;
} }
Object tokenObj = shareLinkInfo.getOtherParam().get(DONATED_ACCOUNT_TOKEN); Object tokenObj = shareLinkInfo.getOtherParam().get(DONATED_ACCOUNT_TOKEN);
@@ -112,14 +113,31 @@ public class ParserAuthUtil {
.onFailure(e -> log.warn("记录自动捐赠账号失败次数失败", e)); .onFailure(e -> log.warn("记录自动捐赠账号失败次数失败", e));
} }
public static boolean isDonatedAccountsEnabled() {
return isDonatedAccountsEnabled(SharedDataUtil.getJsonConfig(ConfigConstant.SERVER));
}
static boolean isDonatedAccountsEnabled(JsonObject server) {
return server != null && Boolean.TRUE.equals(server.getValue("enableDonatedAccounts"))
&& Boolean.TRUE.equals(server.getValue("enableDatabase"));
}
// 只启用已检查解析结果不会携带捐赠账号下载请求头的网盘。
public static boolean supportsServerSideDonation(String type) {
return "ye".equalsIgnoreCase(type) || "fj".equalsIgnoreCase(type) || "iz".equalsIgnoreCase(type);
}
private static Future<Void> applyDonatedAccountFallback(ParserCreate parserCreate, DbService dbService) { private static Future<Void> applyDonatedAccountFallback(ParserCreate parserCreate, DbService dbService) {
if (!isDonatedAccountsEnabled()) {
return Future.succeededFuture();
}
ShareLinkInfo shareLinkInfo = parserCreate.getShareLinkInfo(); ShareLinkInfo shareLinkInfo = parserCreate.getShareLinkInfo();
Map<String, Object> otherParam = shareLinkInfo.getOtherParam(); Map<String, Object> otherParam = shareLinkInfo.getOtherParam();
if (Boolean.TRUE.equals(otherParam.get(TEMP_AUTH_ADDED))) { if (Boolean.TRUE.equals(otherParam.get(TEMP_AUTH_ADDED))) {
return Future.succeededFuture(); return Future.succeededFuture();
} }
String type = shareLinkInfo.getType(); String type = shareLinkInfo.getType();
if (StringUtils.isBlank(type) || hasUsableStaticAuthConfig(type)) { if (!supportsServerSideDonation(type) || hasUsableStaticAuthConfig(type)) {
return Future.succeededFuture(); return Future.succeededFuture();
} }
return dbService.getRandomDonatedAccount(type.toUpperCase()) return dbService.getRandomDonatedAccount(type.toUpperCase())
@@ -770,11 +770,18 @@ public class ParserApi {
*/ */
@RouteMapping(value = "/donateAccount", method = RouteMethod.POST) @RouteMapping(value = "/donateAccount", method = RouteMethod.POST)
public Future<JsonObject> donateAccount(RoutingContext ctx) { public Future<JsonObject> donateAccount(RoutingContext ctx) {
if (!ParserAuthUtil.isDonatedAccountsEnabled()) {
return Future.succeededFuture(JsonResult.error("捐赠账号功能未启用").toJsonObject());
}
JsonObject body = ctx.body().asJsonObject(); JsonObject body = ctx.body().asJsonObject();
if (body == null || StringUtils.isBlank(body.getString("panType")) if (body == null || StringUtils.isBlank(body.getString("panType"))
|| StringUtils.isBlank(body.getString("authType"))) { || StringUtils.isBlank(body.getString("authType"))) {
return Future.succeededFuture(JsonResult.error("panType and authType are required").toJsonObject()); return Future.succeededFuture(JsonResult.error("panType and authType are required").toJsonObject());
} }
if (!ParserAuthUtil.supportsServerSideDonation(body.getString("panType"))) {
return Future.succeededFuture(JsonResult.error("该网盘暂不支持服务端捐赠池").toJsonObject());
}
body.put("panType", body.getString("panType").toUpperCase(java.util.Locale.ROOT));
String ip = ctx.request().remoteAddress().host(); String ip = ctx.request().remoteAddress().host();
body.put("ip", ip); body.put("ip", ip);
return dbService.saveDonatedAccount(body); return dbService.saveDonatedAccount(body);
@@ -785,23 +792,16 @@ public class ParserApi {
*/ */
@RouteMapping(value = "/donateAccountCounts", method = RouteMethod.GET) @RouteMapping(value = "/donateAccountCounts", method = RouteMethod.GET)
public Future<JsonObject> getDonateAccountCounts() { public Future<JsonObject> getDonateAccountCounts() {
return dbService.getDonatedAccountCounts(); if (!ParserAuthUtil.isDonatedAccountsEnabled()) {
} return Future.succeededFuture(JsonResult.data(new JsonObject().put("enabled", false)).toJsonObject());
}
/** return dbService.getDonatedAccountCounts().map(result -> {
* 随机获取指定网盘类型的捐赠账号(内部使用,返回加密后的 auth 参数) JsonObject data = result.getJsonObject("data");
*/ if (data != null) {
@RouteMapping(value = "/randomAuth", method = RouteMethod.GET) data.put("enabled", true);
public Future<JsonObject> getRandomAuth(String panType) {
return dbService.getRandomDonatedAccount(panType).map(res -> {
if (Integer.valueOf(200).equals(res.getInteger("code")) && res.getJsonObject("data") != null) {
JsonObject data = res.getJsonObject("data");
String encryptedAuth = AuthParamCodec.encode(data);
JsonObject safeData = new JsonObject();
safeData.put("encryptedAuth", encryptedAuth);
res.put("data", safeData);
} }
return res; return result;
}); });
} }
} }
@@ -39,7 +39,7 @@ public class DbServiceImpl implements DbService {
private static final long FAILURE_TOKEN_TTL_MILLIS = 10 * 60 * 1000L; private static final long FAILURE_TOKEN_TTL_MILLIS = 10 * 60 * 1000L;
private static final String HMAC_ALGORITHM = "HmacSHA256"; private static final String HMAC_ALGORITHM = "HmacSHA256";
private static final String DONATED_ACCOUNT_TOKEN_SIGN_KEY_CONFIG = "donatedAccountFailureTokenSignKey"; private static final String DONATED_ACCOUNT_TOKEN_SIGN_KEY_CONFIG = "donatedAccountFailureTokenSignKey";
private static final String DONATED_ACCOUNT_TOKEN_SIGN_KEY_FALLBACK = "nfd_donate_fail_token_sign_2026"; private static final String DONATED_ACCOUNT_TOKEN_SIGN_KEY_FALLBACK = java.util.UUID.randomUUID().toString() + java.util.UUID.randomUUID();
@Override @Override
public Future<JsonObject> sayOk(String data) { public Future<JsonObject> sayOk(String data) {
log.info("say ok1 -> wait..."); log.info("say ok1 -> wait...");
@@ -574,7 +574,7 @@ public class DbServiceImpl implements DbService {
return configKey; return configKey;
} }
} catch (Exception e) { } catch (Exception e) {
log.debug("读取捐赠账号失败计数签名密钥失败,使用默认值: {}", e.getMessage()); log.debug("读取捐赠账号失败计数签名密钥失败,使用进程随机值: {}", e.getMessage());
} }
return DONATED_ACCOUNT_TOKEN_SIGN_KEY_FALLBACK; return DONATED_ACCOUNT_TOKEN_SIGN_KEY_FALLBACK;
} }
+4 -2
View File
@@ -8,8 +8,10 @@ server:
# domainName: http://127.0.0.1:6401 # domainName: http://127.0.0.1:6401
# 预览服务URL # 预览服务URL
previewURL: https://nfd-parser.github.io/nfd-preview/preview.html?src= previewURL: https://nfd-parser.github.io/nfd-preview/preview.html?src=
# auth参数加密密钥(16位AES密钥) # 未配置时每次启动自动生成随机密钥;多实例或外部客户端可配置共享密钥。
authEncryptKey: 'nfd_auth_key2026' # authEncryptKey: ""
# 捐赠默认关闭;开启后凭据仅供服务端选用。
enableDonatedAccounts: false
# 反向代理服务器配置路径(不用加后缀) # 反向代理服务器配置路径(不用加后缀)
proxyConf: server-proxy proxyConf: server-proxy
@@ -5,6 +5,8 @@ import cn.qaiu.util.AESUtils;
import io.vertx.core.json.JsonObject; import io.vertx.core.json.JsonObject;
import org.junit.Test; import org.junit.Test;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
@@ -21,7 +23,64 @@ import static org.junit.Assert.*;
public class AuthParamCodecTest { public class AuthParamCodecTest {
// 测试用的固定密钥 // 测试用的固定密钥
private static final String TEST_KEY = "nfd_auth_key2026"; private static final String TEST_KEY = "dummy-test-key16";
@Test
public void usesOneRandomKeyPerProcessAndSupportsExplicitConfiguration() {
String generated = AuthParamCodec.selectKey(null);
assertEquals(32, generated.getBytes(StandardCharsets.UTF_8).length);
assertSame(generated, AuthParamCodec.selectKey(""));
assertSame(generated, AuthParamCodec.selectKey(" "));
assertNotEquals(AuthParamCodec.generateKey(), AuthParamCodec.generateKey());
assertEquals(TEST_KEY, AuthParamCodec.selectKey(TEST_KEY));
assertThrows(IllegalArgumentException.class, () -> AuthParamCodec.selectKey("invalid length"));
}
@Test
public void generatedKeyRoundTripsSyntheticAuth() {
AuthParam auth = AuthParam.builder().authType("token").token("synthetic-only").build();
String key = AuthParamCodec.selectKey(null);
assertEquals("synthetic-only",
AuthParamCodec.decode(AuthParamCodec.encode(auth, key), key).getToken());
}
@Test
public void interoperatesWithBrowserCryptoJsUsingFullUtf8Key() throws Exception {
// CryptoJS 4.2.0: AES-ECB/PKCS7, Utf8.parse(key),
// plaintext {"authType":"token","token":"synthetic-认证"}.
String[][] browserVectors = {
{"0123456789abcdef", "VxQ8JVsWso0Fhf76r82AjtWhuqKaDUtBWPUJcD+Oc1lGwDq001J2N8LJH3RSFBcA"},
{"0123456789abcdefghijklmn", "kCYuDyekW7KZf8rlLqIR0Rcwp7QWcFYn5X6tsGd6XUqlGf9RoJyFzogOgU26JJNS"},
{"0123456789abcdefghijklmnopqrstuv", "FB94nNibPhLIh+oMcnJW0Iuu3O3xSPK0WVHXCiwnvbblwSfe++oPk3RZmw6/7OqX"},
{"密钥测试甲乙丙丁", "cg0YzgNOQxws0chQxDOnepm1Ht+Pkgo7Am9McLXjkUcC35QcRiyHELm0/g4WQm2e"}
};
for (String[] vector : browserVectors) {
String key = vector[0];
AuthParam decoded = AuthParamCodec.decode(URLEncoder.encode(vector[1], StandardCharsets.UTF_8), key);
assertNotNull("browser ciphertext should decode with " + key.getBytes(StandardCharsets.UTF_8).length + "-byte key", decoded);
assertEquals("token", decoded.getAuthType());
assertEquals("synthetic-认证", decoded.getToken());
String encoded = AuthParamCodec.encode(decoded, key);
assertNotNull(encoded);
Cipher peer = Cipher.getInstance("AES/ECB/PKCS5Padding");
peer.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"));
String base64 = URLDecoder.decode(encoded, StandardCharsets.UTF_8);
JsonObject plaintext = new JsonObject(new String(peer.doFinal(Base64.getDecoder().decode(base64)), StandardCharsets.UTF_8));
assertEquals("synthetic-认证", plaintext.getString("token"));
}
}
@Test
public void donatedAccountsRequireExplicitOptInAndDatabase() {
JsonObject server = new JsonObject().put("enableDatabase", true);
assertFalse(ParserAuthUtil.isDonatedAccountsEnabled(server));
assertTrue(ParserAuthUtil.isDonatedAccountsEnabled(server.put("enableDonatedAccounts", true)));
assertFalse(ParserAuthUtil.isDonatedAccountsEnabled(server.put("enableDatabase", false)));
assertTrue(ParserAuthUtil.supportsServerSideDonation("YE"));
assertFalse(ParserAuthUtil.supportsServerSideDonation("QK"));
assertFalse(ParserAuthUtil.supportsServerSideDonation("UC"));
}
@Test @Test
public void testAuthParamModel() { public void testAuthParamModel() {
@@ -18,7 +18,7 @@ import java.util.Base64;
*/ */
public class AuthParamCodecTestMain { public class AuthParamCodecTestMain {
private static final String TEST_KEY = "nfd_auth_key2026"; private static final String TEST_KEY = "dummy-test-key16";
private static int passCount = 0; private static int passCount = 0;
private static int failCount = 0; private static int failCount = 0;
+7 -9
View File
@@ -214,7 +214,7 @@
<div class="info-box"> <div class="info-box">
<p><strong>加密算法:</strong> AES/ECB/PKCS5Padding</p> <p><strong>加密算法:</strong> AES/ECB/PKCS5Padding</p>
<p><strong>默认密钥:</strong> nfd_auth_key2026 (16位)</p> <p><strong>密钥:</strong> 自建服务配置的认证密钥(仅在可信本地环境使用)</p>
<p><strong>编码流程:</strong> JSON对象 → AES加密 → Base64编码 → URL编码</p> <p><strong>编码流程:</strong> JSON对象 → AES加密 → Base64编码 → URL编码</p>
</div> </div>
@@ -268,8 +268,8 @@
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="encryptKey">加密密钥 (可选,默认: nfd_auth_key2026)</label> <label for="encryptKey">加密密钥(必填)</label>
<input type="text" id="encryptKey" placeholder="留空使用默认密钥" value="nfd_auth_key2026"> <input type="password" id="encryptKey" autocomplete="off" placeholder="本地服务配置的密钥">
</div> </div>
<div class="button-group"> <div class="button-group">
@@ -368,7 +368,10 @@
// AES 加密 // AES 加密
try { try {
const encryptKey = document.getElementById('encryptKey').value.trim() || 'nfd_auth_key2026'; const encryptKey = document.getElementById('encryptKey').value;
if (![16, 24, 32].includes(new TextEncoder().encode(encryptKey).length)) {
throw new Error('密钥必须为 16、24 或 32 个 UTF-8 字节');
}
const encrypted = encryptAuthParam(JSON.stringify(authParam), encryptKey); const encrypted = encryptAuthParam(JSON.stringify(authParam), encryptKey);
document.getElementById('encryptedResult').textContent = encrypted; document.getElementById('encryptedResult').textContent = encrypted;
@@ -389,11 +392,6 @@
// AES 加密函数 // AES 加密函数
function encryptAuthParam(jsonString, key) { function encryptAuthParam(jsonString, key) {
// 确保密钥是16位
if (key.length !== 16) {
throw new Error('密钥必须是16位字符');
}
// AES 加密 (ECB 模式, PKCS5Padding) // AES 加密 (ECB 模式, PKCS5Padding)
const encrypted = CryptoJS.AES.encrypt( const encrypted = CryptoJS.AES.encrypt(
jsonString, jsonString,