From d86c4390175a70c96a7d02226ba3d30de3e8cd8a Mon Sep 17 00:00:00 2001 From: Christopher Jeffrey Date: Mon, 1 Aug 2016 01:19:09 -0700 Subject: [PATCH] chachapoly: optimize for little-endian. --- bench/chacha.js | 15 +++++++++++++++ lib/bcoin/chachapoly.js | 11 +++++++++-- 2 files changed, 24 insertions(+), 2 deletions(-) create mode 100644 bench/chacha.js diff --git a/bench/chacha.js b/bench/chacha.js new file mode 100644 index 00000000..32d62530 --- /dev/null +++ b/bench/chacha.js @@ -0,0 +1,15 @@ +'use strict'; + +var chachapoly = require('../lib/bcoin/chachapoly'); +var bench = require('./bench'); + +var chacha = new chachapoly.ChaCha20(); +var iv = new Buffer('0102030405060708', 'hex'); +chacha.init(iv, 0); +var data = new Buffer(32); +for (var i = 0; i < 32; i++) + data[i] = i; +var end = bench('encrypt'); +for (var i = 0; i < 1000000; i++) + chacha.encrypt(data); +end(i); diff --git a/lib/bcoin/chachapoly.js b/lib/bcoin/chachapoly.js index 2f7c8ebb..342fa8e1 100644 --- a/lib/bcoin/chachapoly.js +++ b/lib/bcoin/chachapoly.js @@ -8,6 +8,8 @@ var assert = require('assert'); +var BIG_ENDIAN = new Int8Array(Int16Array.of(1).buffer)[0] === 0; + /** * ChaCha20 (used for bip151) * @see https://tools.ietf.org/html/rfc7539#section-2 @@ -21,7 +23,11 @@ function ChaCha20() { this.state = new Uint32Array(16); this.stream = new Uint32Array(16); - this.bytes = new Buffer(64); + this.bytes = new Uint8Array(this.stream.buffer); + + if (BIG_ENDIAN) + this.bytes = new Buffer(64); + this.pos = 0; this.ivSize = 0; } @@ -116,7 +122,8 @@ ChaCha20.prototype.encrypt = function encrypt(data) { for (j = 0; j < 16; j++) { this.stream[j] += this.state[j]; - this.bytes.writeUInt32LE(this.stream[j], j * 4, true); + if (BIG_ENDIAN) + this.bytes.writeUInt32LE(this.stream[j], j * 4, true); } this.state[12]++;