88 lines
2.8 KiB
TypeScript
88 lines
2.8 KiB
TypeScript
/**
|
|
* crypto.ts — 严格 1:1 复刻 web cipher.ts (字节级一致)
|
|
*
|
|
* 流程: 明文 → md5(hex) → AES-ECB-Pkcs7(key=md5(VITE_CIPHER_KEY)) → Base64 → Hex
|
|
*
|
|
* 关键: cipher.ts:34-37 `Hex.stringify(Base64.parse(result))` 是对 Base64 字符串做 hex,
|
|
* 不是对密文字节做 hex。这是 ddcc 实验里踩过的最大坑。
|
|
*
|
|
* 输入 '123456' 应输出 96 字符 hex (与 web 一致)。
|
|
*/
|
|
import CryptoJS from 'crypto-js'
|
|
import { existsSync, readFileSync } from 'node:fs'
|
|
import { dirname, resolve } from 'node:path'
|
|
import { fileURLToPath } from 'node:url'
|
|
|
|
/** 默认密钥来自 web .env VITE_CIPHER_KEY */
|
|
const FALLBACK_KEY = 'EY8WePvjM5GGwQzn'
|
|
|
|
let _cipherKey: string | null = null
|
|
|
|
function loadCipherKey(): string {
|
|
if (_cipherKey) return _cipherKey
|
|
if (process.env.VITE_CIPHER_KEY) {
|
|
_cipherKey = process.env.VITE_CIPHER_KEY
|
|
return _cipherKey
|
|
}
|
|
try {
|
|
const here = dirname(fileURLToPath(import.meta.url))
|
|
const candidates = [
|
|
resolve(here, '../../../../web/apps/jnpf-web-apps-main/.env'),
|
|
resolve(here, '../../../web/apps/jnpf-web-apps-main/.env'),
|
|
resolve(here, '../../web/apps/jnpf-web-apps-main/.env'),
|
|
]
|
|
for (const p of candidates) {
|
|
if (existsSync(p)) {
|
|
const m = readFileSync(p, 'utf-8').match(/VITE_CIPHER_KEY\s*=\s*(\S+)/)
|
|
if (m) {
|
|
_cipherKey = m[1]
|
|
return _cipherKey
|
|
}
|
|
}
|
|
}
|
|
} catch {
|
|
/* ignore — fallback */
|
|
}
|
|
_cipherKey = FALLBACK_KEY
|
|
return _cipherKey
|
|
}
|
|
|
|
export function encryptByMd5(plain: string): string {
|
|
return CryptoJS.MD5(plain).toString()
|
|
}
|
|
|
|
/** AES-ECB-Pkcs7(密钥=md5(CIPHER_KEY)),再 Base64→Hex */
|
|
function aesEcbHex(inputHex: string): string {
|
|
const aesKey = encryptByMd5(loadCipherKey())
|
|
const encrypted = CryptoJS.AES.encrypt(
|
|
inputHex,
|
|
CryptoJS.enc.Utf8.parse(aesKey),
|
|
{ mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 },
|
|
)
|
|
const base64 = encrypted.toString()
|
|
// 注意: 是对 base64 字符串做 hex (web cipher.ts:36)
|
|
return CryptoJS.enc.Hex.stringify(CryptoJS.enc.Base64.parse(base64))
|
|
}
|
|
|
|
/**
|
|
* 完整登录加密 (与 LoginForm.handleLogin 一致):
|
|
* md5(plain) → aesEncryption.encryptByAES(md5Hex)
|
|
*/
|
|
export function encryptPassword(plain: string): string {
|
|
return aesEcbHex(encryptByMd5(plain))
|
|
}
|
|
|
|
/**
|
|
* 纯 AES-ECB-Pkcs7 加密 (供数据源密码等场景, web Form.vue: handleSubmit 中:
|
|
* password: aesEncryption.encryptByAES(values.password)
|
|
* 流程: AES-ECB-Pkcs7(key=md5(CIPHER_KEY), data=plain) → Base64 → Hex
|
|
*/
|
|
export function encryptAesEcb(plain: string): string {
|
|
return aesEcbHex(plain)
|
|
}
|
|
|
|
/** 96 字符的 hex 即认为已加密 */
|
|
export function isEncrypted(p: string | undefined | null): boolean {
|
|
return !!p && p.length === 96 && /^[0-9a-f]+$/i.test(p)
|
|
}
|