26 Mar 2012

Signature generation for QuickBlox

Signature is encrypted sequence which allows us to be sure that data sent by you during session token is transferred to us without any changes by third party (man in the middle). In few words it prevents Man in the middle type of attacks.


To calculate signature manually you have to do following steps

1. Sort following pairs (parameter, value) by alphabet

app_id=98
auth_key=8h49Tag9EpDNFX6
nonce=596
timestamp=1332758214

and concatenate to one string with ampersand (like query string in URL)

app_id=98&auth_key=8h49Tag9EpDNFX6&nonce=596&timestamp=1332758214

2. Then encrypt it with HMAC-SHA using auth secret (from app settings) as key for encrypting




Manual encryption you can test with online service http://hash.online-convert.com/sha1-generator

Our result is

efdb1cdec94cedf7c821b33f4edd933d21ef8763

As you understood you shouldn't do it manually each time. You can write function by yourself or use QuickBlox SDK to simplify routine operations.

If you work with QB from JavaScript, it will be useful for you lib, that allows to calculate HMAC-SHA encryption http://code.google.com/p/crypto-js/#SHA-1

Function that calculates signature can look as

// QuickBlox application settings.
var QB = {
 appId : 'xxx',
 ownerId : 'xxxx',
 authKey : 'xxxxxxxxxxxxxxx',
 authSecret : 'xxxxxxxxxxxxxxx'
}

function getSignature() {
 var nonce = Math.floor(Math.random() * 1000); // Gets random number (0;1000)
 var timestamp = Math.round((new Date()).getTime() / 1000); // Gets unix timestamp (http://en.wikipedia.org/wiki/Unix_time) 

 // Creating message where parameters are sorted by alphabetical order.
 var message = 'app_id=' + QB.appId + '&auth_key=' + QB.authKey + '&nonce=' + nonce + '&timestamp=' + timestamp;
 var secret = QB.authSecret;
 // Encrypting message with secret key from QuickBlox application parameters.
 var hmac = Crypto.HMAC(Crypto.SHA1, message, secret);
 
 var signatureObj = {
  nonce   : nonce,
  timestamp  : timestamp,
  signature  : hmac
 };
 
 return signatureObj; 
}

No comments:

Post a Comment