XiaoDaiGua-Ray 403fdd589a feat!: rebuild Ray Template as a monorepo
Share workspace packages between Ray Admin and the interactive docs.

BREAKING CHANGE: v6 is a new major line. v5 stays on legacy/v5.
2026-11-04 14:01:28 +08:00

37 lines
1.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { AES, enc } from 'crypto-js'
import { CRYPTO_KEY } from './constant'
import type { CipherParams, WordArray } from './types'
/**
*
* @param data encrypt 返回的密文,或 CryptoJS CipherParams
* @param key 与加密时相同的口令或原始密钥
*
* @returns 解密后的 JSON;密文无法解析时记录错误并返回 undefined。
*/
export const decrypt = (
data: string | CipherParams,
key?: string | WordArray,
) => {
try {
if (typeof key === 'object') {
const parts =
typeof data === 'string' ? /^([a-f0-9]{32}):(.+)$/i.exec(data) : null
const iv =
typeof data === 'string' ? parts && enc.Hex.parse(parts[1]) : data.iv
if (!iv) throw new Error('Missing AES initialization vector.')
const decrypted = AES.decrypt(parts?.[2] ?? data, key, { iv })
return JSON.parse(decrypted.toString(enc.Utf8))
}
const decrypted = AES.decrypt(data, key || CRYPTO_KEY)
return JSON.parse(decrypted.toString(enc.Utf8))
} catch (error) {
console.error('[decrypt]: Invalid ciphertext or key.', error)
}
}