-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
325 lines (276 loc) · 10.4 KB
/
server.js
File metadata and controls
325 lines (276 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
require('dotenv').config();
const express = require('express');
const NodeRSA = require('node-rsa');
const app = express();
app.use(express.json());
// Constants matching Java code
const KEY_ALGORITHM = "RSA";
const SECURE_PADDING = "RSA/ECB/PKCS1Padding";
// Home page
app.get('/', (req, res) => {
res.send(`
<html>
<head><title>Crypto Service</title></head>
<body>
<h1>Crypto Service is running!</h1>
<p>Available endpoints:</p>
<ul>
<li>POST /encrypt</li>
<li>POST /sign</li>
<li>POST /decrypt</li>
<li>POST /verify</li>
<li>POST /headers (for Postman - SecureToken & Signature)</li>
</ul>
<p>Port: ${PORT}</p>
</body>
</html>
`);
});
// Health check
app.get('/health', (req, res) => {
res.json({ status: 'ok', service: 'crypto-service' });
});
// Helper function to create RSA key from base64
function createKeyFromBase64(keyBase64, isPrivate = false) {
try {
// Remove any whitespace or newlines
const cleanKey = keyBase64.replace(/\s+/g, '');
if (isPrivate) {
// For private key (PKCS#8 format)
const key = new NodeRSA();
key.importKey(Buffer.from(cleanKey, 'base64'), 'pkcs8-der-private');
return key;
} else {
// For public key (X.509/SPKI format)
const key = new NodeRSA();
key.importKey(Buffer.from(cleanKey, 'base64'), 'pkcs8-der-public');
return key;
}
} catch (error) {
throw new Error(`Failed to create RSA key: ${error.message}`);
}
}
// Encrypt with public key
app.post('/encrypt', (req, res) => {
try {
const { plainText, publicKey } = req.body;
if (!plainText || !publicKey) {
return res.json({
success: false,
encrypted: plainText || '',
error: 'Missing plainText or publicKey'
});
}
// Create RSA key from base64
const rsaKey = createKeyFromBase64(publicKey, false);
// Configure the key for PKCS1 padding (matches Java)
rsaKey.setOptions({ encryptionScheme: 'pkcs1' });
// Encrypt
const encrypted = rsaKey.encrypt(plainText, 'base64');
res.json({
success: true,
algorithm: KEY_ALGORITHM,
padding: SECURE_PADDING,
encrypted: encrypted
});
} catch (error) {
console.error('Encryption error:', error.message);
res.json({
success: false,
encrypted: req.body.plainText || '', // Fallback like Java
error: error.message
});
}
});
// Sign with private key
app.post('/sign', (req, res) => {
try {
const { plainText, privateKey } = req.body;
if (!plainText || !privateKey) {
return res.json({
success: false,
signature: null,
error: 'Missing plainText or privateKey'
});
}
// Create RSA key from base64
const rsaKey = createKeyFromBase64(privateKey, true);
// Sign with SHA256 (matches Java's SHA256withRSA)
// NodeRSA uses PSS padding by default, we need to change it to PKCS1 for Java compatibility
rsaKey.setOptions({ signingScheme: 'pkcs1-sha256' });
const signature = rsaKey.sign(plainText, 'base64', 'utf8');
res.json({
success: true,
algorithm: 'SHA256withRSA',
signature: signature
});
} catch (error) {
console.error('Signing error:', error.message);
res.json({
success: false,
signature: null, // Fallback like Java
error: error.message
});
}
});
// Decrypt with private key
app.post('/decrypt', (req, res) => {
try {
const { encryptedText, privateKey } = req.body;
if (!encryptedText || !privateKey) {
return res.json({
success: false,
decrypted: encryptedText || '',
error: 'Missing encryptedText or privateKey'
});
}
// Create RSA key from base64
const rsaKey = createKeyFromBase64(privateKey, true);
// Configure for PKCS1 padding
rsaKey.setOptions({ encryptionScheme: 'pkcs1' });
// Decrypt
const decrypted = rsaKey.decrypt(encryptedText, 'utf8');
res.json({
success: true,
algorithm: KEY_ALGORITHM,
padding: SECURE_PADDING,
decrypted: decrypted
});
} catch (error) {
console.error('Decryption error:', error.message);
res.json({
success: false,
decrypted: req.body.encryptedText || '', // Fallback like Java
error: error.message
});
}
});
// Verify signature
app.post('/verify', (req, res) => {
try {
const { plainText, signature, publicKey } = req.body;
if (!plainText || !signature || !publicKey) {
return res.json({
success: false,
valid: false,
error: 'Missing parameters'
});
}
// Create RSA key from base64
const rsaKey = createKeyFromBase64(publicKey, false);
// Configure for PKCS1-SHA256 verification
rsaKey.setOptions({ signingScheme: 'pkcs1-sha256' });
// Verify signature
const isValid = rsaKey.verify(plainText, signature, 'utf8', 'base64');
res.json({
success: true,
algorithm: 'SHA256withRSA',
valid: isValid
});
} catch (error) {
console.error('Verification error:', error.message);
res.json({
success: false,
valid: false,
error: error.message
});
}
});
// All-in-one endpoint for SecureToken & Signature headers (different texts and keys)
app.post('/headers', (req, res) => {
try {
const {
secureTokenData, // Data for SecureToken encryption
signatureData, // Data for Signature signing
publicKey, // Public key for encryption
privateKey // Private key for signing
} = req.body;
// Validate required parameters
if (!secureTokenData || !signatureData || !publicKey || !privateKey) {
return res.json({
success: false,
secureToken: secureTokenData || '',
signature: null,
error: 'Missing required parameters: secureTokenData, signatureData, publicKey, privateKey'
});
}
// 1. Generate SecureToken (encrypt with public key)
const publicKeyObj = createKeyFromBase64(publicKey, false);
publicKeyObj.setOptions({ encryptionScheme: 'pkcs1' });
const secureToken = publicKeyObj.encrypt(secureTokenData, 'base64');
// 2. Generate Signature (sign with private key)
const privateKeyObj = createKeyFromBase64(privateKey, true);
privateKeyObj.setOptions({ signingScheme: 'pkcs1-sha256' });
const signature = privateKeyObj.sign(signatureData, 'base64', 'utf8');
res.json({
success: true,
secureToken: secureToken,
signature: signature,
algorithms: {
secureToken: `${KEY_ALGORITHM}/${SECURE_PADDING}`,
signature: 'SHA256withRSA'
},
details: {
secureTokenDataLength: secureTokenData.length,
signatureDataLength: signatureData.length
}
});
} catch (error) {
console.error('headers endpoint error:', error.message);
res.json({
success: false,
secureToken: req.body.secureTokenData || '', // Fallback like Java
signature: null, // Fallback like Java
error: error.message
});
}
});
// Error handling for port in use
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
const bind = typeof PORT === 'string' ? 'Pipe ' + PORT : 'Port ' + PORT;
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
case 'EADDRINUSE':
console.error(bind + ' is already in use');
console.log('Trying alternative port...');
// Try alternative port
const altPort = parseInt(PORT) + 1;
app.listen(altPort, () => {
console.log(`✅ Service started on alternative port: ${altPort}`);
console.log(`📍 Local: http://localhost:${altPort}`);
});
break;
default:
throw error;
}
}
// Start server
const PORT = process.env.PORT || 3000;
const server = app.listen(PORT, () => {
console.log('========================================');
console.log('🚀 Crypto Service Started! (Using node-rsa)');
console.log('========================================');
console.log(`📍 Local: http://localhost:${PORT}`);
console.log('');
console.log('📋 Available Endpoints:');
console.log(' POST /encrypt - Encrypt with public key');
console.log(' POST /sign - Sign with private key');
console.log(' POST /decrypt - Decrypt with private key');
console.log(' POST /verify - Verify signature');
console.log(' POST /headers - Get SecureToken & Signature headers for Postman');
console.log(' GET /health - Health check');
console.log(' GET / - Service info');
console.log('');
console.log('🔐 Required Parameters for /headers:');
console.log(' - secureTokenData: Data to encrypt for SecureToken');
console.log(' - signatureData: Data to sign for Signature');
console.log(' - publicKey: Base64 RSA public key');
console.log(' - privateKey: Base64 RSA private key');
console.log('========================================');
});
server.on('error', onError);