-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsecret-sharing.mjs
38 lines (28 loc) · 890 Bytes
/
secret-sharing.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import { bls12_381 } from '@noble/curves/bls12-381'
import * as polynomials from './polynomials.mjs'
import { getRandomElement } from './random.mjs'
const defaultField = bls12_381.fields.Fr
export function generateShares(secret, numberThreshold, numberShares, field = defaultField) {
const coefficients = [secret]
for(let i = 0; i < numberThreshold - 1; i++) {
coefficients.push(
getRandomElement(field)
)
}
const result = []
for(let i = 0; i < numberShares; i++) {
result.push({
number: BigInt(i + 1),
subSecret: polynomials.evaluate(coefficients, BigInt(i + 1), field)
})
}
return result
}
export function reconstructSecret(shares, field = defaultField) {
const keyCoefficients = polynomials.lagrange(
shares.map(({ number }) => number),
shares.map(({ subSecret }) => subSecret),
field
)
return polynomials.evaluate(keyCoefficients, 0n, field)
}