chore: encrypt

Signed-off-by: Innei <i@innei.in>
This commit is contained in:
Innei
2024-09-02 18:49:29 +08:00
parent b48b764396
commit a906ee6780
3 changed files with 64 additions and 8 deletions

View File

@@ -19,6 +19,7 @@
"build": "nest build",
"build:webpack": "nest build --webpack --webpackPath ./configs/webpack.config.js -c ./configs/nest-cli.webpack.json",
"dev": "npm run start",
"dev:encrypt": "npm run start -- --encrypt_enable --encrypt_key=33b9405ac49f63ef4ccbf6b338aeeff8152e844d942ef22278abbec2b1f93b5e",
"repl": "npm run start -- --entryFile repl",
"bundle": "rimraf out && npm run build && cd dist/src && npx ncc build main.js -o ../../out --minify -s && cd ../.. && chmod +x out/index.js && node scripts/after-bundle.js",
"start": "cross-env NODE_ENV=development nest start -w --path tsconfig.json -- ",
@@ -169,4 +170,4 @@
"vitest": "1.5.2",
"zx": "7.2.3"
}
}
}

View File

@@ -55,10 +55,18 @@ export const encryptObject = (target: any) => {
const keys = Object.keys(target)
for (const key of keys) {
const value = target[key]
if (isObject(value) && !isArrayLike(value)) {
// 前置判断 整个 Object 都是被加密的
if (
isObject(value) &&
!isArrayLike(value) &&
!isEncryptProperty(target, key)
) {
target[key] = encryptObject(value)
continue
}
target[key] = encryptProperty(target, key, target[key])
}
return target

View File

@@ -34,10 +34,7 @@ export class EncryptUtil {
private static key = Buffer.from(mapString(ENCRYPT.key), 'hex')
private static algorithm = ENCRYPT.algorithm || 'aes-256-ecb'
public static encrypt(data: string): string {
if (!ENCRYPT.enable) {
return data
}
private static encryptString = (data: string) => {
if (EncryptUtil.isEncryptedString(data)) {
return data
}
@@ -59,20 +56,70 @@ export class EncryptUtil {
return EncryptUtil.encryptStringPadding + cipherChunks.join('')
}
public static encrypt<T>(data: T): T {
if (!ENCRYPT.enable) {
return data
}
switch (typeof data) {
case 'string': {
return EncryptUtil.encryptString(data) as T
}
case 'object': {
if (!data) {
return data
}
if (Array.isArray(data)) {
return data.map((item) => EncryptUtil.encrypt(item)) as T
}
const result = {} as T
for (const key in data) {
result[key] = EncryptUtil.encrypt(data[key])
}
return result
}
default:
return data
}
}
public static isEncryptedString(data: string) {
return data.startsWith(EncryptUtil.encryptStringPadding)
}
public static decrypt(data: string): string {
public static decrypt<T>(data: T): T {
if (!ENCRYPT.enable) {
return data
}
if (!data) {
return ''
return data
}
switch (typeof data) {
case 'string': {
return EncryptUtil.decryptString(data) as T
}
case 'object': {
if (Array.isArray(data)) {
return data.map((item) => EncryptUtil.decrypt(item)) as T
}
const result = {} as T
for (const key in data) {
result[key] = EncryptUtil.decrypt(data[key])
}
return result
}
default:
return data
}
}
private static decryptString(data: string): string {
if (!EncryptUtil.isEncryptedString(data)) {
return data
}