fix(ecdh): allow base64 to be left-0-padded, needed for JWK format

Fixes #97
This commit is contained in:
Jack Kleeman 2017-04-11 10:14:00 +01:00 committed by Friedel Ziegelmayer
parent 2b0b7abd78
commit be64372a5e
3 changed files with 11 additions and 4 deletions

View File

@ -117,8 +117,8 @@ function unmarshalPublicKey (curve, key) {
return { return {
kty: 'EC', kty: 'EC',
crv: curve, crv: curve,
x: toBase64(x), x: toBase64(x, byteLen),
y: toBase64(y), y: toBase64(y, byteLen),
ext: true ext: true
} }
} }

View File

@ -5,8 +5,9 @@ const Buffer = require('safe-buffer').Buffer
// Convert a BN.js instance to a base64 encoded string without padding // 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 // Adapted from https://tools.ietf.org/html/draft-ietf-jose-json-web-signature-41#appendix-C
exports.toBase64 = function toBase64 (bn) { exports.toBase64 = function toBase64 (bn, len) {
let s = bn.toArrayLike(Buffer, 'be').toString('base64') // 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 return s
.replace(/(=*)$/, '') // Remove any trailing '='s .replace(/(=*)$/, '') // Remove any trailing '='s

View File

@ -22,4 +22,10 @@ describe('Util', () => {
expect(util.toBase64(bn)).to.be.eql('3q0') expect(util.toBase64(bn)).to.be.eql('3q0')
done() done()
}) })
it('toBase64 zero padding', (done) => {
let bnpad = new BN('ff', 16)
expect(util.toBase64(bnpad, 2)).to.be.eql('AP8')
done()
})
}) })