Skip to content

Commit

Permalink
fix(encrypt.ts): update crypto.scryptSync to use Buffer.from for key …
Browse files Browse the repository at this point in the history
…encryption

feat(encrypt.ts): refactor encryptString and decryptString methods to use base64 encoding for better compatibility
fix(encrypt.ts): improve error handling in isEncrypted method by returning false on invalid input
  • Loading branch information
anpigon committed Jun 27, 2024
1 parent dd580e3 commit 486d1f1
Showing 1 changed file with 12 additions and 13 deletions.
25 changes: 12 additions & 13 deletions src/helpers/encrypt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@ export default class Encrypt {
if (!key) {
throw new Error('No encryption key is set.');
}
return crypto.scryptSync(key, 'salt', 32);
return Buffer.from(key);
}

static encryptString(text: string) {
try {
const iv = crypto.randomBytes(this.IV_LENGTH);
const cipher = crypto.createCipheriv(this.ALGORITHM, this.getEncryptionKey(), iv);
const encrypted = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()]);
return `${iv.toString('hex')}:${encrypted.toString('hex')}`;
const encrypted = cipher.update(text, 'utf8', 'base64');
return `${iv.toString('base64')}:${encrypted}${cipher.final('base64')}`;
} catch (error) {
// eslint-disable-next-line no-console
console.error('Error encrypting:', error);
Expand All @@ -27,15 +27,14 @@ export default class Encrypt {

static decryptString(text: string): string {
try {
const [ivHex, encryptedHex] = text.split(':');
if (!ivHex || !encryptedHex) {
throw new Error('잘못된 형식의 암호화된 문자열입니다.');
const [textParts, encryptedText] = text.split(':');
if (!textParts || !encryptedText) {
throw new Error('An invalidly formatted encrypted string.');
}
const iv = Buffer.from(ivHex, 'hex');
const encrypted = Buffer.from(encryptedHex, 'hex');
const iv = Buffer.from(textParts, 'base64');
const decipher = crypto.createDecipheriv(this.ALGORITHM, this.getEncryptionKey(), iv);
const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]);
return decrypted.toString('utf8');
const decrypted = decipher.update(encryptedText, 'base64', 'utf8');
return decrypted + decipher.final('utf8');
} catch (error) {
// eslint-disable-next-line no-console
console.error('Error decrypting:', error);
Expand All @@ -46,17 +45,17 @@ export default class Encrypt {
static isEncrypted(value: string): boolean {
const parts = value.split(':');
if (parts.length !== 2) return false;

const [ivHex, encryptedHex] = parts;
if (ivHex.length !== this.IV_LENGTH * 2) return false;

try {
Buffer.from(ivHex, 'hex');
Buffer.from(encryptedHex, 'hex');
} catch {
return false;
}

return true;
}
}

0 comments on commit 486d1f1

Please sign in to comment.