bn.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. /**
  2. * Constructs a new bignum from another bignum, a number or a hex string.
  3. */
  4. function bn(it) {
  5. this.initWith(it);
  6. }
  7. bn.prototype = {
  8. radix: 24,
  9. maxMul: 8,
  10. _class: 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;
  96. for (i=this.limbs.length; i<that.limbs.length; i++) {
  97. this.limbs[i] = 0;
  98. }
  99. for (i=0; i<that.limbs.length; i++) {
  100. this.limbs[i] += that.limbs[i];
  101. }
  102. return this;
  103. },
  104. /** this -= that. Does not normalize. */
  105. subM: function(that) {
  106. if (typeof(that) !== "object") { that = new this._class(that); }
  107. var i;
  108. for (i=this.limbs.length; i<that.limbs.length; i++) {
  109. this.limbs[i] = 0;
  110. }
  111. for (i=0; i<that.limbs.length; i++) {
  112. this.limbs[i] -= that.limbs[i];
  113. }
  114. return this;
  115. },
  116. /** this + that. Does not normalize. */
  117. add: function(that) {
  118. return this.copy().addM(that);
  119. },
  120. /** this - that. Does not normalize. */
  121. sub: function(that) {
  122. return this.copy().subM(that);
  123. },
  124. /** this * that. Normalizes and reduces. */
  125. mul: function(that) {
  126. if (typeof(that) == "number") { that = new this._class(that); }
  127. 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;
  128. for (i=0; i < this.limbs.length + that.limbs.length + 1; i++) {
  129. c[i] = 0;
  130. }
  131. for (i=0; i<al; i++) {
  132. ai = a[i];
  133. for (j=0; j<bl; j++) {
  134. c[i+j] += ai * b[j];
  135. }
  136. if (!--ii) {
  137. ii = this.maxMul;
  138. out.cnormalize();
  139. }
  140. }
  141. return out.cnormalize().reduce();
  142. },
  143. /** this ^ 2. Normalizes and reduces. */
  144. square: function() {
  145. return this.mul(this);
  146. },
  147. /** this ^ n. Uses square-and-multiply. Normalizes and reduces. */
  148. power: function(l) {
  149. if (typeof(l) == "number") {
  150. l = [l];
  151. } else if (l.limbs !== undefined) {
  152. l = l.normalize().limbs;
  153. }
  154. var j, out = new this._class(1), pow = this;
  155. for (i=0; i<l.length; i++) {
  156. for (j=0; j<this.radix; j++) {
  157. if (l[i] & (1<<j)) {
  158. out = out.mul(pow);
  159. }
  160. pow = pow.square();
  161. }
  162. }
  163. return out;
  164. },
  165. /** Reduce mod a modulus. Stubbed for subclassing. */
  166. reduce: function() {
  167. return this;
  168. },
  169. /** Reduce and normalize. */
  170. fullReduce: function() {
  171. return this.normalize();
  172. },
  173. /** Propagate carries. */
  174. normalize: function() {
  175. var carry=0, i, pv = this.placeVal, ipv = this.ipv, l, m, limbs = this.limbs, ll = limbs.length, mask = this.radixMask;
  176. for (i=0; i < ll || (carry !== 0 && carry !== -1); i++) {
  177. l = (limbs[i]||0) + carry;
  178. m = limbs[i] = l & mask;
  179. carry = (l-m)*ipv;
  180. }
  181. if (carry == -1) {
  182. limbs[i-1] -= this.placeVal;
  183. }
  184. return this;
  185. },
  186. /** Constant-time normalize. Does not allocate additional space. */
  187. cnormalize: function() {
  188. var carry=0, i, ipv = this.ipv, l, m, limbs = this.limbs, ll = limbs.length, mask = this.radixMask;
  189. for (i=0; i < ll-1; i++) {
  190. l = limbs[i] + carry;
  191. m = limbs[i] = l & mask;
  192. carry = (l-m)*ipv;
  193. }
  194. limbs[i] += carry;
  195. return this;
  196. }
  197. };
  198. /* Initialization routines for bignum library. */
  199. (function init(){
  200. bn.prototype.ipv = 1 / (bn.prototype.placeVal = Math.pow(2,bn.prototype.radix));
  201. bn.prototype.radixMask = (1 << bn.prototype.radix) - 1;
  202. })();
  203. /**
  204. * Creates a new subclass of bn, based on reduction modulo a pseudo-Mersenne prime,
  205. * i.e. a prime of the form 2^e + sum(a * 2^b),where the sum is negative and sparse.
  206. */
  207. function pseudoMersennePrime(exponent, coeff) {
  208. function p(it) {
  209. this.initWith(it);
  210. /*if (this.limbs[this.modOffset]) {
  211. this.reduce();
  212. }*/
  213. }
  214. var ppr = p.prototype = new bn(), i, tmp, mo;
  215. mo = ppr.modOffset = Math.ceil(tmp = exponent / ppr.radix);
  216. ppr.exponent = exponent;
  217. ppr.offset = [];
  218. ppr.factor = [];
  219. ppr.minOffset = mo;
  220. ppr.fullMask = 0;
  221. ppr.fullOffset = [];
  222. ppr.fullFactor = [];
  223. ppr.modulus = p.modulus = new bn(Math.pow(2,exponent));
  224. ppr.fullMask = 0|-Math.pow(2, exponent % ppr.radix);
  225. for (i=0; i<coeff.length; i++) {
  226. ppr.offset[i] = Math.floor(coeff[i][0] / ppr.radix - tmp);
  227. ppr.fullOffset[i] = Math.ceil(coeff[i][0] / ppr.radix - tmp);
  228. ppr.factor[i] = coeff[i][1] * Math.pow(1/2, exponent - coeff[i][0] + ppr.offset[i] * ppr.radix);
  229. ppr.fullFactor[i] = coeff[i][1] * Math.pow(1/2, exponent - coeff[i][0] + ppr.fullOffset[i] * ppr.radix);
  230. ppr.modulus.addM(new bn(Math.pow(2,coeff[i][0])*coeff[i][1]));
  231. ppr.minOffset = Math.min(ppr.minOffset, -ppr.offset[i]); // conservative
  232. }
  233. ppr._class = p;
  234. ppr.modulus.cnormalize();
  235. /** Approximate reduction mod p. May leave a number which is negative or slightly larger than p. */
  236. ppr.reduce = function() {
  237. var i, k, l, mo = this.modOffset, limbs = this.limbs, aff, off = this.offset, ol = this.offset.length, fac = this.factor, ll;
  238. i = this.minOffset;
  239. while (limbs.length > mo) {
  240. l = limbs.pop();
  241. ll = limbs.length;
  242. for (k=0; k<ol; k++) {
  243. limbs[ll+off[k]] -= fac[k] * l;
  244. }
  245. i--;
  246. if (i == 0) {
  247. limbs.push(0);
  248. this.cnormalize();
  249. i = this.minOffset;
  250. }
  251. }
  252. this.cnormalize();
  253. return this;
  254. };
  255. ppr._strongReduce = (ppr.fullMask == -1) ? ppr.reduce : function() {
  256. var limbs = this.limbs, i = limbs.length - 1, l;
  257. this.reduce();
  258. if (i == this.modOffset - 1) {
  259. l = limbs[i] & this.fullMask;
  260. limbs[i] -= l;
  261. for (k=0; k<this.fullOffset.length; k++) {
  262. limbs[i+this.fullOffset[k]] -= this.fullFactor[k] * l;
  263. }
  264. this.normalize();
  265. }
  266. };
  267. /** mostly constant-time, very expensive full reduction. */
  268. ppr.fullReduce = function() {
  269. var greater, i;
  270. // massively above the modulus, may be negative
  271. this._strongReduce();
  272. // less than twice the modulus, may be negative
  273. this.addM(this.modulus);
  274. this.addM(this.modulus);
  275. this.normalize();
  276. // probably 2-3x the modulus
  277. this._strongReduce();
  278. // less than the power of 2. still may be more than
  279. // the modulus
  280. // HACK: pad out to this length
  281. for (i=this.limbs.length; i<this.modOffset; i++) {
  282. this.limbs[i] = 0;
  283. }
  284. // constant-time subtract modulus
  285. greater = this.greaterEquals(this.modulus);
  286. for (i=0; i<this.limbs.length; i++) {
  287. this.limbs[i] -= this.modulus.limbs[i] * greater;
  288. }
  289. this.cnormalize();
  290. return this;
  291. };
  292. ppr.inverse = function() {
  293. return (this.power(this.modulus.sub(2)));
  294. };
  295. ppr.toBits = function() {
  296. this.fullReduce();
  297. var i=this.modOffset - 1, w=sjcl.bitArray, e = (this.exponent + 7 & -8) % this.radix || this.radix;
  298. out = [w.partial(e, this.getLimb(i))];
  299. for (i--; i >= 0; i--) {
  300. out = w.concat(out, [w.partial(this.radix, this.getLimb(i))]);
  301. }
  302. return out;
  303. };
  304. p.fromBits = function(bits) {
  305. var out = new this(), words=[], w=sjcl.bitArray, t = this.prototype,
  306. l = Math.min(w.bitLength(bits), t.exponent + 7 & -8), e = l % t.radix || t.radix;
  307. words[0] = w.extract(bits, 0, e);
  308. for (; e < l; e += t.radix) {
  309. words.unshift(w.extract(bits, e, t.radix));
  310. }
  311. out.limbs = words;
  312. return out;
  313. };
  314. return p;
  315. }
  316. // a small Mersenne prime
  317. p127 = pseudoMersennePrime(127, [[0,-1]]);
  318. // Bernstein's prime for Curve25519
  319. p25519 = pseudoMersennePrime(255, [[0,-19]]);
  320. // NIST primes
  321. p192 = pseudoMersennePrime(192, [[0,-1],[64,-1]]);
  322. p224 = pseudoMersennePrime(224, [[0,1],[96,-1]]);
  323. p256 = pseudoMersennePrime(256, [[0,-1],[96,1],[192,1],[224,-1]]);
  324. p384 = pseudoMersennePrime(384, [[0,-1],[32,1],[96,-1],[128,-1]]);
  325. p521 = pseudoMersennePrime(521, [[0,-1]]);
  326. bn.random = function(modulus, paranoia) {
  327. if (typeof modulus != "object") { modulus = new bn(modulus); }
  328. var words, i, l = modulus.limbs.length, m = modulus.limbs[l-1]+1, out = new bn();
  329. while (true) {
  330. // get a sequence whose first digits make sense
  331. do {
  332. words = sjcl.random.randomWords(l, paranoia);
  333. if (words[l-1] < 0) { words[l-1] += 0x100000000; }
  334. } while (Math.floor(words[l-1] / m) == Math.floor(0x100000000 / m));
  335. words[l-1] %= m;
  336. // mask off all the limbs
  337. for (i=0; i<l-1; i++) {
  338. words[i] &= modulus.radixMask;
  339. }
  340. // check the rest of the digitssj
  341. out.limbs = words;
  342. if (!out.greaterEquals(modulus)) {
  343. return out;
  344. }
  345. }
  346. };