// 模拟前端加密登录的完整流程 const CryptoJS = require('crypto-js'); // 1. 前端准备登录凭据 const credentials = { username: 'admin', password: 'password123' }; console.log('=== 前端加密流程 ==='); console.log('原始登录凭据:', JSON.stringify(credentials)); // 2. 前端加密凭据 const plainText = JSON.stringify(credentials); const secretKey = 'MyDifficultPassw'; const encrypted = CryptoJS.AES.encrypt(plainText, secretKey); const base64String = encrypted.toString(); console.log('加密后完整字符串:', base64String); console.log('加密后字符串长度:', base64String.length); // 3. 转换为Base64URL格式(后端期望的格式) let base64UrlString = base64String.replace(/\+/g, '-').replace(/\//g, '_'); console.log('Base64URL格式字符串:', base64UrlString); // 4. 准备发送给后端的请求体 const timestamp = Date.now(); const encryptedRequest = { encryptedCredentials: base64UrlString, timestamp: timestamp }; console.log('发送给后端的请求:', JSON.stringify(encryptedRequest, null, 2)); console.log('\n=== 模拟后端处理流程 ==='); console.log('后端接收到的请求:', JSON.stringify(encryptedRequest, null, 2)); // 5. 后端处理流程 try { // 后端验证时间戳(5分钟内有效) const currentTime = Date.now(); const timeDiff = Math.abs(currentTime - encryptedRequest.timestamp); console.log(`时间戳验证: 请求时间=${encryptedRequest.timestamp}, 当前时间=${currentTime}, 差值=${timeDiff}ms`); if (timeDiff > 300000) { // 5分钟 = 300000毫秒 console.log('时间戳验证失败'); process.exit(1); } console.log('时间戳验证通过'); // 后端接收到Base64URL格式并转换回标准格式 const receivedString = encryptedRequest.encryptedCredentials; console.log('后端接收到的加密字符串:', receivedString); // 后端转换回标准Base64格式 const standardBase64 = receivedString.replace(/-/g, '+').replace(/_/g, '/'); console.log('转换回标准Base64格式:', standardBase64); // 后端确保适当的填充 let paddedBase64 = standardBase64; const paddingNeeded = (4 - (standardBase64.length % 4)) % 4; for (let i = 0; i < paddingNeeded; i++) { paddedBase64 += '='; } console.log('填充后的Base64格式:', paddedBase64); // 后端解密 const decryptedBytes = CryptoJS.AES.decrypt(paddedBase64, secretKey); const decryptedData = decryptedBytes.toString(CryptoJS.enc.Utf8); console.log('后端解密结果:', decryptedData); // 验证解密是否成功 if (decryptedData === JSON.stringify(credentials)) { console.log('✅ 加密解密流程测试通过!'); } else { console.log('❌ 加密解密流程测试失败!'); console.log('期望:', JSON.stringify(credentials)); console.log('实际:', decryptedData); } // 模拟将解密后的JSON解析为LoginRequest对象 try { const parsedCredentials = JSON.parse(decryptedData); console.log('✅ 解析登录凭据成功:', JSON.stringify(parsedCredentials)); } catch (parseError) { console.log('❌ 解析登录凭据失败:', parseError.message); } } catch (error) { console.log('❌ 后端处理流程出错:', error.message); console.error(error.stack); }