Performance Optimization

- Uses optimized c secp256k1 library Node.js addon
- Browserified version continues to use elliptic.js
This commit is contained in:
Braydon Fuller 2015-09-18 09:49:17 -04:00
parent b1b2693a5c
commit 452dc5386c
12 changed files with 306 additions and 95 deletions

45
.jshintrc Normal file
View File

@ -0,0 +1,45 @@
{
"bitwise": false,
"browser": true,
"camelcase": false,
"curly": true,
"devel": false,
"eqeqeq": true,
"esnext": true,
"freeze": true,
"immed": true,
"indent": 2,
"latedef": true,
"newcap": false,
"noarg": true,
"node": true,
"noempty": true,
"nonew": true,
"quotmark": "single",
"regexp": true,
"smarttabs": false,
"strict": true,
"trailing": true,
"undef": true,
"unused": true,
"maxparams": 4,
"maxstatements": 15,
"maxcomplexity": 10,
"maxdepth": 4,
"maxlen": 120,
"multistr": true,
"predef": [ // Extra globals.
"after",
"afterEach",
"before",
"beforeEach",
"define",
"describe",
"exports",
"it",
"module",
"require"
]
}

63
benchmarks/index.js Normal file
View File

@ -0,0 +1,63 @@
'use strict';
var assert = require('assert');
var benchmark = require('benchmark');
var bitauth = require('../lib/bitauth-node');
var async = require('async');
var maxTime = 10;
async.series([
function(next) {
var privkey = '9b3bdba1c7910017dae5d6cbfb2e86aafdccfbcbea518d1b984c45817b6c655b';
var privkeyBuffer = new Buffer(privkey, 'hex');
var pubkey = '03ff368ca67364d1df4c0f131b6a454d4fa14c00538357f03235917feabc1a9cb6';
var pubkeyBuffer = new Buffer(pubkey, 'hex');
var contract = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer vestibulum nibh neque, ac fermentum nunc pharetra in. Aenean orci velit, facilisis a gravida eu, ullamcorper feugiat dui. Sed quis eros sed sem egestas sagittis non sit amet arcu. Nulla feugiat purus et sem tempus convallis. Ut a odio consequat, vulputate nisl a, venenatis lectus. Aenean mi diam, pulvinar sed vehicula pulvinar, commodo quis justo. Pellentesque quis elementum eros. Sed ligula tellus, interdum non interdum eget, ultricies in ipsum. Maecenas vitae lectus sit amet ante volutpat malesuada. Nulla condimentum iaculis sem sit amet rhoncus. Mauris at vestibulum felis, a porttitor elit. Pellentesque rhoncus faucibus condimentum. Praesent auctor auctor magna, nec consectetur mi suscipit eget. Nulla sit amet ligula enim. Ut odio augue, auctor ac quam vel, aliquet mattis nisi. Curabitur orci lectus, viverra at hendrerit at, feugiat at magna. Morbi rhoncus bibendum erat, quis dapibus felis eleifend vitae. Etiam vel sapien consequat, tempor libero non, lobortis purus. Maecenas finibus pretium augue a ullamcorper. Donec consectetur sed nunc sed convallis. Phasellus eu magna a nisl lobortis finibus. Quisque hendrerit at arcu tempus gravida. Donec fringilla pulvinar sapien at porta. Interdum et malesuada fames ac ante ipsum primis in faucibus. Sed dui metus, rhoncus at iaculis nec, porta at nunc. Donec in purus pellentesque, lacinia erat eget, congue massa. In a magna molestie tellus convallis dictum. Etiam id magna laoreet, suscipit leo non, egestas turpis. Sed dolor orci, pellentesque eget tempor ut, tincidunt at magna. Duis quis imperdiet sapien.';
var contractBuffer = new Buffer(contract);
var signature = '3045022100db71942a5a6dd1443cbf7519b2bc16a041aff8d4830bd42599f03ce503b8bf700220281989345617548d2512391a4b04450761df9add920d83043f9e21cb5baeb703';
var signatureBuffer = new Buffer(signature, 'hex');
function nodebitauthVerify() {
bitauth.verifySignature(contractBuffer, pubkeyBuffer, signatureBuffer);
}
// #verifySignature
var suite = new benchmark.Suite();
suite.add('bitauth#verifySignature', nodebitauthVerify, { maxTime: maxTime });
suite
.on('cycle', function(event) {
console.log(String(event.target));
})
.on('complete', function() {
console.log('---------------------------------------');
next();
})
.run();
},
function(next) {
// invalid checksum
var sinbad = 'Tf1Jc1xSbqasm5QLwwSQc5umddx2h7mAMhX';
function nodebitauthValidateSin() {
bitauth.validateSin(sinbad);
}
// #validateSin
var suite = new benchmark.Suite();
suite.add('bitauth#validateSin', nodebitauthValidateSin, { maxTime: maxTime });
suite
.on('cycle', function(event) {
console.log(String(event.target));
})
.on('complete', function() {
console.log('---------------------------------------');
next();
})
.run();
}
], function(err) {
console.log('Finished');
});

View File

@ -1,5 +1,5 @@
// get base functionality
var bitauth = require('./lib/bitauth');
var bitauth = require('./lib/bitauth-node');
// add node-specific encrypt/decrypt
bitauth.encrypt = require('./lib/encrypt');

48
lib/bitauth-browserify.js Normal file
View File

@ -0,0 +1,48 @@
'use strict';
var elliptic = require('elliptic');
var ecdsa = new elliptic.ec(elliptic.curves.secp256k1);
var BitAuth = require('./bitauth-common');
BitAuth._generateRandomPair = function() {
var keys = ecdsa.genKeyPair();
var privateKey = keys.getPrivate('hex');
var publicKey = BitAuth.getPublicKeyFromPrivateKey(privateKey);
return [privateKey, publicKey];
};
BitAuth._getPublicKeyFromPrivateKey = function(privkey) {
var privKeyString;
if (Buffer.isBuffer(privkey)) {
privKeyString = privkey.toString('hex');
} else {
privKeyString = privkey;
}
var keys = ecdsa.keyPair(privkey, 'hex');
// compressed public key
var pubKey = keys.getPublic();
var xbuf = new Buffer(pubKey.x.toString('hex', 64), 'hex');
var ybuf = new Buffer(pubKey.y.toString('hex', 64), 'hex');
var pub;
if (ybuf[ybuf.length - 1] % 2) { //odd
pub = Buffer.concat([new Buffer([3]), xbuf]);
} else { //even
pub = Buffer.concat([new Buffer([2]), xbuf]);
}
return pub;
};
BitAuth._sign = function(hashBuffer, privkey) {
var signature = ecdsa.sign(hashBuffer.toString('hex'), privkey);
var hexsignature = signature.toDER('hex');
return hexsignature;
};
BitAuth._verifySignature = function(hashBuffer, signatureBuffer, pubkey) {
return ecdsa.verify(hashBuffer.toString('hex'), signatureBuffer, pubkey);
};
module.exports = BitAuth;

View File

@ -1,8 +1,10 @@
var elliptic = require('elliptic');
var ecdsa = new elliptic.ec(elliptic.curves.secp256k1);
var hashjs = require('hash.js');
var bs58 = require('bs58');
var BitAuth = {};
'use strict';
var crypto = require('crypto');
var bs58 = require('bs58');
var BitAuth = {};
BitAuth.PREFIX = new Buffer('0f02', 'hex');
/**
* Will return a key pair and identity
@ -10,20 +12,14 @@ var BitAuth = {};
* @returns {Object} An object with keys: created, priv, pub and sin
*/
BitAuth.generateSin = function() {
var keys = ecdsa.genKeyPair();
var privateKey = keys.getPrivate('hex');
var publicKey = this.getPublicKeyFromPrivateKey(privateKey);
var sin = this.getSinFromPublicKey(publicKey);
var pair = BitAuth._generateRandomPair();
var sin = this.getSinFromPublicKey(pair[1]);
var sinObj = {
created: Math.round(Date.now() / 1000),
priv: privateKey,
pub: publicKey,
priv: pair[0],
pub: pair[1],
sin: sin
};
return sinObj;
};
@ -34,25 +30,9 @@ BitAuth.generateSin = function() {
* @returns {String} A compressed public key in hex
*/
BitAuth.getPublicKeyFromPrivateKey = function(privkey) {
var keys = ecdsa.keyPair(privkey, 'hex');
// compressed public key
var pubKey = keys.getPublic();
var xbuf = new Buffer(pubKey.x.toString('hex', 64), 'hex');
var ybuf = new Buffer(pubKey.y.toString('hex', 64), 'hex');
var pub;
if (ybuf[ybuf.length-1] % 2) { //odd
pub = Buffer.concat([new Buffer([3]), xbuf]);
} else { //even
pub = Buffer.concat([new Buffer([2]), xbuf]);
}
var pub = BitAuth._getPublicKeyFromPrivateKey(privkey);
var hexPubKey = pub.toString('hex');
return hexPubKey;
};
/**
@ -62,28 +42,34 @@ BitAuth.getPublicKeyFromPrivateKey = function(privkey) {
* @returns {String} A SIN identity
*/
BitAuth.getSinFromPublicKey = function(pubkey) {
var pubkeyBuffer;
if (!Buffer.isBuffer(pubkey)) {
pubkeyBuffer = new Buffer(pubkey, 'hex');
} else {
pubkeyBuffer = pubkey;
}
// sha256 hash the pubkey
var pubHash = (new hashjs.sha256()).update(pubkey, 'hex').digest('hex');
var pubHash = crypto.createHash('sha256').update(pubkeyBuffer).digest();
// get the ripemd160 hash of the pubkey
var pubRipe = (new hashjs.ripemd160()).update(pubHash, 'hex').digest('hex');
var pubRipe = crypto.createHash('rmd160').update(pubHash).digest();
// add the version
var pubPrefixed = '0f02'+pubRipe;
var pubPrefixed = Buffer.concat([BitAuth.PREFIX, pubRipe]);
// two rounds of hashing to generate the checksum
var hash1 = (new hashjs.sha256()).update(pubPrefixed, 'hex').digest('hex');
var checksumTotal = (new hashjs.sha256()).update(hash1, 'hex').digest('hex');
var hash1 = crypto.createHash('sha256').update(pubPrefixed).digest();
var checksumTotal = crypto.createHash('sha256').update(hash1).digest();
// slice the hash to arrive at the checksum
var checksum = checksumTotal.slice(0,8);
var checksum = checksumTotal.slice(0, 4);
// add the checksum to the ripemd160 pubkey
var pubWithChecksum = pubPrefixed + checksum;
var pubWithChecksum = Buffer.concat([pubPrefixed, checksum]);
// encode into base58
var sin = bs58.encode(new Buffer(pubWithChecksum, 'hex'));
var sin = bs58.encode(pubWithChecksum);
return sin;
@ -97,9 +83,14 @@ BitAuth.getSinFromPublicKey = function(pubkey) {
* @returns {String} signature - A DER signature in hex
*/
BitAuth.sign = function(data, privkey) {
var hash = (new hashjs.sha256()).update(data).digest('hex');
var signature = ecdsa.sign(hash, privkey);
var hexsignature = signature.toDER('hex');
var dataBuffer;
if (!Buffer.isBuffer(data)) {
dataBuffer = new Buffer(data, 'utf-8');
} else {
dataBuffer = data;
}
var hashBuffer = crypto.createHash('sha256').update(dataBuffer).digest();
var hexsignature = BitAuth._sign(hashBuffer, privkey);
return hexsignature;
};
@ -112,15 +103,27 @@ BitAuth.sign = function(data, privkey) {
* @returns {Function|Boolean} - If the signature is valid
*/
BitAuth.verifySignature = function(data, pubkey, hexsignature, callback) {
var hash = (new hashjs.sha256()).update(data).digest('hex');
var signature = new Buffer(hexsignature, 'hex');
var valid = ecdsa.verify(hash, signature, pubkey);
if (callback)
var dataBuffer;
if (!Buffer.isBuffer(data)) {
dataBuffer = new Buffer(data, 'utf-8');
} else {
dataBuffer = data;
}
var hashBuffer = crypto.createHash('sha256').update(dataBuffer).digest();
var signatureBuffer;
if (!Buffer.isBuffer(hexsignature)) {
signatureBuffer = new Buffer(hexsignature, 'hex');
} else {
signatureBuffer = hexsignature;
}
var valid = BitAuth._verifySignature(hashBuffer, signatureBuffer, pubkey);
if (callback) {
return callback(null, valid);
}
return valid;
};
/**
* Will verify that a SIN is valid
*
@ -134,36 +137,42 @@ BitAuth.validateSin = function(sin, callback) {
// check for non-base58 characters
try {
pubWithChecksum = new Buffer(bs58.decode(sin), 'hex').toString('hex');
} catch(err) {
if (callback)
} catch (err) {
if (callback) {
return callback(err);
}
return false;
}
// check the version
if (pubWithChecksum.slice(0, 4) !== '0f02') {
if (callback)
if (callback) {
return callback(new Error('Invalid prefix or SIN version'));
}
return false;
}
// get the checksum
var checksum = pubWithChecksum.slice(pubWithChecksum.length-8,
pubWithChecksum.length);
var pubPrefixed = pubWithChecksum.slice(0, pubWithChecksum.length-8);
var checksum = pubWithChecksum.slice(
pubWithChecksum.length - 8,
pubWithChecksum.length
);
var pubPrefixed = pubWithChecksum.slice(0, pubWithChecksum.length - 8);
// two rounds of hashing to generate the checksum
var hash1 = (new hashjs.sha256()).update(pubPrefixed, 'hex').digest('hex');
var checksumTotal = (new hashjs.sha256()).update(hash1, 'hex').digest('hex');
var hash1 = crypto.createHash('sha256').update(new Buffer(pubPrefixed, 'hex')).digest();
var checksumTotal = crypto.createHash('sha256').update(hash1).digest('hex');
// check the checksum
if (checksumTotal.slice(0,8) === checksum) {
if (callback)
if (checksumTotal.slice(0, 8) === checksum) {
if (callback) {
return callback(null);
}
return true;
} else {
if (callback)
if (callback) {
return callback(new Error('Checksum does not match'));
}
return false;
}

44
lib/bitauth-node.js Normal file
View File

@ -0,0 +1,44 @@
'use strict';
var secp256k1 = require('secp256k1');
var BitAuth = require('./bitauth-common');
var crypto = require('crypto');
BitAuth._generateRandomPair = function() {
var privateKeyBuffer = crypto.randomBytes(32); // may throw error if entropy sources drained
var publicKeyBuffer = secp256k1.createPublicKey(privateKeyBuffer, true);
return [privateKeyBuffer.toString('hex'), publicKeyBuffer.toString('hex')];
};
BitAuth._getPublicKeyFromPrivateKey = function(privkey) {
var privateKeyBuffer;
if (Buffer.isBuffer(privkey)) {
privateKeyBuffer = privkey;
} else {
privateKeyBuffer = new Buffer(privkey, 'hex');
}
return secp256k1.createPublicKey(privateKeyBuffer, true);
};
BitAuth._sign = function(hashBuffer, privkey) {
var privkeyBuffer;
if (Buffer.isBuffer(privkey)) {
privkeyBuffer = privkey;
} else {
privkeyBuffer = new Buffer(privkey, 'hex');
}
var signatureInfo = secp256k1.sign(hashBuffer, privkeyBuffer, true);
return signatureInfo.toString('hex');
};
BitAuth._verifySignature = function(hashBuffer, signatureBuffer, pubkey) {
var pubkeyBuffer;
if (!Buffer.isBuffer(pubkey)){
pubkeyBuffer = new Buffer(pubkey, 'hex');
} else {
pubkeyBuffer = pubkey;
}
return secp256k1.verify(hashBuffer, signatureBuffer, pubkeyBuffer) ? true : false;
};
module.exports = BitAuth;

View File

@ -3,12 +3,12 @@ var crypto = require('crypto');
module.exports = function decrypt(password, str) {
var aes256 = crypto.createDecipher('aes-256-cbc', password);
var a = aes256.update(new Buffer(base58.decode(str)));
var b = aes256.final();
var buf = new Buffer(a.length + b.length);
var a = aes256.update(new Buffer(base58.decode(str)));
var b = aes256.final();
var buf = new Buffer(a.length + b.length);
a.copy(buf, 0);
b.copy(buf, a.length);
return buf.toString('utf8');
};
};

View File

@ -3,12 +3,12 @@ var crypto = require('crypto');
module.exports = function encrypt(password, str) {
var aes256 = crypto.createCipher('aes-256-cbc', password);
var a = aes256.update(str, 'utf8');
var b = aes256.final();
var buf = new Buffer(a.length + b.length);
var a = aes256.update(str, 'utf8');
var b = aes256.final();
var buf = new Buffer(a.length + b.length);
a.copy(buf, 0);
b.copy(buf, a.length);
return base58.encode(buf);
};
};

View File

@ -1,20 +1,24 @@
var bitauth = require('../bitauth');
var bitauth = require('../bitauth-node');
module.exports = function(req, res, next) {
if(req.headers && req.headers['x-identity'] && req.headers['x-signature']) {
if (req.headers && req.headers['x-identity'] && req.headers['x-signature']) {
// Check signature is valid
// First construct data to check signature on
var fullUrl = req.protocol + '://' + req.get('host') + req.url;
var data = fullUrl + req.rawBody;
bitauth.verifySignature(data, req.headers['x-identity'], req.headers['x-signature'], function(err, result) {
if(err || !result) {
return res.send(400, {error: 'Invalid signature'});
if (err || !result) {
return res.send(400, {
error: 'Invalid signature'
});
}
// Get the SIN from the public key
var sin = bitauth.getSinFromPublicKey(req.headers['x-identity']);
if(!sin) return res.send(400, {error: 'Bad public key from identity'});
if (!sin) return res.send(400, {
error: 'Bad public key from identity'
});
req.sin = sin;
next();
});

View File

@ -30,17 +30,15 @@
"main": "index.js",
"version": "0.2.1",
"dependencies": {
"elliptic": "=1.0.0",
"hash.js": "^0.3.2",
"bs58": "^2.0.0",
"request": "^2.36.0",
"express": "^4.3.1",
"body-parser": "^1.2.0"
"elliptic": "=1.0.0",
"secp256k1": "=1.1.3"
},
"devDependencies": {
"uglify-js": "~2.4.14",
"benchmark": "^1.0.0",
"browserify": "=6.1.0",
"chai": "=1.9.1",
"uglify-js": "~2.4.14",
"mocha": "~1.20.1"
}
}

View File

@ -1,5 +1,5 @@
echo "Building browser bundle for bitauth..."
node_modules/.bin/browserify lib/bitauth.js -s bitauth -o dist/bitauth.bundle.js
node_modules/.bin/browserify lib/bitauth-browserify.js -s bitauth -o dist/bitauth.bundle.js
echo "Minifying bitauth..."
node_modules/.bin/uglifyjs dist/bitauth.bundle.js --compress --mangle -o dist/bitauth.browser.min.js
echo "Done!"

View File

@ -1,6 +1,6 @@
'use strict';
if ( typeof(window) === 'undefined' ) {
if (typeof(window) === 'undefined') {
var bitauth = require('../index');
} else {
var bitauth = window.bitauth;
@ -17,29 +17,29 @@ describe('bitauth', function() {
priv: '97811b691dd7ebaeb67977d158e1da2c4d3eaa4ee4e2555150628acade6b344c',
pub: '02326209e52f6f17e987ec27c56a1321acf3d68088b8fb634f232f12ccbc9a4575',
sin: 'Tf3yr5tYvccKNVrE26BrPs6LWZRh8woHwjR'
}
};
// a private key that will produce a public key with a leading zero
var privateKeyToZero = 'c6b7f6bfe5bb19b1e390e55ed4ba5df8af6068d0eb89379a33f9c19aacf6c08c';
// keys generated
var keys = null;
var keys = null;
// invalid checksum
var sinbad = 'Tf1Jc1xSbqasm5QLwwSQc5umddx2h7mAMhX';
var sinbad = 'Tf1Jc1xSbqasm5QLwwSQc5umddx2h7mAMhX';
// valid sin
var singood = 'TfG4ScDgysrSpodWD4Re5UtXmcLbY5CiUHA';
var singood = 'TfG4ScDgysrSpodWD4Re5UtXmcLbY5CiUHA';
// data to sign
var contract = 'keyboard cat';
var secret = 'o hai, nsa. how i do teh cryptos?';
var password = 's4705hiru13z!';
var contract = 'kéyboard cät';
var secret = 'o hai, nsa. how i do teh cryptos?';
var password = 's4705hiru13z!';
var encryptedSecret = '291Dm9unZMwfxBA7BEHiQsraRxCrMRqwJ2TjCWwEH3Sp5QGMehNFNgZLo62sgF5Khe';
// signature from generate keys
var signature = null;
var enc = null;
var enc = null;
describe('#generateSin', function() {
@ -95,7 +95,7 @@ describe('bitauth', function() {
describe('#verifySignature', function() {
it('should verify the signature', function(done) {
bitauth.verifySignature(contract, keys.pub, signature, function(err, valid){
bitauth.verifySignature(contract, keys.pub, signature, function(err, valid) {
should.not.exist(err);
should.exist(valid);
valid.should.equal(true);
@ -111,7 +111,7 @@ describe('bitauth', function() {
};
signature = bitauth.sign(contract, leadingZeroKeys.priv);
bitauth.verifySignature(contract, leadingZeroKeys.pub, signature, function(err, valid){
bitauth.verifySignature(contract, leadingZeroKeys.pub, signature, function(err, valid) {
should.not.exist(err);
should.exist(valid);
valid.should.equal(true);
@ -152,7 +152,7 @@ describe('bitauth', function() {
describe('#validateSinCallback', function() {
it('should receive error callback', function(done) {
var valid = bitauth.validateSin(sinbad, function(err){
bitauth.validateSin(sinbad, function(err) {
should.exist(err);
err.message.should.equal('Checksum does not match');
done();
@ -162,7 +162,7 @@ describe('bitauth', function() {
});
// node specific tests
if ( typeof(window) === 'undefined' ) {
if (typeof(window) === 'undefined') {
describe('#encrypt', function() {
@ -194,7 +194,7 @@ describe('bitauth', function() {
describe('#middleware', function() {
it('should expose an express middleware', function(done) {
bitauth.middleware( {} , {} , function() {
bitauth.middleware({}, {}, function() {
done();
});
});