Shamir 秘密分享:我无法在 javascript 中获得正确的重构值

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

我尝试使用shamir 秘密共享。我实现了我在维基百科中找到的代码。但是当我运行它时,对于巨大的数字,重建的结果与真正的秘密值不同。

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

重构函数为:

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>

当我尝试 运行 这段代码时,结果是 761 而不是 9846513。 有人可以帮我解决这个逻辑错误吗?

根据公式,您要重构的数字必须小于算法中使用的素数。

您必须使用大于 9846513 的素数...下一个最大的素数是 9846517

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

Fiddle 这里: https://jsfiddle.net/brettwgreen/gz84bw83/