Skip to content

Latest commit

 

History

History
63 lines (44 loc) · 1.77 KB

Message-Encryption.md

File metadata and controls

63 lines (44 loc) · 1.77 KB

Message Encryption

By default, the qnode won't encrypt the message. You can override the encrypt() and decrypt() methods to implement your own message encryption and decryption. If you did, you should implement the encrypt() and decrypt() methods at your Server as well.


qnode.encrypt(msg, cb)

Method of encryption. Overridable.

Arguments:

  1. msg (String | Buffer): The outgoing message.
  2. cb (Function): function (err, encrypted) {}, the callback you should call and pass the encrypted message to it after encryption.

qnode.decrypt(msg, cb)

Method of decryption. Overridable.

Arguments:

  1. msg (Buffer): The incoming message which is a raw buffer.
  2. cb (Function): function (err, decrypted) {}, the callback you should call and pass the decrypted message to it after decryption.


Encryption/Decryption Example:

// In this example, I simply encrypt the message with a constant password 'mysecrete'.

qnode.encrypt = function (msg, callback) {
  const msgBuf = new Buffer(msg)
  const cipher = crypto.createCipher('aes128', 'mysecrete')
  let encrypted = cipher.update(msgBuf, 'binary', 'base64')

  try {
    encrypted += cipher.final('base64')
    callback(null, encrypted)
  } catch (err) {
    callback(err)
  }
}

qnode.decrypt = function (msg, callback) {
  msg = msg.toString()
  const decipher = crypto.createDecipher('aes128', 'mypassword')
  let decrypted = decipher.update(msg, 'base64', 'utf8')

  try {
    decrypted += decipher.final('utf8')
    callback(null, decrypted)
  } catch (e) {
    // log 'decrytion fails'
    console.log('decrytion fails.')
    callback(e)
  }
}