BlueGit

timfa filemanager

Files

filemanager / server / crypto.js

crypto.js

import project
timfa Tim Falken · pushed by timfa · 6 months ago
d3c0b911 History
crypto.js 5.0 KiB Download Raw
1'use strict';
2
3/**
4 * RSA-OAEP (SHA-256) + AES-256-GCM hybrid encryption helpers.
5 *
6 * The server generates a 2048-bit RSA key pair once on startup and stores it
7 * under ./keys/. All login credential decryption and token encryption use
8 * these routines.
9 *
10 * Hybrid scheme (encrypt):
11 * 1. Generate random 256-bit AES key + 96-bit IV.
12 * 2. Encrypt plaintext with AES-256-GCM → ciphertext + 128-bit auth tag.
13 * 3. Encrypt AES key with RSA-OAEP (SHA-256) → encryptedKey.
14 * 4. Return { encryptedKey, iv, ciphertext, tag } all base64-encoded.
15 *
16 * Hybrid scheme (decrypt):
17 * 1. Decrypt AES key with RSA private key.
18 * 2. Decrypt ciphertext with AES-256-GCM.
19 */
20
21const crypto = require('crypto');
22const fs = require('fs');
23const path = require('path');
24
25const KEYS_DIR = path.join(__dirname, '../keys');
26const PRIV_KEY_PATH = path.join(KEYS_DIR, 'server.key');
27const PUB_KEY_PATH = path.join(KEYS_DIR, 'server.pub');
28
29let _serverPrivateKey = null;
30let _serverPublicKey = null;
31
32// ---------------------------------------------------------------------------
33// Key management
34// ---------------------------------------------------------------------------
35
36function ensureServerKeys() {
37 if (!fs.existsSync(KEYS_DIR)) {
38 fs.mkdirSync(KEYS_DIR, { recursive: true });
39 }
40
41 if (fs.existsSync(PRIV_KEY_PATH) && fs.existsSync(PUB_KEY_PATH)) {
42 _serverPrivateKey = fs.readFileSync(PRIV_KEY_PATH, 'utf8');
43 _serverPublicKey = fs.readFileSync(PUB_KEY_PATH, 'utf8');
44 console.log('Server RSA keys loaded.');
45 return;
46 }
47
48 console.log('Generating server RSA key pair (2048-bit) …');
49 const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
50 modulusLength: 2048,
51 publicKeyEncoding: { type: 'spki', format: 'pem' },
52 privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
53 });
54
55 fs.writeFileSync(PRIV_KEY_PATH, privateKey, { mode: 0o600 });
56 fs.writeFileSync(PUB_KEY_PATH, publicKey);
57
58 _serverPrivateKey = privateKey;
59 _serverPublicKey = publicKey;
60 console.log('Server RSA key pair generated and saved.');
61}
62
63function getServerPublicKeyPem() {
64 return _serverPublicKey;
65}
66
67/**
68 * Returns the server public key as a JWK object (for the browser's
69 * SubtleCrypto.importKey({ format: 'jwk' }) call).
70 */
71function getServerPublicKeyJwk() {
72 const keyObj = crypto.createPublicKey(_serverPublicKey);
73 return keyObj.export({ format: 'jwk' });
74}
75
76// ---------------------------------------------------------------------------
77// Hybrid decrypt (server receives encrypted payload from client)
78// ---------------------------------------------------------------------------
79
80/**
81 * payload: { encryptedKey, iv, ciphertext, tag } — all base64 strings
82 * Returns the decrypted plaintext string.
83 */
84function hybridDecrypt(payload) {
85 const encryptedKey = Buffer.from(payload.encryptedKey, 'base64');
86 const iv = Buffer.from(payload.iv, 'base64');
87 const ciphertext = Buffer.from(payload.ciphertext, 'base64');
88 const tag = Buffer.from(payload.tag, 'base64');
89
90 // 1. Decrypt AES key with server RSA private key
91 const aesKey = crypto.privateDecrypt(
92 {
93 key: _serverPrivateKey,
94 padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
95 oaepHash: 'sha256',
96 },
97 encryptedKey,
98 );
99
100 // 2. Decrypt ciphertext with AES-256-GCM
101 const decipher = crypto.createDecipheriv('aes-256-gcm', aesKey, iv);
102 decipher.setAuthTag(tag);
103
104 const plain = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
105 return plain.toString('utf8');
106}
107
108// ---------------------------------------------------------------------------
109// Hybrid encrypt (server sends encrypted payload to client)
110// ---------------------------------------------------------------------------
111
112/**
113 * Encrypts `plaintext` (string) for the recipient identified by their RSA
114 * public key in JWK format.
115 * Returns { encryptedKey, iv, ciphertext, tag } — all base64 strings.
116 */
117function hybridEncryptForClient(plaintext, clientPublicKeyJwk) {
118 // Import client public key
119 const clientPubKey = crypto.createPublicKey({ key: clientPublicKeyJwk, format: 'jwk' });
120
121 // 1. Generate random AES-256 key + IV
122 const aesKey = crypto.randomBytes(32);
123 const iv = crypto.randomBytes(12);
124
125 // 2. Encrypt plaintext with AES-256-GCM
126 const cipher = crypto.createCipheriv('aes-256-gcm', aesKey, iv);
127 const ciphertext = Buffer.concat([
128 cipher.update(Buffer.from(plaintext, 'utf8')),
129 cipher.final(),
130 ]);
131 const tag = cipher.getAuthTag();
132
133 // 3. Encrypt AES key with client's RSA public key
134 const encryptedKey = crypto.publicEncrypt(
135 {
136 key: clientPubKey,
137 padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
138 oaepHash: 'sha256',
139 },
140 aesKey,
141 );
142
143 return {
144 encryptedKey: encryptedKey.toString('base64'),
145 iv: iv.toString('base64'),
146 ciphertext: ciphertext.toString('base64'),
147 tag: tag.toString('base64'),
148 };
149}
150
151module.exports = {
152 ensureServerKeys,
153 getServerPublicKeyPem,
154 getServerPublicKeyJwk,
155 hybridDecrypt,
156 hybridEncryptForClient,
157};