diff --git a/lib/bcoin/bip151.js b/lib/bcoin/bip151.js index 7555ab13..24dc76d9 100644 --- a/lib/bcoin/bip151.js +++ b/lib/bcoin/bip151.js @@ -1,5 +1,6 @@ /*! * bip151.js - peer-to-peer communication encryption. + * See: https://github.com/bitcoin/bips/blob/master/bip-0151.mediawiki * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/bcoin-org/bcoin */ @@ -13,6 +14,11 @@ var assert = utils.assert; var constants = bcoin.protocol.constants; var chachapoly = require('./chachapoly'); +var HKDF_SALT = new Buffer('bitcoinechd' /* ecHd (sic?) */, 'ascii'); +var INFO_KEY1 = new Buffer('BitcoinK1', 'ascii'); +var INFO_KEY2 = new Buffer('BitcoinK2', 'ascii'); +var INFO_SID = new Buffer('BitcoinSessionID', 'ascii'); + function BIP151(cipher, key) { if (!(this instanceof BIP151)) return new BIP151(cipher, key); @@ -28,7 +34,7 @@ function BIP151(cipher, key) { this.sid = null; this.chacha = new chachapoly.ChaCha20(); this.aead = new chachapoly.AEAD(); - this.mac = null; + this.prk = null; this.tag = null; this.seq = 0; @@ -51,12 +57,10 @@ BIP151.prototype.init = function init(publicKey) { p.writeBytes(this.secret); p.writeU8(this.cipher); - this.mac = utils.hmac('sha512', p.render(), 'encryption key'); - - this.k1 = this.mac.slice(0, 32); - this.k2 = this.mac.slice(32, 64); - - this.sid = utils.hmac('sha256', this.secret, 'session id'); + this.prk = utils.hkdfExtract(p.render(), HKDF_SALT, 'sha256'); + this.k1 = utils.hkdfExpand(this.prk, INFO_KEY1, 32, 'sha256'); + this.k2 = utils.hkdfExpand(this.prk, INFO_KEY2, 32, 'sha256'); + this.sid = utils.hkdfExpand(this.prk, INFO_SID, 32, 'sha256'); this.seq = 0; @@ -66,10 +70,9 @@ BIP151.prototype.init = function init(publicKey) { }; BIP151.prototype.rekey = function rekey() { - assert(this.mac, 'Cannot rekey before initialization.'); - this.mac = utils.hash256(this.mac); - this.k1 = this.mac.slice(0, 32); - this.k2 = this.mac.slice(32, 64); + assert(this.prk, 'Cannot rekey before initialization.'); + this.k1 = utils.hash256(this.k1); + this.k2 = utils.hash256(this.k2); this.seq = 0; this.chacha.init(this.k1, this.iv()); this.aead.init(this.k2, this.iv());