面试题答案
一键面试步骤
- 引入加密模块:在Node.js中使用
crypto
模块,它是Node.js内置的加密模块。 - 生成密钥和初始化向量(IV):对于对称加密算法(如AES),需要生成密钥和IV。密钥长度取决于所使用的加密算法,IV通常用于增加加密的安全性,且长度也因算法而异。
- 加密数据:在数据发送端,使用生成的密钥和IV对要发送的数据进行加密。
- 发送加密数据:通过TCP连接发送加密后的数据。
- 接收加密数据:在TCP连接的接收端接收加密数据。
- 解密数据:使用相同的密钥和IV对接收的加密数据进行解密。
关键代码示例
TCP服务器端(添加加密解密)
const net = require('net');
const crypto = require('crypto');
// 生成密钥和IV
const key = crypto.randomBytes(32); // AES - 256 - CBC 密钥长度为32字节
const iv = crypto.randomBytes(16); // AES - 256 - CBC IV长度为16字节
const server = net.createServer((socket) => {
socket.on('data', (encryptedData) => {
const decipher = crypto.createDecipheriv('aes - 256 - cbc', key, iv);
let decrypted = decipher.update(encryptedData, 'hex', 'utf8');
decrypted += decipher.final('utf8');
console.log('解密后的数据:', decrypted);
});
});
server.listen(8080, () => {
console.log('服务器已启动,监听8080端口');
});
TCP客户端(添加加密解密)
const net = require('net');
const crypto = require('crypto');
// 假设与服务器端使用相同的密钥和IV
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
const socket = new net.Socket();
socket.connect(8080, '127.0.0.1', () => {
const dataToSend = 'Hello, Server!';
const cipher = crypto.createCipheriv('aes - 256 - cbc', key, iv);
let encrypted = cipher.update(dataToSend, 'utf8', 'hex');
encrypted += cipher.final('hex');
socket.write(encrypted);
});
socket.on('error', (err) => {
console.log('连接错误:', err);
});
上述代码示例展示了如何在简单的TCP服务器和客户端之间使用crypto
模块的aes - 256 - cbc
算法进行数据的加密和解密。实际应用中,密钥和IV的管理需要更安全的方式,例如通过密钥管理服务(KMS)等。