From be64372a5e92d3769fb35c28a97795f15e58bd07 Mon Sep 17 00:00:00 2001 From: Jack Kleeman Date: Tue, 11 Apr 2017 10:14:00 +0100 Subject: [PATCH] fix(ecdh): allow base64 to be left-0-padded, needed for JWK format Fixes #97 --- src/crypto/ecdh-browser.js | 4 ++-- src/crypto/util.js | 5 +++-- test/util.spec.js | 6 ++++++ 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/crypto/ecdh-browser.js b/src/crypto/ecdh-browser.js index 4fbb30b..ca806b4 100644 --- a/src/crypto/ecdh-browser.js +++ b/src/crypto/ecdh-browser.js @@ -117,8 +117,8 @@ function unmarshalPublicKey (curve, key) { return { kty: 'EC', crv: curve, - x: toBase64(x), - y: toBase64(y), + x: toBase64(x, byteLen), + y: toBase64(y, byteLen), ext: true } } diff --git a/src/crypto/util.js b/src/crypto/util.js index 46d0eaa..0f25b8e 100644 --- a/src/crypto/util.js +++ b/src/crypto/util.js @@ -5,8 +5,9 @@ const Buffer = require('safe-buffer').Buffer // Convert a BN.js instance to a base64 encoded string without padding // Adapted from https://tools.ietf.org/html/draft-ietf-jose-json-web-signature-41#appendix-C -exports.toBase64 = function toBase64 (bn) { - let s = bn.toArrayLike(Buffer, 'be').toString('base64') +exports.toBase64 = function toBase64 (bn, len) { + // if len is defined then the bytes are leading-0 padded to the length + let s = bn.toArrayLike(Buffer, 'be', len).toString('base64') return s .replace(/(=*)$/, '') // Remove any trailing '='s diff --git a/test/util.spec.js b/test/util.spec.js index 7142084..cb2c5a2 100644 --- a/test/util.spec.js +++ b/test/util.spec.js @@ -22,4 +22,10 @@ describe('Util', () => { expect(util.toBase64(bn)).to.be.eql('3q0') done() }) + + it('toBase64 zero padding', (done) => { + let bnpad = new BN('ff', 16) + expect(util.toBase64(bnpad, 2)).to.be.eql('AP8') + done() + }) })