Skip to content

Commit

Permalink
pseudo-mersenne: fix K256.imulK
Browse files Browse the repository at this point in the history
  • Loading branch information
indutny committed Jan 4, 2015
1 parent c6e4bd0 commit 3557d78
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 11 deletions.
25 changes: 14 additions & 11 deletions lib/bn.js
Expand Up @@ -1555,24 +1555,27 @@ K256.prototype.imulK = function imulK(num) {
num.words[num.length] = 0;
num.words[num.length + 1] = 0;
num.length += 2;
for (var i = num.length - 3; i >= 0; i--) {

var uhi = 0;
var hi = 0;
var lo = 0;
for (var i = 0; i < num.length; i++) {
var w = num.words[i];
var hi = w * 0x40;
var lo = w * 0x3d1;
hi += w * 0x40;
lo += w * 0x3d1;
hi += (lo / 0x4000000) | 0;
var uhi = (hi / 0x4000000) | 0;
uhi += (hi / 0x4000000) | 0;
hi &= 0x3ffffff;
lo &= 0x3ffffff;

num.words[i + 2] += uhi;
num.words[i + 1] += hi;
num.words[i] = lo;

lo = hi;
hi = uhi;
uhi = 0;
}
var w = num.words[num.length - 2];
if (w >= 0x4000000) {
num.words[num.length - 1] += w >>> 26;
num.words[num.length - 2] = w & 0x3ffffff;
}

// Fast length reduction
if (num.words[num.length - 1] === 0)
num.length--;
if (num.words[num.length - 1] === 0)
Expand Down
13 changes: 13 additions & 0 deletions test/red-test.js
Expand Up @@ -123,5 +123,18 @@ describe('BN.js/Reduction context', function() {
regr2 = regr2.toRed(BN.red('k256'));
assert.equal(regr2.redInvm().redMul(regr2).fromRed().cmpn(1), 0);
});

it('should correctly square the number', function() {
var p = BN._prime('k256').p;
var red = BN.red('k256');

var n = new BN('9cd8cb48c3281596139f147c1364a3ed' +
'e88d3f310fdb0eb98c924e599ca1b3c9',
16);
var expected = n.sqr().mod(p);
var actual = n.toRed(red).redSqr().fromRed();

assert.equal(actual.toString(16), expected.toString(16));
});
});
});

0 comments on commit 3557d78

Please sign in to comment.