shamirsecretsharing/README.md
README.mdRaw
1# Shamir Secret Sharing [](https://goreportcard.com/report/github.com/arnaucube/shamirsecretsharing) [](https://godoc.org/github.com/arnaucube/shamirsecretsharing)
2This repo contains a Go lang implementation of Shamir Secret Sharing, and a compiled Web Assembly version from the Go code to be used from the browser.
3
4- https://en.wikipedia.org/wiki/Shamir%27s_Secret_Sharing
5
6## Wasm usage
7Compile to wasm, inside the `wasm` directory, execute:
8```
9GOARCH=wasm GOOS=js go build -o shamirsecretsharing.wasm shamirsecretsharing-wasm-wrapper.go
10```
11
12Add the file `wasm_exec.js` in the directory:
13```
14cp "$(go env GOROOT)/misc/wasm/wasm_exec.js" .
15```
16
17Call the library from javascript:
18```js
19// Create shares from a secret
20// nNeededShares: number of secrets needed
21// nShares: number of shares
22// p: random point
23// k: secret to share
24createShares(nNeededShares, nShares, p, k);
25```
26
27## Usage from Go
28```go
29// define secret to share
30k, ok := new(big.Int).SetString("123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890", 10)
31assert.True(t, ok)
32
33// define random prime
34p, err := rand.Prime(rand.Reader, bits/2)
35assert.Nil(t, err)
36
37// define how many shares want to generate
38nShares := big.NewInt(int64(6))
39
40// define how many shares are needed to recover the secret
41nNeededShares := big.NewInt(int64(3))
42
43// create the shares
44shares, err := Create(
45 nNeededShares,
46 nShares,
47 p,
48 big.NewInt(int64(k)))
49assert.Nil(t, err)
50
51// select shares to use
52var sharesToUse [][]*big.Int
53sharesToUse = append(sharesToUse, shares[2])
54sharesToUse = append(sharesToUse, shares[1])
55sharesToUse = append(sharesToUse, shares[0])
56
57// recover the secret using Lagrange Interpolation
58secr := LagrangeInterpolation(sharesToUse, p)
59
60// check that the restored secret matches the original secret
61if !bytes.Equal(k.Bytes(), secr.Bytes()) {
62 fmt.Println("reconstructed secret not correspond to original secret")
63}
64```