title: node.js - Simple TCP client/server example with aes256 encryption yields decrypt error & quirk
body: <p>Ahoy there! My first posting, be gentle!</p>
  
  <p><strong><em>Windows 7 SrvPck 1, node v0.12.3, npm 2.9.1, aes256 cipher</em></strong> </p>
  
  <p>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.</p>
  
  <p>This inquiry is based on <a href="https://stackoverflow.com/questions/25172527/attempting-to-decrypt-using-crypto-js-and-nodejs">this posting</a> 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:</p>
  
  <p><strong><em>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)</em></strong></p>
  
  <p>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 <strong>encrypt</strong> and then <strong>decrypt twice</strong> the received buffer from the client! Yes, this doesn't make sense!</p>
  
  <p>I'm using the following on the client side:</p>
  
  <p><strong><em>client.connect(PORT, HOST, function() {
  .
  .
      client.write(encryptedText);<br>
  .
  .
  });</em></strong></p>
  
  <p>Can someone shed some light on this basic example... so I can preserve my sanity?</p>
  
  <p>-ChromaBurst</p>
  
  <p><strong>decryptserver.js</strong></p>
  
  <pre><code>// 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}&gt;';
  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); //              &lt;---- bad decrypt if &lt;data&gt; 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 + "&gt; " + 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");
  </code></pre>
  
  <p><strong>encryptclient.js</strong></p>
  
  <pre><code>    // JSON test string - {"resTemp":"82.19","roomTemp":98,"ph":58,"ec":700}&gt;
  
  // 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}&gt;'
      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');
  });
  </code></pre>
  
  <p><strong>Server Output - NOT WORKING!</strong></p>
  
  <pre><code>C:\Users\ChromaBurst&gt;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.&lt;anonymous&gt; (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&gt;
  </code></pre>
  
  <p><strong>Server Output - CORRECT</strong></p>
  
  <pre><code>C:\Users\ChromaBurst&gt;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}&gt;
  
  ::ffff:127.0.0.1:2648&gt; {"resTemp":"82.19","roomTemp":98,"ph":58,"ec":700}&gt;::ffff
  :127.0.0.1:2648 left the chat.
  ::ffff:127.0.0.1:2648 left the chat.
  </code></pre>
  
  <p><strong>Client Output</strong></p>
  
  <pre><code>C:\Users\ChromaBurst&gt;node encryptclient.js
  CONNECTED TO: localhost:5000
  ########################################################
  msg: {"resTemp":"82.19","roomTemp":98,"ph":58,"ec":700}&gt;
  &lt;Buffer 85 ce 6c cf 67 fb ba a8 bb 13 47 9c 3a 6e 08 4d&gt;
  ########################################################
  
  sent encrypted msg: 21a9de41435c9e497a9775985cfd9bf2cdef139f692a62391171ed445e93
  dc7481e5b1ea4595e09d042ea4b84a6a8657f9e401ec9109973fb02cc3403926ff27
  
  
  ########################################################
  check decrypted msg: {"resTemp":"82.19","roomTemp":98,"ph":58,"ec":700}&gt;
  
  
  Server Response: Welcome ::ffff:127.0.0.1:20809
  
  Connection closed
  </code></pre>