'use strict'; /** * RSA-OAEP (SHA-256) + AES-256-GCM hybrid encryption helpers. * * The server generates a 2048-bit RSA key pair once on startup and stores it * under ./keys/. All login credential decryption and token encryption use * these routines. * * Hybrid scheme (encrypt): * 1. Generate random 256-bit AES key + 96-bit IV. * 2. Encrypt plaintext with AES-256-GCM → ciphertext + 128-bit auth tag. * 3. Encrypt AES key with RSA-OAEP (SHA-256) → encryptedKey. * 4. Return { encryptedKey, iv, ciphertext, tag } all base64-encoded. * * Hybrid scheme (decrypt): * 1. Decrypt AES key with RSA private key. * 2. Decrypt ciphertext with AES-256-GCM. */ const crypto = require('crypto'); const fs = require('fs'); const path = require('path'); const KEYS_DIR = path.join(__dirname, '../keys'); const PRIV_KEY_PATH = path.join(KEYS_DIR, 'server.key'); const PUB_KEY_PATH = path.join(KEYS_DIR, 'server.pub'); let _serverPrivateKey = null; let _serverPublicKey = null; // --------------------------------------------------------------------------- // Key management // --------------------------------------------------------------------------- function ensureServerKeys() { if (!fs.existsSync(KEYS_DIR)) { fs.mkdirSync(KEYS_DIR, { recursive: true }); } if (fs.existsSync(PRIV_KEY_PATH) && fs.existsSync(PUB_KEY_PATH)) { _serverPrivateKey = fs.readFileSync(PRIV_KEY_PATH, 'utf8'); _serverPublicKey = fs.readFileSync(PUB_KEY_PATH, 'utf8'); console.log('Server RSA keys loaded.'); return; } console.log('Generating server RSA key pair (2048-bit) …'); const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048, publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem' }, }); fs.writeFileSync(PRIV_KEY_PATH, privateKey, { mode: 0o600 }); fs.writeFileSync(PUB_KEY_PATH, publicKey); _serverPrivateKey = privateKey; _serverPublicKey = publicKey; console.log('Server RSA key pair generated and saved.'); } function getServerPublicKeyPem() { return _serverPublicKey; } /** * Returns the server public key as a JWK object (for the browser's * SubtleCrypto.importKey({ format: 'jwk' }) call). */ function getServerPublicKeyJwk() { const keyObj = crypto.createPublicKey(_serverPublicKey); return keyObj.export({ format: 'jwk' }); } // --------------------------------------------------------------------------- // Hybrid decrypt (server receives encrypted payload from client) // --------------------------------------------------------------------------- /** * payload: { encryptedKey, iv, ciphertext, tag } — all base64 strings * Returns the decrypted plaintext string. */ function hybridDecrypt(payload) { const encryptedKey = Buffer.from(payload.encryptedKey, 'base64'); const iv = Buffer.from(payload.iv, 'base64'); const ciphertext = Buffer.from(payload.ciphertext, 'base64'); const tag = Buffer.from(payload.tag, 'base64'); // 1. Decrypt AES key with server RSA private key const aesKey = crypto.privateDecrypt( { key: _serverPrivateKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha256', }, encryptedKey, ); // 2. Decrypt ciphertext with AES-256-GCM const decipher = crypto.createDecipheriv('aes-256-gcm', aesKey, iv); decipher.setAuthTag(tag); const plain = Buffer.concat([decipher.update(ciphertext), decipher.final()]); return plain.toString('utf8'); } // --------------------------------------------------------------------------- // Hybrid encrypt (server sends encrypted payload to client) // --------------------------------------------------------------------------- /** * Encrypts `plaintext` (string) for the recipient identified by their RSA * public key in JWK format. * Returns { encryptedKey, iv, ciphertext, tag } — all base64 strings. */ function hybridEncryptForClient(plaintext, clientPublicKeyJwk) { // Import client public key const clientPubKey = crypto.createPublicKey({ key: clientPublicKeyJwk, format: 'jwk' }); // 1. Generate random AES-256 key + IV const aesKey = crypto.randomBytes(32); const iv = crypto.randomBytes(12); // 2. Encrypt plaintext with AES-256-GCM const cipher = crypto.createCipheriv('aes-256-gcm', aesKey, iv); const ciphertext = Buffer.concat([ cipher.update(Buffer.from(plaintext, 'utf8')), cipher.final(), ]); const tag = cipher.getAuthTag(); // 3. Encrypt AES key with client's RSA public key const encryptedKey = crypto.publicEncrypt( { key: clientPubKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha256', }, aesKey, ); return { encryptedKey: encryptedKey.toString('base64'), iv: iv.toString('base64'), ciphertext: ciphertext.toString('base64'), tag: tag.toString('base64'), }; } module.exports = { ensureServerKeys, getServerPublicKeyPem, getServerPublicKeyJwk, hybridDecrypt, hybridEncryptForClient, };