Created
June 4, 2023 19:40
-
-
Save soltrinox/9acf87b66d2f9b559939fbf10e551af8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const β = require('bignumber.js'); | |
function Ω(a, m) { | |
const b = new β(a).mod(m); | |
for (let x = new β(1); x.lt(m); x = x.plus(1)) { | |
if (b.times(x).mod(m).eq(1)) { | |
return x; | |
} | |
} | |
return new β(1); | |
} | |
function ζ(num) { | |
if (num < 2) { return false; } | |
for (let i = 2; i <= Math.sqrt(num); i++) { | |
if (num % i === 0) { return false; } | |
} | |
return true; | |
} | |
function Φ(bits) { | |
const min = new β(2).pow(bits - 1); | |
const max = new β(2).pow(bits).minus(1); | |
while (true) { | |
const num = new β(max).minus(min).times(Math.random()).plus(min); | |
if (ζ(num)) { | |
return num; | |
} | |
} | |
} | |
function Σ(µ, Θ, λ) { | |
const prime = Φ(256); | |
const ε = [new β(µ)]; | |
for (let i = 1; i < λ; i++) { | |
ε.push(new β(Math.floor(Math.random() * prime.toNumber()))); | |
} | |
const ξ = []; | |
for (let i = 1; i <= Θ; i++) { | |
let share = new β(0); | |
for (let j = 0; j < ε.length; j++) { | |
const term = ε[j].times(new β(i).pow(j)); | |
share = share.plus(term).mod(prime); | |
} | |
ξ.push({ x: i, y: share }); | |
} | |
return ξ; | |
} | |
function Ξ(ξ) { | |
let δ = new β(0); | |
const prime = new β(ξ[0].y).c; | |
for (let i = 0; i < ξ.length; i++) { | |
const x_i = new β(ξ[i].x); | |
const y_i = new β(ξ[i].y); | |
let term = new β(1); | |
for (let j = 0; j < ξ.length; j++) { | |
if (j !== i) { | |
const x_j = new β(ξ[j].x); | |
term = term.times(x_j).dividedBy(x_j.minus(x_i)); | |
} | |
} | |
const inv = Ω(term, prime); | |
δ = δ.plus(y_i.times(term).times(inv)).mod(prime); | |
} | |
return δ.toString(); | |
} | |
// Example usage: | |
const µ = 4321; // secret | |
const Θ = 4; | |
const λ = 3; | |
const ξ = Σ(µ, Θ, λ); | |
console.log('Generated shares:', ξ); | |
const æ = [ξ[0], ξ[3], ξ[6], ξ[9]]; | |
const Љ = Ξ(æ); | |
console.log('Combined µ:', Љ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment