Skip to content

Instantly share code, notes, and snippets.

@mvberg
Last active December 9, 2016 20:07
Show Gist options
  • Save mvberg/df69779c7368b036d63cfc4932902539 to your computer and use it in GitHub Desktop.
Save mvberg/df69779c7368b036d63cfc4932902539 to your computer and use it in GitHub Desktop.
BCHMAC: Generating Your Secret Key (Javascript)
const crypto = require('crypto');
/* generate your secret key (note 16 vs 128 (java) for key length) */
const key = crypto.pbkdf2Sync('yourPassword', 'client://barchart.com/yourUsername', 128 * 1024, 16, 'sha1');
/* use your key to sign requests*/
const mac = crypto.createHmac('SHA256', key);
/* set the text on hmac object */
const requestTest = 'helloWorld';
mac.update(requestTest);
/* get signature, equal to doFinal() in Java */
var signature = mac.digest('base64');
console.log('Secret key', key.toString('hex'));
console.log('Sig (base64)', signature);
/* real world example */
/* request body if any, must still here even if empty lolol */
var body = ''; //d41d8cd98f00b204e9800998ecf8427e
const md5Body = crypto.createHash('md5').update(body).digest('hex');
/* content type header on request */
var contentType = '';
requestText = 'GET\n' +
'/accounts/account/05a66d32-2002-5648-a81d-69cab7e45197/permissions\n' +
md5Body + '\n' +
contentType + '\n' +
'Tue, 30 Aug 2016 20:07:41 GMT\n';
const newMac = crypto.createHmac('SHA256', key);
newMac.update(requestText);
console.log('Real Request Sig', newMac.digest('base64'));
// Browser Example
<script type="text/javascript" src="../bower_components/crypto-js/crypto-js.js"></script>
var hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
hmac.update(user);
hmac.update(timestamp + '');
var token = hmac.finalize();
var sig_base64 = CryptoJS.enc.Base64.stringify(token);
var sig_hex = CryptoJS.enc.Hex.stringify(token);
/* or single line */
var sig_hex = CryptoJS.enc.Hex.stringify(CryptoJS.HmacSHA256(user+timestamp, key));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment