4 <script type="text/javascript">
7 /* Split number into the shares */
8 function split(number, available, needed) {
10 var coef = [number, 166, 94], x, exp, c, accum, shares = [];
11 for(c = 1, coef[0] = number; c < needed; c++) coef[c] = Math.floor(Math.random() * (prime - 1));
12 for(x = 1; x <= available; x++) {
13 /* coef = [1234, 166, 94] which is 1234x^0 + 166x^1 + 94x^2 */
14 for(exp = 1, accum = coef[0]; exp < needed; exp++) accum = (accum + (coef[exp] * (Math.pow(x, exp) % prime) % prime)) % prime;
15 /* Store values as (1, 132), (2, 66), (3, 188), (4, 241), (5, 225) (6, 140) */
16 shares[x - 1] = [x, accum];
21 /* Gives the decomposition of the gcd of a and b. Returns [x,y,z] such that x = gcd(a,b) and y*a + z*b = x */
23 if (b == 0) return [a, 1, 0];
25 var n = Math.floor(a/b), c = a % b, r = gcdD(b,c);
26 return [r[0], r[2], r[1]-r[2]*n];
30 /* Gives the multiplicative inverse of k mod prime. In other words (k * modInverse(k)) % prime = 1 for all prime > k >= 1 */
31 function modInverse(k) {
33 var r = (k < 0) ? -gcdD(prime,-k)[2] : gcdD(prime,k)[2];
34 return (prime + r) % prime;
37 /* Join the shares into a number */
38 function join(shares) {
39 var accum, count, formula, startposition, nextposition, value, numerator, denominator;
40 for(formula = accum = 0; formula < shares.length; formula++) {
41 /* Multiply the numerator across the top and denominators across the bottom to do Lagrange's interpolation
42 * Result is x0(2), x1(4), x2(5) -> -4*-5 and (2-4=-2)(2-5=-3), etc for l0, l1, l2...
44 for(count = 0, numerator = denominator = 1; count < shares.length; count++) {
45 if(formula == count) continue; // If not the same value
46 startposition = shares[formula][0];
47 nextposition = shares[count][0];
48 numerator = (numerator * -nextposition) % prime;
49 denominator = (denominator * (startposition - nextposition)) % prime;
51 value = shares[formula][1];
52 accum = (prime + accum + (value * numerator * modInverse(denominator))) % prime;
57 var sh = split(1234, 6, 3) /* split the secret value 129 into 6 components - at least 3 of which will be needed to figure out the secret value */
58 for (var i=0; i<sh.length; i++) alert(sh[i]);
59 var newshares = [sh[1], sh[3], sh[4]]; /* pick any selection of 3 shared keys from sh */
61 alert(join(newshares));