From 528456c168de41af7763a847f452dea5c7b872fb Mon Sep 17 00:00:00 2001 From: whoswhip Date: Thu, 5 Mar 2026 22:05:24 -0500 Subject: [PATCH] refactor(encryption): replace magic numbers with constants for improved readability and maintainability --- SharpbinV3.Client/src/lib/utils/encryption.ts | 58 +++++++++++-------- 1 file changed, 33 insertions(+), 25 deletions(-) diff --git a/SharpbinV3.Client/src/lib/utils/encryption.ts b/SharpbinV3.Client/src/lib/utils/encryption.ts index 6e5a3b8..ea67bd3 100644 --- a/SharpbinV3.Client/src/lib/utils/encryption.ts +++ b/SharpbinV3.Client/src/lib/utils/encryption.ts @@ -1,10 +1,21 @@ import { argon2id } from 'hash-wasm'; +const BASE64_CHUNK_SIZE = 0x8000; +const SALT_LENGTH = 16; +const IV_LENGTH = 12; +const ARGON2_MEMORY_SIZE = 262144; +const ARGON2_ITERATIONS = 3; +const ARGON2_PARALLELISM = 1; +const ARGON2_HASH_LENGTH = 32; +const AES_KEY_LENGTH = 256; +const ENCRYPTION_AAD = 'enc-v4'; +const ENCRYPTED_DATA_OVERHEAD = 60; +const ENCRYPTED_METADATA_OVERHEAD = 150; + function toBase64(bytes: Uint8Array): string { let binary = ''; - const chunkSize = 0x8000; - for (let i = 0; i < bytes.length; i += chunkSize) { - binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize)); + for (let i = 0; i < bytes.length; i += BASE64_CHUNK_SIZE) { + binary += String.fromCharCode(...bytes.subarray(i, i + BASE64_CHUNK_SIZE)); } return btoa(binary); } @@ -20,35 +31,32 @@ function fromBase64(data: string): Uint8Array { export async function encryptAES(content: string, password: string): Promise { const enc = new TextEncoder(); - const salt = window.crypto.getRandomValues(new Uint8Array(16)); - const memorySize = 262144; - const iterations = 3; - const parallelism = 1; + const salt = window.crypto.getRandomValues(new Uint8Array(SALT_LENGTH)); const keyMaterial = await argon2id({ password, salt, - iterations, - memorySize, - parallelism, - hashLength: 32, + iterations: ARGON2_ITERATIONS, + memorySize: ARGON2_MEMORY_SIZE, + parallelism: ARGON2_PARALLELISM, + hashLength: ARGON2_HASH_LENGTH, outputType: 'binary' }); const key = await window.crypto.subtle.importKey( 'raw', new Uint8Array(keyMaterial), - { name: 'AES-GCM', length: 256 }, + { name: 'AES-GCM', length: AES_KEY_LENGTH }, false, ['encrypt'] ); - const iv = window.crypto.getRandomValues(new Uint8Array(12)); + const iv = window.crypto.getRandomValues(new Uint8Array(IV_LENGTH)); const encryptedContent = await window.crypto.subtle.encrypt( { name: 'AES-GCM', iv, - additionalData: enc.encode('enc-v4') + additionalData: enc.encode(ENCRYPTION_AAD) }, key, enc.encode(content) @@ -62,9 +70,9 @@ export async function encryptAES(content: string, password: string): Promise { @@ -85,8 +93,8 @@ export async function decryptAES(result: string, password: string): Promise