🔨 Refactor(custom): refactor encrypt class

This commit is contained in:
Kuingsmile 2024-04-18 17:31:37 +08:00
parent 0f7b043da3
commit 2fab2a9765

View File

@ -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 {
export class AESHelper {
key: Buffer
constructor () {
const userPassword = picgo.getConfig<string>(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()
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')