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