javascriptshared-secret

Shamir Secret Sharing: I cant get the right reconstructed value in javascript


I try to use shamir secret sharing. I implement the code that I find in wikipedia. But when I run it, for enormous numbers the result of reconstruction is different from the real secret value.

https://en.wikipedia.org/wiki/Shamir%27s_Secret_Sharing

The reconstruction function is:

function join(shares) {
    var accum, count, formula, startposition, nextposition, value, numerator, denominator;
    for(formula = accum = 0; formula < shares.length; formula++) {
    for(count = 0, numerator = denominator = 1; count < shares.length; count++) {
        if(formula == count) continue; // If not the same value
        startposition = shares[formula][0];
        nextposition = shares[count][0];
        numerator = (numerator * -nextposition) % prime;
        denominator = (denominator * (startposition - nextposition)) % prime;
    }
    value = shares[formula][1];
    accum = (prime + accum + (value * numerator * modInverse(denominator))) % prime;
}
return accum;
}

var sh = split(9846513, 5, 3)
var newshares = [sh[1], sh[3], sh[4]]; 

document.write(join(newshares));

</script>

When I try to run this code, instead of 9846513 the result is 761. Can someone help me to fix this logical error?


Solution

  • According to the formula, the number your are trying to reconstruct must be less than the prime number used in the algorithm.

    You must use a prime number larger that 9846513... next largest prime is 9846517

    var prime = 9846517;
    ...
    var sh = split(9846513, 5, 3)
    var newshares = [sh[1], sh[3], sh[4]]; 
    document.write(join(newshares));
    

    Fiddle here: https://jsfiddle.net/brettwgreen/gz84bw83/