diff --git a/src/lib/crypto-server.ts b/src/lib/crypto-server.ts index 237d31e..8ad695f 100644 --- a/src/lib/crypto-server.ts +++ b/src/lib/crypto-server.ts @@ -53,8 +53,9 @@ export function encrypt(plaintext: string): string { ]); const authTag = cipher.getAuthTag(); - // 格式: iv + authTag + encrypted - const combined = Buffer.concat([iv, authTag, encrypted]); + // 格式: iv + encrypted + authTag + // 与客户端 crypto.ts 的 decrypt 格式一致(Web Crypto API 将 authTag 附在 ciphertext 末尾) + const combined = Buffer.concat([iv, encrypted, authTag]); return combined.toString('base64'); } @@ -66,8 +67,8 @@ export function decrypt(encryptedBase64: string): string { const combined = Buffer.from(encryptedBase64, 'base64'); const iv = combined.subarray(0, IV_LENGTH); - const authTag = combined.subarray(IV_LENGTH, IV_LENGTH + AUTH_TAG_LENGTH); - const encrypted = combined.subarray(IV_LENGTH + AUTH_TAG_LENGTH); + const authTag = combined.subarray(combined.length - AUTH_TAG_LENGTH); + const encrypted = combined.subarray(IV_LENGTH, combined.length - AUTH_TAG_LENGTH); const decipher = crypto.createDecipheriv(ALGORITHM, key, iv); decipher.setAuthTag(authTag);