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.

64 lines
2.1 KiB

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