From 2fab2a97652bf0f9939d591484cdb05ef755dcc2 Mon Sep 17 00:00:00 2001 From: Kuingsmile Date: Thu, 18 Apr 2024 17:31:37 +0800 Subject: [PATCH] :hammer: Refactor(custom): refactor encrypt class --- src/main/utils/aesHelper.ts | 25 ++++++++++--------------- 1 file changed, 10 insertions(+), 15 deletions(-) diff --git a/src/main/utils/aesHelper.ts b/src/main/utils/aesHelper.ts index 6a1c4cd..a974f80 100644 --- a/src/main/utils/aesHelper.ts +++ b/src/main/utils/aesHelper.ts @@ -3,18 +3,15 @@ import picgo from '@core/picgo' import { DEFAULT_AES_PASSWORD } from '~/universal/utils/static' import { configPaths } from '~/universal/utils/configPaths' -function getDerivedKey (): Buffer { - const userPassword = picgo.getConfig(configPaths.settings.aesPassword) || DEFAULT_AES_PASSWORD - const fixedSalt = Buffer.from('a8b3c4d2e4f5098712345678feedc0de', 'hex') - const fixedIterations = 100000 - const keyLength = 32 - return crypto.pbkdf2Sync(userPassword, fixedSalt, fixedIterations, keyLength, 'sha512') -} - export class AESHelper { key: Buffer + constructor () { - this.key = getDerivedKey() + const userPassword = picgo.getConfig(configPaths.settings.aesPassword) || DEFAULT_AES_PASSWORD + const fixedSalt = Buffer.from('a8b3c4d2e4f5098712345678feedc0de', 'hex') + const fixedIterations = 100000 + const keyLength = 32 + this.key = crypto.pbkdf2Sync(userPassword, fixedSalt, fixedIterations, keyLength, 'sha512') } encrypt (plainText: string) { @@ -22,17 +19,15 @@ export class AESHelper { const cipher = crypto.createCipheriv('aes-256-cbc', this.key, iv) let encrypted = cipher.update(plainText, 'utf8', 'hex') encrypted += cipher.final('hex') - const encryptedData = `${iv.toString('hex')}:${encrypted}` - return encryptedData + return `${iv.toString('hex')}:${encrypted}` } decrypt (encryptedData: string) { - const parts = encryptedData.split(':') - if (parts.length !== 2) { + const [ivHex, encryptedText] = encryptedData.split(':') + if (!ivHex || !encryptedText) { return '{}' } - const iv = Buffer.from(parts[0], 'hex') - const encryptedText = parts[1] + const iv = Buffer.from(ivHex, 'hex') const decipher = crypto.createDecipheriv('aes-256-cbc', this.key, iv) let decrypted = decipher.update(encryptedText, 'hex', 'utf8') decrypted += decipher.final('utf8')