Skip to content
This repository has been archived by the owner on Jul 21, 2023. It is now read-only.

Commit

Permalink
fix(ecdh): allow base64 to be left-0-padded, needed for JWK format
Browse files Browse the repository at this point in the history
Fixes #97
  • Loading branch information
jackkleeman authored and dignifiedquire committed Apr 11, 2017
1 parent 2b0b7ab commit be64372
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 4 deletions.
4 changes: 2 additions & 2 deletions src/crypto/ecdh-browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
Expand Down
5 changes: 3 additions & 2 deletions src/crypto/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions test/util.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()
})
})

0 comments on commit be64372

Please sign in to comment.