node.js-具有aes256加密的简单TCP客户端/服务器示例会产生解密错误& amp;怪癖 [英] node.js - Simple TCP client/server example with aes256 encryption yields decrypt error & quirk

查看:117
本文介绍了node.js-具有aes256加密的简单TCP客户端/服务器示例会产生解密错误& amp;怪癖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨!我的第一个帖子,请保持柔和!

Ahoy there! My first posting, be gentle!

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

Windows 7 SrvPck 1, node v0.12.3, npm 2.9.1, aes256 cipher

这让我感到困惑...当我使用TCP从客户端检索示例数据时,也引发了一个非常基本的错误.我的测试配置在具有节点v0.12.3和npm 2.9.1的Windows 7 SrvPck 1上.我的客户端/服务器与服务器位于同一端口的Windows计算机上.

This is throwing me... it's also throwing a very basic error when I retrieve sample data from a client using TCP. My test configuration is on Windows 7 SrvPck 1 with node v0.12.3 and npm 2.9.1. My client/server are on the same Windows machine with port 5000 as the server.

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

This inquiry is based on this posting which I found very informative - I'm new to node.js and crypto! Unfortunately I've been unable to decrypt any message from the client without the encountering the following error:

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) 在套接字. (C:\ Users \ ChromaBurst \ decryptserver.js:71:23) 在Socket.emit(events.js:107:17) 在可读的AddChunk(_stream_visible.js:163:16) 在Socket.Readable.push(_stream_visible.js:126:10) 在TCP.onread(net.js:538:20)

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.js:26:27) at Socket. (C:\Users\ChromaBurst\decryptserver.js:71:23) 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)

为说明问题,我提供了一个配对版本的客户端/服务器示例.当我加密然后解密两次从客户端收到的缓冲区时,我只能让服务器端正确解密!是的,这没有道理!

To illustrate the problem, I've included a paired down version of the client/server example. I can only get the server-side to decrypt correctly when I encrypt and then decrypt twice the received buffer from the client! Yes, this doesn't make sense!

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

I'm using the following on the client side:

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

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

有人可以阐明这个基本示例吗?这样我就可以保持理智?

Can someone shed some light on this basic example... so I can preserve my sanity?

-ChromaBurst

-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

推荐答案

问题似乎在于,将data传递给decrypt方法是Buffer,而不是十六进制字符串.

The problem appears to be the fact that data being passed to the decrypt method is a Buffer, not a hex string.

尝试更换:

var decryptedText = decrypt(key, data);

使用:

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

它似乎工作正常.

这篇关于node.js-具有aes256加密的简单TCP客户端/服务器示例会产生解密错误&amp; amp;怪癖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆