bn.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. /**
  2. * Constructs a new bignum from another bignum, a number or a hex string.
  3. */
  4. sjcl.bn = function(it) {
  5. this.initWith(it);
  6. }
  7. sjcl.bn.prototype = {
  8. radix: 24,
  9. maxMul: 8,
  10. _class: sjcl.bn,
  11. copy: function() {
  12. return new this._class(this);
  13. },
  14. /**
  15. * Initializes this with it, either as a bn, a number, or a hex string.
  16. */
  17. initWith: function(it) {
  18. var i=0, k, n, l;
  19. switch(typeof it) {
  20. case "object":
  21. this.limbs = it.limbs.slice(0);
  22. break;
  23. case "number":
  24. this.limbs = [it];
  25. this.normalize();
  26. break;
  27. case "string":
  28. it = it.replace(/^0x/, '');
  29. this.limbs = [];
  30. // hack
  31. k = this.radix / 4;
  32. for (i=0; i < it.length; i+=k) {
  33. this.limbs.push(parseInt(it.substring(Math.max(it.length - i - k, 0), it.length - i),16));
  34. }
  35. break;
  36. default:
  37. this.limbs = [0];
  38. }
  39. return this;
  40. },
  41. /**
  42. * Returns true if "this" and "that" are equal. Calls fullReduce().
  43. * Equality test is in constant time.
  44. */
  45. equals: function(that) {
  46. if (typeof that == "number") { that = new this._class(that); }
  47. var difference = 0, i;
  48. this.fullReduce();
  49. that.fullReduce();
  50. for (i = 0; i < this.limbs.length || i < that.limbs.length; i++) {
  51. difference |= this.getLimb(i) ^ that.getLimb(i);
  52. }
  53. return (difference === 0);
  54. },
  55. /**
  56. * Get the i'th limb of this, zero if i is too large.
  57. */
  58. getLimb: function(i) {
  59. return (i >= this.limbs.length) ? 0 : this.limbs[i];
  60. },
  61. /**
  62. * Constant time comparison function.
  63. * Returns 1 if this >= that, or zero otherwise.
  64. */
  65. greaterEquals: function(that) {
  66. if (typeof that == "number") { that = new this._class(that); }
  67. var less = 0, greater = 0, i, a, b;
  68. i = Math.max(this.limbs.length, that.limbs.length) - 1;
  69. for (; i>= 0; i--) {
  70. a = this.getLimb(i);
  71. b = that.getLimb(i);
  72. greater |= (b - a) & ~less;
  73. less |= (a - b) & ~greater
  74. }
  75. return (greater | ~less) >>> 31;
  76. },
  77. /**
  78. * Convert to a hex string.
  79. */
  80. toString: function() {
  81. this.fullReduce();
  82. var out="", i, s, l = this.limbs;
  83. for (i=0; i < this.limbs.length; i++) {
  84. s = l[i].toString(16);
  85. while (i < this.limbs.length - 1 && s.length < 6) {
  86. s = "0" + s;
  87. }
  88. out = s + out;
  89. }
  90. return "0x"+out;
  91. },
  92. /** this += that. Does not normalize. */
  93. addM: function(that) {
  94. if (typeof(that) !== "object") { that = new this._class(that); }
  95. var i, l=this.limbs, ll=that.limbs;
  96. for (i=l.length; i<ll.length; i++) {
  97. l[i] = 0;
  98. }
  99. for (i=0; i<ll.length; i++) {
  100. l[i] += ll[i];
  101. }
  102. return this;
  103. },
  104. /** this *= 2. Requires normalized; ends up normalized. */
  105. doubleM: function() {
  106. var i, carry=0, tmp, r=this.radix, m=this.radixMask, l=this.limbs;
  107. for (i=0; i<l.length; i++) {
  108. tmp = l[i];
  109. tmp = tmp+tmp+carry;
  110. l[i] = tmp & m;
  111. carry = tmp >> r;
  112. }
  113. if (carry) l.push(carry);
  114. return this;
  115. },
  116. /** this /= 2, rounded down. Requires normalized; ends up normalized. */
  117. halveM: function() {
  118. var i, carry=0, tmp, r=this.radix, l=this.limbs;
  119. for (i=l.length-1; i>=0; i--) {
  120. tmp = l[i];
  121. l[i] = (tmp+carry)>>1;
  122. carry = (tmp&1) << r;
  123. }
  124. if (!l[l.length-1]) l.pop();
  125. return this;
  126. },
  127. /** this -= that. Does not normalize. */
  128. subM: function(that) {
  129. if (typeof(that) !== "object") { that = new this._class(that); }
  130. var i, l=this.limbs, ll=that.limbs;
  131. for (i=l.length; i<ll.length; i++) {
  132. l[i] = 0;
  133. }
  134. for (i=0; i<ll.length; i++) {
  135. l[i] -= ll[i];
  136. }
  137. return this;
  138. },
  139. mod: function(that) {
  140. that = new sjcl.bn(that).normalize(); // copy before we begin
  141. var out = new sjcl.bn(this).normalize(), ci=0;
  142. for (; out.greaterEquals(that); ci++) {
  143. that.doubleM();
  144. }
  145. for (; ci > 0; ci--) {
  146. that.halveM();
  147. if (out.greaterEquals(that)) {
  148. out.subM(that).normalize();
  149. }
  150. }
  151. return out.trim();
  152. },
  153. /** return inverse mod prime p. p must be odd. Binary extended Euclidean algorithm mod p. */
  154. inverseMod: function(p) {
  155. var a = new sjcl.bn(1), b = new sjcl.bn(0), x = new sjcl.bn(this), y = new sjcl.bn(p), tmp, i, nz=1;
  156. if (!(p.limbs[0] & 1)) {
  157. throw (new sjcl.exception.invalid("inverseMod: p must be odd"));
  158. }
  159. // invariant: y is odd
  160. do {
  161. if (x.limbs[0] & 1) {
  162. if (!x.greaterEquals(y)) {
  163. // x < y; swap everything
  164. tmp = x; x = y; y = tmp;
  165. tmp = a; a = b; b = tmp;
  166. }
  167. x.subM(y);
  168. x.normalize();
  169. if (!a.greaterEquals(b)) {
  170. a.addM(p);
  171. }
  172. a.subM(b);
  173. }
  174. // cut everything in half
  175. x.halveM();
  176. if (a.limbs[0] & 1) {
  177. a.addM(p);
  178. }
  179. a.normalize();
  180. a.halveM();
  181. // check for termination: x ?= 0
  182. for (i=nz=0; i<x.limbs.length; i++) {
  183. nz |= x.limbs[i];
  184. }
  185. } while(nz);
  186. if (!y.equals(1)) {
  187. throw (new sjcl.exception.invalid("inverseMod: p and x must be relatively prime"));
  188. }
  189. return b;
  190. },
  191. /** this + that. Does not normalize. */
  192. add: function(that) {
  193. return this.copy().addM(that);
  194. },
  195. /** this - that. Does not normalize. */
  196. sub: function(that) {
  197. return this.copy().subM(that);
  198. },
  199. /** this * that. Normalizes and reduces. */
  200. mul: function(that) {
  201. if (typeof(that) == "number") { that = new this._class(that); }
  202. var i, j, a = this.limbs, b = that.limbs, al = a.length, bl = b.length, out = new this._class(), c = out.limbs, ai, ii=this.maxMul;
  203. for (i=0; i < this.limbs.length + that.limbs.length + 1; i++) {
  204. c[i] = 0;
  205. }
  206. for (i=0; i<al; i++) {
  207. ai = a[i];
  208. for (j=0; j<bl; j++) {
  209. c[i+j] += ai * b[j];
  210. }
  211. if (!--ii) {
  212. ii = this.maxMul;
  213. out.cnormalize();
  214. }
  215. }
  216. return out.cnormalize().reduce();
  217. },
  218. /** this ^ 2. Normalizes and reduces. */
  219. square: function() {
  220. return this.mul(this);
  221. },
  222. /** this ^ n. Uses square-and-multiply. Normalizes and reduces. */
  223. power: function(l) {
  224. if (typeof(l) == "number") {
  225. l = [l];
  226. } else if (l.limbs !== undefined) {
  227. l = l.normalize().limbs;
  228. }
  229. var j, out = new this._class(1), pow = this;
  230. for (i=0; i<l.length; i++) {
  231. for (j=0; j<this.radix; j++) {
  232. if (l[i] & (1<<j)) {
  233. out = out.mul(pow);
  234. }
  235. pow = pow.square();
  236. }
  237. }
  238. return out;
  239. },
  240. trim: function() {
  241. var l = this.limbs, p;
  242. do { p = l.pop() } while (l.length && p == 0);
  243. l.push(p);
  244. return this;
  245. },
  246. /** Reduce mod a modulus. Stubbed for subclassing. */
  247. reduce: function() {
  248. return this;
  249. },
  250. /** Reduce and normalize. */
  251. fullReduce: function() {
  252. return this.normalize();
  253. },
  254. /** Propagate carries. */
  255. normalize: function() {
  256. var carry=0, i, pv = this.placeVal, ipv = this.ipv, l, m, limbs = this.limbs, ll = limbs.length, mask = this.radixMask;
  257. for (i=0; i < ll || (carry !== 0 && carry !== -1); i++) {
  258. l = (limbs[i]||0) + carry;
  259. m = limbs[i] = l & mask;
  260. carry = (l-m)*ipv;
  261. }
  262. if (carry == -1) {
  263. limbs[i-1] -= this.placeVal;
  264. }
  265. return this;
  266. },
  267. /** Constant-time normalize. Does not allocate additional space. */
  268. cnormalize: function() {
  269. var carry=0, i, ipv = this.ipv, l, m, limbs = this.limbs, ll = limbs.length, mask = this.radixMask;
  270. for (i=0; i < ll-1; i++) {
  271. l = limbs[i] + carry;
  272. m = limbs[i] = l & mask;
  273. carry = (l-m)*ipv;
  274. }
  275. limbs[i] += carry;
  276. return this;
  277. },
  278. /** Serialize to a bit array */
  279. toBits: function(len) {
  280. this.fullReduce();
  281. len = len || this.exponent || this.limbs.length * this.radix;
  282. var i = Math.floor((len-1)/24), w=sjcl.bitArray, e = (len + 7 & -8) % this.radix || this.radix,
  283. out = [w.partial(e, this.getLimb(i))];
  284. for (i--; i >= 0; i--) {
  285. out = w.concat(out, [w.partial(this.radix, this.getLimb(i))]);
  286. }
  287. return out;
  288. },
  289. /** Return the length in bits, rounded up to the nearest byte. */
  290. bitLength: function() {
  291. this.fullReduce();
  292. var out = this.radix * (this.limbs.length - 1);
  293. var b = this.limbs[this.limbs.length - 1];
  294. for (; b; b >>= 1) {
  295. out ++;
  296. }
  297. return out+7 & -8;
  298. }
  299. };
  300. sjcl.bn.fromBits = function(bits) {
  301. var out = new this(), words=[], w=sjcl.bitArray, t = this.prototype,
  302. l = Math.min(this.bitLength || 0x100000000, w.bitLength(bits)), e = l % t.radix || t.radix;
  303. words[0] = w.extract(bits, 0, e);
  304. for (; e < l; e += t.radix) {
  305. words.unshift(w.extract(bits, e, t.radix));
  306. }
  307. out.limbs = words;
  308. return out;
  309. };
  310. sjcl.bn.prototype.ipv = 1 / (sjcl.bn.prototype.placeVal = Math.pow(2,sjcl.bn.prototype.radix))
  311. sjcl.bn.prototype.radixMask = (1 << sjcl.bn.prototype.radix) - 1;
  312. /**
  313. * Creates a new subclass of bn, based on reduction modulo a pseudo-Mersenne prime,
  314. * i.e. a prime of the form 2^e + sum(a * 2^b),where the sum is negative and sparse.
  315. */
  316. sjcl.bn.pseudoMersennePrime = function(exponent, coeff) {
  317. function p(it) {
  318. this.initWith(it);
  319. /*if (this.limbs[this.modOffset]) {
  320. this.reduce();
  321. }*/
  322. }
  323. var ppr = p.prototype = new sjcl.bn(), i, tmp, mo;
  324. mo = ppr.modOffset = Math.ceil(tmp = exponent / ppr.radix);
  325. ppr.exponent = exponent;
  326. ppr.offset = [];
  327. ppr.factor = [];
  328. ppr.minOffset = mo;
  329. ppr.fullMask = 0;
  330. ppr.fullOffset = [];
  331. ppr.fullFactor = [];
  332. ppr.modulus = p.modulus = new sjcl.bn(Math.pow(2,exponent));
  333. ppr.fullMask = 0|-Math.pow(2, exponent % ppr.radix);
  334. for (i=0; i<coeff.length; i++) {
  335. ppr.offset[i] = Math.floor(coeff[i][0] / ppr.radix - tmp);
  336. ppr.fullOffset[i] = Math.ceil(coeff[i][0] / ppr.radix - tmp);
  337. ppr.factor[i] = coeff[i][1] * Math.pow(1/2, exponent - coeff[i][0] + ppr.offset[i] * ppr.radix);
  338. ppr.fullFactor[i] = coeff[i][1] * Math.pow(1/2, exponent - coeff[i][0] + ppr.fullOffset[i] * ppr.radix);
  339. ppr.modulus.addM(new sjcl.bn(Math.pow(2,coeff[i][0])*coeff[i][1]));
  340. ppr.minOffset = Math.min(ppr.minOffset, -ppr.offset[i]); // conservative
  341. }
  342. ppr._class = p;
  343. ppr.modulus.cnormalize();
  344. /** Approximate reduction mod p. May leave a number which is negative or slightly larger than p. */
  345. ppr.reduce = function() {
  346. var i, k, l, mo = this.modOffset, limbs = this.limbs, aff, off = this.offset, ol = this.offset.length, fac = this.factor, ll;
  347. i = this.minOffset;
  348. while (limbs.length > mo) {
  349. l = limbs.pop();
  350. ll = limbs.length;
  351. for (k=0; k<ol; k++) {
  352. limbs[ll+off[k]] -= fac[k] * l;
  353. }
  354. i--;
  355. if (i == 0) {
  356. limbs.push(0);
  357. this.cnormalize();
  358. i = this.minOffset;
  359. }
  360. }
  361. this.cnormalize();
  362. return this;
  363. };
  364. ppr._strongReduce = (ppr.fullMask == -1) ? ppr.reduce : function() {
  365. var limbs = this.limbs, i = limbs.length - 1, l;
  366. this.reduce();
  367. if (i == this.modOffset - 1) {
  368. l = limbs[i] & this.fullMask;
  369. limbs[i] -= l;
  370. for (k=0; k<this.fullOffset.length; k++) {
  371. limbs[i+this.fullOffset[k]] -= this.fullFactor[k] * l;
  372. }
  373. this.normalize();
  374. }
  375. };
  376. /** mostly constant-time, very expensive full reduction. */
  377. ppr.fullReduce = function() {
  378. var greater, i;
  379. // massively above the modulus, may be negative
  380. this._strongReduce();
  381. // less than twice the modulus, may be negative
  382. this.addM(this.modulus);
  383. this.addM(this.modulus);
  384. this.normalize();
  385. // probably 2-3x the modulus
  386. this._strongReduce();
  387. // less than the power of 2. still may be more than
  388. // the modulus
  389. // HACK: pad out to this length
  390. for (i=this.limbs.length; i<this.modOffset; i++) {
  391. this.limbs[i] = 0;
  392. }
  393. // constant-time subtract modulus
  394. greater = this.greaterEquals(this.modulus);
  395. for (i=0; i<this.limbs.length; i++) {
  396. this.limbs[i] -= this.modulus.limbs[i] * greater;
  397. }
  398. this.cnormalize();
  399. return this;
  400. };
  401. ppr.inverse = function() {
  402. return (this.power(this.modulus.sub(2)));
  403. };
  404. p.fromBits = sjcl.bn.fromBits;
  405. return p;
  406. }
  407. // a small Mersenne prime
  408. sjcl.bn.prime = {
  409. p127: sjcl.bn.pseudoMersennePrime(127, [[0,-1]]),
  410. // Bernstein's prime for Curve25519
  411. p25519: sjcl.bn.pseudoMersennePrime(255, [[0,-19]]),
  412. // NIST primes
  413. p192: sjcl.bn.pseudoMersennePrime(192, [[0,-1],[64,-1]]),
  414. p224: sjcl.bn.pseudoMersennePrime(224, [[0,1],[96,-1]]),
  415. p256: sjcl.bn.pseudoMersennePrime(256, [[0,-1],[96,1],[192,1],[224,-1]]),
  416. p384: sjcl.bn.pseudoMersennePrime(384, [[0,-1],[32,1],[96,-1],[128,-1]]),
  417. p521: sjcl.bn.pseudoMersennePrime(521, [[0,-1]])
  418. };
  419. sjcl.bn.random = function(modulus, paranoia) {
  420. if (typeof modulus != "object") { modulus = new sjcl.bn(modulus); }
  421. var words, i, l = modulus.limbs.length, m = modulus.limbs[l-1]+1, out = new sjcl.bn();
  422. while (true) {
  423. // get a sequence whose first digits make sense
  424. do {
  425. words = sjcl.random.randomWords(l, paranoia);
  426. if (words[l-1] < 0) { words[l-1] += 0x100000000; }
  427. } while (Math.floor(words[l-1] / m) == Math.floor(0x100000000 / m));
  428. words[l-1] %= m;
  429. // mask off all the limbs
  430. for (i=0; i<l-1; i++) {
  431. words[i] &= modulus.radixMask;
  432. }
  433. // check the rest of the digitssj
  434. out.limbs = words;
  435. if (!out.greaterEquals(modulus)) {
  436. return out;
  437. }
  438. }
  439. };