Skip to content

Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.

Refactor: API Key encryption

Khuram Niazfe5584f8f427
diff --git a/src/lib/encryption.ts b/src/lib/encryption.ts
index 9d1334b..8d1ad0e 100644
--- a/src/lib/encryption.ts
+++ b/src/lib/encryption.ts
@@ -11,19 +11,22 @@ const ALGORITHM = "aes-256-gcm";
const IV_LENGTH = 12;
const AUTH_TAG_LENGTH = 16;
const KEY_LENGTH = 32;
+const SALT_LENGTH = 16;
const PBKDF2_ITERATIONS = 100_000;
-const SALT = "jobsync-api-key-encryption";
+// Fallback for decrypting records created before per-record random salts
+const LEGACY_SALT = "jobsync-api-key-encryption";
-function getDerivedKey(): Buffer {
+function getDerivedKey(salt: string | Buffer): Buffer {
const secret = process.env.ENCRYPTION_KEY;
if (!secret) {
throw new Error("ENCRYPTION_KEY is not set");
}
- return pbkdf2Sync(secret, SALT, PBKDF2_ITERATIONS, KEY_LENGTH, "sha256");
+ return pbkdf2Sync(secret, salt, PBKDF2_ITERATIONS, KEY_LENGTH, "sha256");
}
export function encrypt(plaintext: string): { encrypted: string; iv: string } {
- const key = getDerivedKey();
+ const salt = randomBytes(SALT_LENGTH);
+ const key = getDerivedKey(salt);
const iv = randomBytes(IV_LENGTH);
const cipher = createCipheriv(ALGORITHM, key, iv, {
authTagLength: AUTH_TAG_LENGTH,
@@ -33,7 +36,6 @@ export function encrypt(plaintext: string): { encrypted: string; iv: string } {
encrypted += cipher.final("base64");
const authTag = cipher.getAuthTag();
- // Append auth tag to encrypted data
const combined = Buffer.concat([
Buffer.from(encrypted, "base64"),
authTag,
@@ -41,16 +43,27 @@ export function encrypt(plaintext: string): { encrypted: string; iv: string } {
return {
encrypted: combined,
- iv: iv.toString("base64"),
+ iv: `${salt.toString("base64")}.${iv.toString("base64")}`,
};
}
export function decrypt(encryptedData: string, iv: string): string {
- const key = getDerivedKey();
- const ivBuffer = Buffer.from(iv, "base64");
+ let salt: string | Buffer;
+ let ivBase64: string;
+
+ if (iv.includes(".")) {
+ const [saltPart, ivPart] = iv.split(".");
+ salt = Buffer.from(saltPart, "base64");
+ ivBase64 = ivPart;
+ } else {
+ salt = LEGACY_SALT;
+ ivBase64 = iv;
+ }
+
+ const key = getDerivedKey(salt);
+ const ivBuffer = Buffer.from(ivBase64, "base64");
const combined = Buffer.from(encryptedData, "base64");
- // Extract auth tag from end of combined data
const authTag = combined.subarray(combined.length - AUTH_TAG_LENGTH);
const encrypted = combined.subarray(0, combined.length - AUTH_TAG_LENGTH);