You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
2.1 KiB

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