Skip to content

Instantly share code, notes, and snippets.

@bachwehbi
Created August 15, 2014 18:48
Show Gist options
  • Save bachwehbi/3d1186d5589052f50ae8 to your computer and use it in GitHub Desktop.
Save bachwehbi/3d1186d5589052f50ae8 to your computer and use it in GitHub Desktop.
Simple subscriber: using Beebotte MQTT with secure connection, AES 256 encrypted data, QoS level 1
// Copyright (c) 2013-2014 Beebotte <contact@beebotte.com>
// This program is published under the MIT License (http://opensource.org/licenses/MIT).
/////////////////////////////////////////////////////////////
// This code uses the Beebotte API, you must have an account.
// You can register here: http://beebotte.com/register
/////////////////////////////////////////////////////////////
var mqtt = require('mqtt')
var crypto = require('crypto');
//AES Cipherer
var aesCipher = function(opts) {
opts = opts || {};
this.algo = opts.algo || 'aes-256-cbc';
this.inputEncoding = opts.inputEncoding || 'utf8';
this.outputEncoding = opts.outputEncoding || 'base64';
this.key = '1234567890'; //Ciphering Key
//encrypts given data
this.encrypt = function(data) {
var cipher = crypto.createCipher(this.algo, this.key);
var encrypted = cipher.update(data, this.inputEncoding, this.outputEncoding);
encrypted += cipher.final(this.outputEncoding);
return encrypted;
}
//decrypts given encrypted data
this.decrypt = function(encrypted) {
var decipher = crypto.createDecipher(this.algo, this.key);
var deciphered = decipher.update(encrypted, this.outputEncoding, this.inputEncoding);
deciphered += decipher.final(this.inputEncoding);
return deciphered;
}
}
//Creates a secure (SSL) MQTT connection. Username is your private Key.
client = mqtt.createSecureClient(8883, 'mqtt.beebotte.com', {username: 'YOU_SECRET_KEY', password: ''});
aes = new aesCipher();
client.on('message', function (topic, message) {
//decrypt message
decrypted_msg = aes.decrypt(message);
console.log(topic + ' ' + decrypted_msg);
});
//Subscribe with QoS 1
client.subscribe('mychannel/resource', {qos: 1});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment