Skip to content

Instantly share code, notes, and snippets.

@bachwehbi
Created August 27, 2014 01:01
Show Gist options
  • Save bachwehbi/14b7fa7f70a3f976cac2 to your computer and use it in GitHub Desktop.
Save bachwehbi/14b7fa7f70a3f976cac2 to your computer and use it in GitHub Desktop.
Beebotte MQTT example with signature based authentication
var mqtt = require('mqtt')
var crypto = require('crypto');
//Creates a hash mac of a string
function sign (key, algo, str){
var hmac = crypto.createHmac(algo, key);
hmac.setEncoding('base64');
hmac.write(str);
// you can't read from the stream until you call end()
hmac.end();
// read out hmac
var hash = hmac.read();
return hash;
}
//Construct the password by concatenating the token, column and the signature
//the token MUST NOT contain column ':' character
var token = 'mytoken';
var signature = sign('SECRET_KEY', 'sha1', 'mytoken');
var pass = token + ':' + signature;
client = mqtt.createSecureClient(8883, 'mqtt.beebotte.com', {username: 'ACCESS_KEY',
password: pass,
clientId: 'bachtech',
clean: false
});
client.on('message', function (topic, message) {
console.log(topic);
console.log(message);
});
client.subscribe('dev/#', {qos: 1});
client.publish('dev/test', 'Hello world', {qos: 1, retain: true});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment