From b0bb5d516d39c61ae1274d5809547165f6c4f616 Mon Sep 17 00:00:00 2001 From: Christopher Jeffrey Date: Mon, 25 Jul 2016 22:11:32 -0700 Subject: [PATCH] chachapoly: do not reinitialize state. --- lib/bcoin/bip151.js | 5 ++--- lib/bcoin/chachapoly.js | 24 +++++++++++++++++++++++- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/lib/bcoin/bip151.js b/lib/bcoin/bip151.js index c2d29e1f..8ae82ea0 100644 --- a/lib/bcoin/bip151.js +++ b/lib/bcoin/bip151.js @@ -104,9 +104,8 @@ BIP151Stream.prototype.rekey = function rekey() { BIP151Stream.prototype.sequence = function sequence() { this.seq++; - this.chacha.init(this.k1, this.iv()); - this.aead.init(this.k2, this.iv()); - this.aead.aad(this.sid); + this.chacha.init(null, this.iv()); + this.aead.init(null, this.iv()); }; BIP151Stream.prototype.iv = function iv() { diff --git a/lib/bcoin/chachapoly.js b/lib/bcoin/chachapoly.js index f36b79e7..fbee45c4 100644 --- a/lib/bcoin/chachapoly.js +++ b/lib/bcoin/chachapoly.js @@ -34,6 +34,19 @@ function ChaCha20() { */ ChaCha20.prototype.init = function init(key, iv, counter) { + if (key) + this.initKey(key); + + if (iv) + this.initIV(iv, counter); +}; + +/** + * Set key. + * @param {Buffer} key + */ + +ChaCha20.prototype.initKey = function initKey(key) { this.state[0] = 0x61707865; this.state[1] = 0x3320646e; this.state[2] = 0x79622d32; @@ -50,6 +63,16 @@ ChaCha20.prototype.init = function init(key, iv, counter) { this.state[12] = 0; + this.pos = 0xffffffff; +}; + +/** + * Set IV and counter. + * @param {Buffer} iv + * @param {Number} counter + */ + +ChaCha20.prototype.initIV = function initIV(iv, counter) { if (iv.length === 8) { this.state[13] = 0; this.state[14] = iv.readUInt32LE(0, true); @@ -62,7 +85,6 @@ ChaCha20.prototype.init = function init(key, iv, counter) { assert(false, 'Bad iv size.'); } - this.pos = 0xffffffff; this.ivSize = iv.length * 8; this.setCounter(counter);