Skip to content

Commit

Permalink
utils: leak less information in getNAF()
Browse files Browse the repository at this point in the history
  • Loading branch information
indutny committed Nov 22, 2019
1 parent 71e4e8e commit ec735ed
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 14 deletions.
10 changes: 6 additions & 4 deletions lib/elliptic/curve/base.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ function BaseCurve(type, conf) {
this._wnafT3 = new Array(4);
this._wnafT4 = new Array(4);

this._bitLength = this.n ? this.n.bitLength() : 0;

// Generalized Greg Maxwell's trick
var adjustCount = this.n && this.p.div(this.n);
if (!adjustCount || adjustCount.cmpn(100) > 0) {
Expand All @@ -51,7 +53,7 @@ BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {
assert(p.precomputed);
var doubles = p._getDoubles();

var naf = getNAF(k, 1);
var naf = getNAF(k, 1, this._bitLength);
var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);
I /= 3;

Expand Down Expand Up @@ -88,7 +90,7 @@ BaseCurve.prototype._wnafMul = function _wnafMul(p, k) {
var wnd = nafPoints.points;

// Get NAF form
var naf = getNAF(k, w);
var naf = getNAF(k, w, this._bitLength);

// Add `this`*(N+1) for every w-NAF index
var acc = this.jpoint(null, null, null);
Expand Down Expand Up @@ -144,8 +146,8 @@ BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,
var a = i - 1;
var b = i;
if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {
naf[a] = getNAF(coeffs[a], wndWidth[a]);
naf[b] = getNAF(coeffs[b], wndWidth[b]);
naf[a] = getNAF(coeffs[a], wndWidth[a], this._bitLength);
naf[b] = getNAF(coeffs[b], wndWidth[b], this._bitLength);
max = Math.max(naf[a].length, max);
max = Math.max(naf[b].length, max);
continue;
Expand Down
19 changes: 9 additions & 10 deletions lib/elliptic/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,17 @@ utils.toHex = minUtils.toHex;
utils.encode = minUtils.encode;

// Represent num in a w-NAF form
function getNAF(num, w) {
var naf = [];
function getNAF(num, w, bits) {
var naf = new Array(Math.max(num.bitLength(), bits) + 1);
naf.fill(0);

var ws = 1 << (w + 1);
var k = num.clone();
while (k.cmpn(1) >= 0) {

for (var i = 0; i < naf.length; i++) {
var z;
var mod = k.andln(ws - 1);
if (k.isOdd()) {
var mod = k.andln(ws - 1);
if (mod > (ws >> 1) - 1)
z = (ws >> 1) - mod;
else
Expand All @@ -28,13 +31,9 @@ function getNAF(num, w) {
} else {
z = 0;
}
naf.push(z);

// Optimization, shift by word if possible
var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1;
for (var i = 1; i < shift; i++)
naf.push(0);
k.iushrn(shift);
naf[i] = z;
k.iushrn(1);
}

return naf;
Expand Down

0 comments on commit ec735ed

Please sign in to comment.