chachapoly: optimize for little-endian.

This commit is contained in:
Christopher Jeffrey 2016-08-01 01:19:09 -07:00
parent ac42de6cfb
commit d86c439017
No known key found for this signature in database
GPG Key ID: 8962AB9DE6666BBD
2 changed files with 24 additions and 2 deletions

15
bench/chacha.js Normal file
View File

@ -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);

View File

@ -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]++;