| |
| const { encrypt, decrypt } = require('../utils/cryptoUtils'); |
|
|
| |
| |
| const sessionKeys = new Map(); |
|
|
| |
| |
| |
| |
| |
| function generateSessionKey(clientId) { |
| |
| const sessionKey = require('crypto').randomBytes(32).toString('hex'); |
| |
| |
| sessionKeys.set(clientId, sessionKey); |
| |
| return sessionKey; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| function authenticateClient(clientId, clientSecret) { |
| |
| |
| const validClientId = 'test-client'; |
| const validClientSecret = 'test-secret'; |
| |
| return clientId === validClientId && clientSecret === validClientSecret; |
| } |
|
|
| |
| |
| |
| |
| |
| function getSessionKey(clientId) { |
| return sessionKeys.get(clientId) || null; |
| } |
|
|
| |
| |
| |
| |
| function removeSessionKey(clientId) { |
| sessionKeys.delete(clientId); |
| } |
|
|
| |
| |
| |
| |
| |
| |
| function encryptPacket(data, clientId) { |
| const sessionKey = getSessionKey(clientId); |
| |
| if (!sessionKey) { |
| throw new Error('未找到会话密钥'); |
| } |
| |
| |
| const encrypted = encrypt(data, sessionKey); |
| |
| |
| |
| const result = Buffer.concat([ |
| encrypted.salt, |
| encrypted.iv, |
| encrypted.authTag, |
| encrypted.data |
| ]); |
| |
| return result; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| function decryptPacket(encryptedData, clientId) { |
| const sessionKey = getSessionKey(clientId); |
| |
| if (!sessionKey) { |
| throw new Error('未找到会话密钥'); |
| } |
| |
| |
| const salt = encryptedData.slice(0, 16); |
| const iv = encryptedData.slice(16, 28); |
| const authTag = encryptedData.slice(28, 44); |
| const data = encryptedData.slice(44); |
| |
| |
| return decrypt(data, salt, iv, authTag, sessionKey); |
| } |
|
|
| module.exports = { |
| generateSessionKey, |
| authenticateClient, |
| getSessionKey, |
| removeSessionKey, |
| encryptPacket, |
| decryptPacket |
| }; |