node.js - 具有aes256加密的简单TCP客户端/服务器示例产生解密错误&俏皮话

时间:2015-05-20 05:55:05

标签: node.js encryption tcp cryptography aes

啊,啊!我的第一个帖子,温柔!

Windows 7 SrvPck 1,节点v0.12.3,npm 2.9.1,aes256密码

这让我失望......当我使用TCP从客户端检索样本数据时,它也会抛出一个非常基本的错误。我的测试配置在Windows 7 SrvPck 1上,节点为v0.12.3,npm为2.9.1。我的客户端/服务器位于同一台Windows机器上,端口5000作为服务器。

此查询基于this posting我发现非常有用 - 我是node.js和crypto的新手!不幸的是,在没有遇到以下错误的情况下,我无法解密来自客户端的任何消息:

crypto.js:202   var ret = this._handle.final();                          ^ 错误:错误:06065064:数字信封例程:EVP_DecryptFinal_ex:解密错误     在错误(本机)     在Decipher.Cipher.final(crypto.js:202:26)     在解密时(C:\ Users \ ChromaBurst \ decryptserver.js:26:27)     在Socket。 (C:\ Users \用户ChromaBurst \ decryptserver.js:71:23)     在Socket.emit(events.js:107:17)     在readableAddChunk(_stream_readable.js:163:16)     在Socket.Readable.push(_stream_readable.js:126:10)     在TCP.onread(net.js:538:20)

为了说明问题,我已经包含了客户端/服务器示例的配对版本。当我加密然后解密两次来自客户端的接收缓冲区时,我只能让服务器端正确解密!是的,这没有意义!

我在客户端使用以下内容:

client.connect(PORT,HOST,function(){ 。 。     client.write(encryptedText);
。 。 });

有人可以对这个基本的例子有所了解......所以我可以保持理智吗?

-ChromaBurst

decryptserver.js

// Load the TCP Library
net = require('net');

// Load the Crypto Module
var crypto = require("crypto");

//var encString=req.query.d;
//console.log(encString);

var msg = '{"resTemp":"82.19","roomTemp":98,"ph":58,"ec":700}>';
var key = new Buffer('85CE6CCF67FBBAA8BB13479C3A6E084D', 'hex');

function encrypt(key, data) {
    var cipher = crypto.createCipher('aes256', key);
    var crypted = cipher.update(data, 'utf-8', 'hex');
    crypted += cipher.final('hex');

    return crypted;
}

function decrypt(key, data) {
    var decipher = crypto.createDecipher('aes256', key);
    var decrypted = decipher.update(data, 'hex', 'utf-8');
    decrypted += decipher.final('utf-8');

    return decrypted;
}

// Keep track of the chat clients
var clients = [];


// Start a TCP Server
net.createServer(function (socket) {

// Identify this client
socket.name = socket.remoteAddress + ":" + socket.remotePort

//socket.setEncoding('hex'); DEBUG

// Put this new client in the list
clients.push(socket);

// Send a nice welcome message and announce
socket.write("Welcome " + socket.name + "\n");
broadcast(socket.name + " joined the chat\n", socket);
console.log("\r\n");

/*********************************************************************************************/
// Handle incoming messages from clients.
socket.on('data', function (data) {

//console.log(data);    
//console.log("recv encrypted msg: " + data); 
//console.log("\r\n");

// Attempt to decrypt data with the above key
var decryptedText = decrypt(key, data); //              <---- bad decrypt if <data> is decryted here

// By commenting out the decrypt function call above and uncommenting the next block works correctly!
/* var test1=encrypt(key, data);    // we have received the client msg, encrypt!
console.log(test1+"\r\n");
var test2=decrypt(key, test1);
console.log(test2+"\r\n");
var test3=decrypt(key, test2);      // decrypt twice, yields original client msg! Correct!
console.log("check decrypt: "+test3+"\r\n"); */

console.log(decryptedText);
broadcast(socket.name + "> " + decryptedText, socket);

});
/*********************************************************************************************/
// Remove the client from the list when it leaves
socket.on('end', function () {
  clients.splice(clients.indexOf(socket), 1);
  broadcast(socket.name + " left the chat.\n");
  console.log(socket.name + " left the chat.\n");
});

// Send a message to all clients
function broadcast(message, sender) {
  clients.forEach(function (client) {
  // Don't want to send it to sender
  if (client === sender) return;
  client.write(message);
  });
// Log it to the server output too
process.stdout.write(message)
}

}).listen(5000);

// Put a friendly message on the terminal of the server.
console.log("Chat server running at port 5000\n");

encryptclient.js

    // JSON test string - {"resTemp":"82.19","roomTemp":98,"ph":58,"ec":700}>

// Load the TCP Library
net = require('net');

// Load the Crypto Module
var crypto = require("crypto");

//var ciphers = crypto.getCiphers();
//console.log(ciphers); // ['AES-128-CBC', 'AES-128-CBC-HMAC-SHA1', ...]

//var HOST = '192.168.0.39';
var HOST = 'localhost';
var PORT = 5000;

/*********************************************************************************************/
function encrypt(key, data) {
    var cipher = crypto.createCipher('aes256', key);
    var crypted = cipher.update(data, 'utf-8', 'hex');
    crypted += cipher.final('hex');

    return crypted;
}

function decrypt(key, data) {
    var decipher = crypto.createDecipher('aes256', key);
    var decrypted = decipher.update(data, 'hex', 'utf-8');
    decrypted += decipher.final('utf-8');

    return decrypted;
}

/*********************************************************************************************/
var client = new net.Socket();
client.connect(PORT, HOST, function() {

    console.log('CONNECTED TO: ' + HOST + ':' + PORT);
    // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client 
    console.log("########################################################");
    var msg = '{"resTemp":"82.19","roomTemp":98,"ph":58,"ec":700}>'
    var key = new Buffer('85CE6CCF67FBBAA8BB13479C3A6E084D', 'hex');

    console.log("msg: " + msg);
    console.log(key);
    console.log("########################################################\r\n");

    // Attempt to encrypt data with the above key
    var encryptedText = encrypt(key, msg);
    console.log("sent encrypted msg: " + encryptedText);
    console.log("\r\n");
    //console.log(encryptedText);   DEBUG

    //console.log("\r\n");
    // client.write(msg);   DEBUG
    client.write(encryptedText);    
    console.log("########################################################");
    console.log("check decrypted msg: " + decrypt(key, encryptedText));
});

/*********************************************************************************************/
// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {

    console.log("\r\n");
    console.log('Server Response: ' + data);
    // Close the client socket completely
    client.destroy();

});

/*********************************************************************************************/
// Add a 'close' event handler for the client socket
client.on('close', function() {
    console.log('Connection closed');
});

服务器输出 - 不工作!

C:\Users\ChromaBurst>node decryptserver_minimal.js
Chat server running at port 5000

::ffff:127.0.0.1:2617 joined the chat


crypto.js:202
  var ret = this._handle.final();
                         ^
Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
    at Error (native)
    at Decipher.Cipher.final (crypto.js:202:26)
    at decrypt (C:\Users\ChromaBurst\decryptserver_minimal.js:24:27)
    at Socket.<anonymous> (C:\Users\ChromaBurst\decryptserver_minimal.js:58:21)
    at Socket.emit (events.js:107:17)
    at readableAddChunk (_stream_readable.js:163:16)
    at Socket.Readable.push (_stream_readable.js:126:10)
    at TCP.onread (net.js:538:20)

C:\Users\ChromaBurst>

服务器输出 - 正确

C:\Users\ChromaBurst>node decryptserver_minimal_working.js
Chat server running at port 5000

::ffff:127.0.0.1:2648 joined the chat


794795812eb088f315ad9896c07930cb70db6f56a00e712a7df6ead5574b9ce98b39de0a5d25637e
8203b94e2592104e0c4429a4e322c703b0c3cf8fdd3b8d45d13d8459bb38ac224fd05f6961c7a4e1
eab0567a7330db46e43e088f1873d031d7c114056f019b4e4c575c4ffb7931d2313b0c7db6eef61b
39ce0de5614d81deca51480c497ba564fce5d3c8683806cd

21a9de41435c9e497a9775985cfd9bf2cdef139f692a62391171ed445e93dc7481e5b1ea4595e09d
042ea4b84a6a8657f9e401ec9109973fb02cc3403926ff27

check decrypt: {"resTemp":"82.19","roomTemp":98,"ph":58,"ec":700}>

::ffff:127.0.0.1:2648> {"resTemp":"82.19","roomTemp":98,"ph":58,"ec":700}>::ffff
:127.0.0.1:2648 left the chat.
::ffff:127.0.0.1:2648 left the chat.

客户端输出

C:\Users\ChromaBurst>node encryptclient.js
CONNECTED TO: localhost:5000
########################################################
msg: {"resTemp":"82.19","roomTemp":98,"ph":58,"ec":700}>
<Buffer 85 ce 6c cf 67 fb ba a8 bb 13 47 9c 3a 6e 08 4d>
########################################################

sent encrypted msg: 21a9de41435c9e497a9775985cfd9bf2cdef139f692a62391171ed445e93
dc7481e5b1ea4595e09d042ea4b84a6a8657f9e401ec9109973fb02cc3403926ff27


########################################################
check decrypted msg: {"resTemp":"82.19","roomTemp":98,"ph":58,"ec":700}>


Server Response: Welcome ::ffff:127.0.0.1:20809

Connection closed

1 个答案:

答案 0 :(得分:1)

问题似乎是传递给data方法的decryptBuffer,而不是十六进制字符串。

尝试更换:

var decryptedText = decrypt(key, data);

使用:

var decryptedText = decrypt(key, data.toString('utf-8'));

似乎工作正常。