├── .github └── workflows │ ├── goreadme.yml │ └── test.yml ├── LICENSE ├── README.md ├── go.mod ├── go.sum ├── internal └── polynom │ ├── polynom.go │ └── polynom_test.go ├── sharedsecret.go └── sharedsecret_test.go /.github/workflows/goreadme.yml: -------------------------------------------------------------------------------- 1 | on: 2 | pull_request: 3 | branches: [master] 4 | push: 5 | branches: [master] 6 | jobs: 7 | goreadme: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - name: Check out repository 11 | uses: actions/checkout@v2 12 | - name: Update readme according to Go doc 13 | uses: posener/goreadme@v1.2.13 14 | with: 15 | recursive: 'true' 16 | badge-codecov: 'true' 17 | badge-godoc: 'true' 18 | github-token: '${{ secrets.GITHUB_TOKEN }}' 19 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | on: 2 | pull_request: 3 | branches: [master] 4 | push: 5 | branches: [master] 6 | jobs: 7 | test: 8 | strategy: 9 | matrix: 10 | go-version: 11 | - 1.13.x 12 | - 1.14.x 13 | platform: 14 | - ubuntu-latest 15 | - macos-latest 16 | runs-on: ${{ matrix.platform }} 17 | steps: 18 | - name: Install Go 19 | uses: actions/setup-go@v1 20 | with: 21 | go-version: ${{ matrix.go-version }} 22 | - name: Checkout code 23 | uses: actions/checkout@v2 24 | - name: Test 25 | run: go test -v -race -coverprofile=coverage.txt -covermode=atomic ./... 26 | - name: Report coverage 27 | uses: codecov/codecov-action@v1 28 | with: 29 | file: coverage.txt 30 | fail_ci_if_error: true -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # sharedsecret 2 | 3 | [![codecov](https://codecov.io/gh/posener/sharedsecret/branch/master/graph/badge.svg)](https://codecov.io/gh/posener/sharedsecret) 4 | [![GoDoc](https://img.shields.io/badge/pkg.go.dev-doc-blue)](http://pkg.go.dev/github.com/posener/sharedsecret) 5 | 6 | Package sharedsecret is implementation of Shamir's Secret Sharing algorithm. 7 | 8 | Shamir's Secret Sharing is an algorithm in cryptography created by Adi Shamir. It is a form of 9 | secret sharing, where a secret is divided into parts, giving each participant its own unique 10 | part. To reconstruct the original secret, a minimum number of parts is required. In the threshold 11 | scheme this number is less than the total number of parts. Otherwise all participants are needed 12 | to reconstruct the original secret. 13 | See [wiki page](https://en.wikipedia.org/wiki/Shamir's_Secret_Sharing). 14 | 15 | ## Examples 16 | 17 | ### Distribute 18 | 19 | With the `Distribute` function, a given secret can be distributed to shares. 20 | 21 | ```golang 22 | secret := big.NewInt(120398491412912873) 23 | 24 | // Create 5 shares that 3 or more of them can recover the secret. 25 | shares := Distribute(secret, 5, 3) 26 | 27 | // We can recover from only 3 (or more) shares: 28 | recovered := Recover(shares[1], shares[3], shares[0]) 29 | 30 | fmt.Println(recovered) 31 | ``` 32 | 33 | Output: 34 | 35 | ``` 36 | 120398491412912873 37 | ``` 38 | 39 | ### New 40 | 41 | With the `New` function, a random secret is generated and distributed into shares. Both the 42 | secret and the shares are returned. 43 | 44 | ```golang 45 | // Create 5 shares that 3 or more of them can recover the secret. 46 | shares, secret := New(5, 3) 47 | 48 | // Now we should distribute the shares to different parties and forget about the shares and 49 | // secret. Once the original secret is needed, at least 3 shares should be used in order to 50 | // recover it: 51 | 52 | // We can't recover from only 2 shares: 53 | wrong := Recover(shares[1], shares[3]) 54 | 55 | // We can recover from only 3 (or more) shares: 56 | correct := Recover(shares[1], shares[3], shares[0]) 57 | 58 | fmt.Println(secret.Cmp(wrong) != 0, secret.Cmp(correct) == 0) 59 | ``` 60 | 61 | Output: 62 | 63 | ``` 64 | true true 65 | ``` 66 | 67 | --- 68 | Readme created from Go doc with [goreadme](https://github.com/posener/goreadme) 69 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/posener/sharedsecret 2 | 3 | go 1.13 4 | 5 | require github.com/stretchr/testify v1.4.0 6 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= 2 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 4 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 5 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 6 | github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= 7 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= 8 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 9 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 10 | gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= 11 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 12 | -------------------------------------------------------------------------------- /internal/polynom/polynom.go: -------------------------------------------------------------------------------- 1 | package polynom 2 | 3 | import ( 4 | "crypto/rand" 5 | "fmt" 6 | "math/big" 7 | ) 8 | 9 | // Polynom represents a big integer polynom. 10 | type Polynom struct { 11 | // coeff are the coefficients of the polynom. coeff[i] is the coefficient of x^i. 12 | coeff []*big.Int 13 | // mod is the modulus for polynom arithmetics calculations. 14 | mod *big.Int 15 | } 16 | 17 | // NewRandom returns a new random polynom of the given degree, which is subjected to arithmetics of 18 | // the given modulus. 19 | func NewRandom(degree int64, modulus *big.Int) Polynom { 20 | if degree <= 0 { 21 | panic("deg must be positive number") 22 | } 23 | 24 | var ( 25 | err error 26 | coeff = make([]*big.Int, degree) 27 | ) 28 | for i := range coeff { 29 | coeff[i], err = rand.Int(rand.Reader, modulus) 30 | if err != nil { 31 | panic(fmt.Sprintf("creating random int: %s", err)) 32 | } 33 | } 34 | return Polynom{coeff: coeff, mod: modulus} 35 | } 36 | 37 | // Deg returns the degree of the polynom. 38 | func (p Polynom) Deg() int { 39 | return len(p.coeff) 40 | } 41 | 42 | // Coeff returns the i'th coefficient. 43 | // 44 | // Can panic with index out of range when i >= p.Deg(). 45 | func (p Polynom) Coeff(i int) *big.Int { 46 | return cp(p.coeff[i]) 47 | } 48 | 49 | // SetCoeff sets the i'th coefficient. 50 | // 51 | // Can panic with index out of range when i >= p.Deg(). 52 | func (p Polynom) SetCoeff(i int, v *big.Int) { 53 | v = cp(v) 54 | p.coeff[i] = v.Mod(v, p.mod) 55 | } 56 | 57 | // ValueAt returns the y value of the polynom on a given x0 value. 58 | func (p Polynom) ValueAt(x0 *big.Int) *big.Int { 59 | val := big.NewInt(0) 60 | for i := len(p.coeff) - 1; i >= 0; i-- { 61 | val.Mul(val, x0) 62 | val.Add(val, p.coeff[i]) 63 | val.Mod(val, p.mod) 64 | } 65 | return val 66 | } 67 | 68 | // Interpolate returns the y value at x0 of a polynom that lies on points (x[i], y[i]), with modulus 69 | // arithmetics for the given modulus. 70 | func Interpolate(x0 *big.Int, x []*big.Int, y []*big.Int, modulus *big.Int) (y0 *big.Int) { 71 | if len(x) != len(y) { 72 | return nil // x and y lists must have the same length. 73 | } 74 | 75 | nums := make([]*big.Int, len(x)) 76 | dens := make([]*big.Int, len(x)) 77 | 78 | for i := range x { 79 | nums[i] = product(x, x0, i) 80 | dens[i] = product(x, x[i], i) 81 | } 82 | 83 | den := product(dens, nil, -1) 84 | 85 | num := big.NewInt(0) 86 | for i := range nums { 87 | nums[i].Mul(nums[i], den) 88 | nums[i].Mul(nums[i], y[i]) 89 | nums[i].Mod(nums[i], modulus) 90 | v := divmod(nums[i], dens[i], modulus) 91 | if v == nil { 92 | return nil // x values are not distinct. 93 | } 94 | num.Add(num, v) 95 | } 96 | 97 | y0 = divmod(num, den, modulus) 98 | y0.Add(y0, modulus) 99 | y0.Mod(y0, modulus) 100 | return y0 101 | } 102 | 103 | // product returns the product of vals. If sub is given, the returned product is of (sub-vals[i]). 104 | // If skip is given, the i'th value will be ignored. 105 | func product(vals []*big.Int, sub *big.Int, skip int) *big.Int { 106 | p := big.NewInt(1) 107 | for i := range vals { 108 | if i == skip { 109 | continue 110 | } 111 | v := cp(vals[i]) 112 | if sub != nil { 113 | v.Sub(sub, v) 114 | } 115 | p.Mul(p, v) 116 | } 117 | return p 118 | } 119 | 120 | // divmod computes num / den modulo mod. 121 | func divmod(a, b, mod *big.Int) *big.Int { 122 | b = b.ModInverse(b, mod) 123 | if b == nil { 124 | return nil 125 | } 126 | return a.Mul(a, b) 127 | } 128 | 129 | // cp copies a big.Int. 130 | func cp(v *big.Int) *big.Int { 131 | var u big.Int 132 | u.Set(v) 133 | return &u 134 | } 135 | -------------------------------------------------------------------------------- /internal/polynom/polynom_test.go: -------------------------------------------------------------------------------- 1 | package polynom 2 | 3 | import ( 4 | "crypto/rand" 5 | "math/big" 6 | "testing" 7 | 8 | "github.com/stretchr/testify/assert" 9 | "github.com/stretchr/testify/require" 10 | ) 11 | 12 | func TestInterpolate(t *testing.T) { 13 | t.Parallel() 14 | t.Run("simple", func(t *testing.T) { 15 | x := []*big.Int{big.NewInt(0), big.NewInt(2)} 16 | got := Interpolate(big.NewInt(1), x, x, big.NewInt(3)) 17 | assert.Equal(t, big.NewInt(1), got) 18 | }) 19 | 20 | t.Run("at given points", func(t *testing.T) { 21 | mod := big.NewInt(13) 22 | x := []*big.Int{big.NewInt(1), big.NewInt(12), big.NewInt(6)} 23 | y := []*big.Int{big.NewInt(4), big.NewInt(2), big.NewInt(7)} 24 | 25 | assert.Equal(t, big.NewInt(4), Interpolate(big.NewInt(1), x, y, mod)) 26 | assert.Equal(t, big.NewInt(2), Interpolate(big.NewInt(12), x, y, mod)) 27 | assert.Equal(t, big.NewInt(7), Interpolate(big.NewInt(6), x, y, mod)) 28 | }) 29 | } 30 | 31 | func TestInterpolate_panic(t *testing.T) { 32 | t.Parallel() 33 | t.Run("Different array sizes", func(t *testing.T) { 34 | result := Interpolate(big.NewInt(0), []*big.Int{big.NewInt(1), big.NewInt(2)}, []*big.Int{big.NewInt(1)}, big.NewInt(11)) 35 | assert.Nil(t, result) 36 | }) 37 | t.Run("x points are not unique", func(t *testing.T) { 38 | result := Interpolate(big.NewInt(0), []*big.Int{big.NewInt(1), big.NewInt(1)}, []*big.Int{big.NewInt(1), big.NewInt(2)}, big.NewInt(11)) 39 | assert.Nil(t, result) 40 | }) 41 | } 42 | 43 | func TestNewRandom(t *testing.T) { 44 | t.Parallel() 45 | p := NewRandom(1, big.NewInt(11)) 46 | assert.Equal(t, 1, p.Deg()) 47 | assert.Equal(t, p.ValueAt(big.NewInt(0)), p.Coeff(0)) 48 | } 49 | 50 | func TestNewRandom_def2Fuzz(t *testing.T) { 51 | t.Parallel() 52 | for i := 0; i < 10000; i++ { 53 | x, err := rand.Int(rand.Reader, big.NewInt(10000)) 54 | require.NoError(t, err) 55 | 56 | mod, err := rand.Int(rand.Reader, big.NewInt(10000)) 57 | mod.Add(mod, big.NewInt(1)) // mod should be greater than 0 58 | require.NoError(t, err) 59 | 60 | p := NewRandom(2, mod) 61 | 62 | want := cp(p.Coeff(1)) 63 | want.Mul(want, x) 64 | want.Add(want, p.Coeff(0)) 65 | want.Mod(want, mod) 66 | 67 | assert.Equal(t, p.ValueAt(x), want) 68 | } 69 | } 70 | 71 | func TestNewRandom_panic(t *testing.T) { 72 | t.Parallel() 73 | assert.Panics(t, func() { NewRandom(0, big.NewInt(11)) }) 74 | assert.Panics(t, func() { NewRandom(-1, big.NewInt(11)) }) 75 | } 76 | -------------------------------------------------------------------------------- /sharedsecret.go: -------------------------------------------------------------------------------- 1 | // Package sharedsecret is implementation of Shamir's Secret Sharing algorithm. 2 | // 3 | // Shamir's Secret Sharing is an algorithm in cryptography created by Adi Shamir. It is a form of 4 | // secret sharing, where a secret is divided into parts, giving each participant its own unique 5 | // part. To reconstruct the original secret, a minimum number of parts is required. In the threshold 6 | // scheme this number is less than the total number of parts. Otherwise all participants are needed 7 | // to reconstruct the original secret. 8 | // See (wiki page) https://en.wikipedia.org/wiki/Shamir's_Secret_Sharing. 9 | package sharedsecret 10 | 11 | import ( 12 | "bytes" 13 | "errors" 14 | "math/big" 15 | 16 | "github.com/posener/sharedsecret/internal/polynom" 17 | ) 18 | 19 | // prime128 is a large prime number that fits into 128 bits (value of 2^127 - 1). 20 | var prime128 = prime128Value() 21 | 22 | // Share is a part of a secret. 23 | type Share struct { 24 | x, y *big.Int 25 | } 26 | 27 | // New creates n Shares and a secret. k defines the minimum number of shares that should be 28 | // collected in order to recover the secret. Recovering the secret can be done by calling Recover 29 | // with more than k Share objects. 30 | func New(n, k int64) (shares []Share, secret *big.Int) { 31 | return distribute(nil, n, k) 32 | } 33 | 34 | // Distribute creates n Shares for a given secret. k defines the minimum number of shares that 35 | // should be collected in order to recover the secret. Recovering the secret can be done by calling 36 | // Recover with more than k Share objects. 37 | func Distribute(secret *big.Int, n, k int64) (shares []Share) { 38 | shares, _ = distribute(secret, n, k) 39 | return shares 40 | } 41 | 42 | // distribute creates n shares. The secret argument is optional. It returns the shares and the 43 | // secret for the shares. 44 | func distribute(secret *big.Int, n, k int64) ([]Share, *big.Int) { 45 | if n < k { 46 | panic("irrecoverable: not enough shares to reconstruct the secret.") 47 | } 48 | if k <= 0 { 49 | panic("number of shares must be positive.") 50 | } 51 | p := polynom.NewRandom(k, prime128) 52 | 53 | // Set the first coefficient to the secret (the value at x=0) if the secret was given. And 54 | // anyway store the first coefficient in the secret variable. 55 | if secret != nil { 56 | if secret.Cmp(prime128) > 0 { 57 | panic("secret value is too big (must be lower than 2^127 - 1)") 58 | } 59 | p.SetCoeff(0, secret) 60 | } 61 | secret = p.Coeff(0) 62 | 63 | // Create the shares which are the value of p at any point but x != 0. Choose x in [1..n]. 64 | shares := make([]Share, 0, n) 65 | for i := int64(1); i <= n; i++ { 66 | x := big.NewInt(i) 67 | y := p.ValueAt(x) 68 | shares = append(shares, Share{x: x, y: y}) 69 | } 70 | 71 | return shares, secret 72 | } 73 | 74 | // Recover the secret from shares. Notice that the number of shares that is used should be at least 75 | // the recover amount (k) that was used in order to create them in the New function. 76 | func Recover(shares ...Share) (secret *big.Int) { 77 | // Convert the shares to a list of points x[i], y[i]. 78 | xs := make([]*big.Int, len(shares)) 79 | ys := make([]*big.Int, len(shares)) 80 | for i := range shares { 81 | xs[i] = shares[i].x 82 | ys[i] = shares[i].y 83 | } 84 | // Evaluate the polynom that goes through all (x[i], y[i]) points at x=0. 85 | return polynom.Interpolate(big.NewInt(0), xs, ys, prime128) 86 | } 87 | 88 | // String dumps the share object to a string. 89 | func (s Share) String() string { 90 | return s.x.String() + "," + s.y.String() 91 | } 92 | 93 | // MarshalText implements the encoding.TextMarshaler interface. 94 | func (s Share) MarshalText() ([]byte, error) { 95 | x, err := s.x.MarshalText() 96 | if err != nil { 97 | return nil, err 98 | } 99 | y, err := s.y.MarshalText() 100 | if err != nil { 101 | return nil, err 102 | } 103 | return append(append(x, ','), y...), nil 104 | } 105 | 106 | // UnmarshalText implements the encoding.TextUnmarshaler interface. 107 | func (s *Share) UnmarshalText(txt []byte) error { 108 | parts := bytes.Split(txt, []byte{','}) 109 | if len(parts) != 2 { 110 | return errors.New("expected two parts") 111 | } 112 | s.x = &big.Int{} 113 | s.y = &big.Int{} 114 | err := s.x.UnmarshalText(parts[0]) 115 | if err != nil { 116 | return err 117 | } 118 | return s.y.UnmarshalText(parts[1]) 119 | } 120 | 121 | // prime128 returns a large prime that fits into 128 bits. It is 12th Mersenne Prime. (for this 122 | // application we want a known prime number as close as possible to our security level; e.g. desired 123 | // security level of 128 bits -- too large and all the ciphertext is large; too small and security 124 | // is compromised) It is equal to 2^127 - 1. (13th Mersenne Prime is 2^521 - 1). 125 | func prime128Value() *big.Int { 126 | p := big.NewInt(2) 127 | p.Exp(p, big.NewInt(127), nil) 128 | p.Sub(p, big.NewInt(1)) 129 | return p 130 | } 131 | -------------------------------------------------------------------------------- /sharedsecret_test.go: -------------------------------------------------------------------------------- 1 | package sharedsecret 2 | 3 | import ( 4 | "crypto/rand" 5 | "fmt" 6 | "math/big" 7 | "testing" 8 | 9 | "github.com/stretchr/testify/assert" 10 | "github.com/stretchr/testify/require" 11 | ) 12 | 13 | // With the `New` function, a random secret is generated and distributed into shares. Both the 14 | // secret and the shares are returned. 15 | func Example_new() { 16 | // Create 5 shares that 3 or more of them can recover the secret. 17 | shares, secret := New(5, 3) 18 | 19 | // Now we should distribute the shares to different parties and forget about the shares and 20 | // secret. Once the original secret is needed, at least 3 shares should be used in order to 21 | // recover it: 22 | 23 | // We can't recover from only 2 shares: 24 | wrong := Recover(shares[1], shares[3]) 25 | 26 | // We can recover from only 3 (or more) shares: 27 | correct := Recover(shares[1], shares[3], shares[0]) 28 | 29 | fmt.Println(secret.Cmp(wrong) != 0, secret.Cmp(correct) == 0) 30 | // Output: true true 31 | } 32 | 33 | // With the `Distribute` function, a given secret can be distributed to shares. 34 | func Example_distribute() { 35 | secret := big.NewInt(120398491412912873) 36 | 37 | // Create 5 shares that 3 or more of them can recover the secret. 38 | shares := Distribute(secret, 5, 3) 39 | 40 | // We can recover from only 3 (or more) shares: 41 | recovered := Recover(shares[1], shares[3], shares[0]) 42 | 43 | fmt.Println(recovered) 44 | // Output: 120398491412912873 45 | } 46 | 47 | const ( 48 | testN = 10 49 | testK = 4 50 | ) 51 | 52 | func TestNewRecover_sanity(t *testing.T) { 53 | t.Parallel() 54 | 55 | // Create testN shares that testK or more of them can recover the secret. 56 | shares, secret := New(testN, testK) 57 | 58 | testSharesAndSecret(t, shares, secret) 59 | } 60 | 61 | func TestDistributeRecover_sanity(t *testing.T) { 62 | t.Parallel() 63 | 64 | // Create a secret and distribute it to testN shares that testK or more of them can recover the 65 | // secret. 66 | secret := big.NewInt(123456) 67 | shares := Distribute(secret, testN, testK) 68 | 69 | testSharesAndSecret(t, shares, secret) 70 | } 71 | 72 | func testSharesAndSecret(t *testing.T, shares []Share, secret *big.Int) { 73 | t.Run("All shares should recover", func(t *testing.T) { 74 | assert.Equal(t, secret, Recover(shares...)) 75 | }) 76 | 77 | t.Run("The minimum number of shares should recover", func(t *testing.T) { 78 | assert.Equal(t, secret, Recover(shares[:testK]...)) 79 | assert.Equal(t, secret, Recover(shares[testK:]...)) 80 | }) 81 | 82 | t.Run("Less than the minimum number of shares should not recover", func(t *testing.T) { 83 | assert.NotEqual(t, secret, Recover(shares[:testK-1]...)) 84 | assert.NotEqual(t, secret, Recover(shares[testN-testK+1:]...)) 85 | }) 86 | 87 | t.Run("minimum number with repeated share should not recover", func(t *testing.T) { 88 | shares := shares[:testK-1] 89 | shares = append(shares, shares[0]) 90 | assert.NotEqual(t, secret, Recover(shares...)) 91 | assert.NotEqual(t, secret, Recover(shares...)) 92 | }) 93 | } 94 | 95 | func TestNew_panic(t *testing.T) { 96 | t.Parallel() 97 | 98 | secret := big.NewInt(123456) 99 | secretTooBig := big.NewInt(2) 100 | secretTooBig.Exp(secretTooBig, big.NewInt(127), nil) 101 | 102 | assert.Panics(t, func() { New(1, 2) }) 103 | assert.Panics(t, func() { New(1, 0) }) 104 | assert.Panics(t, func() { Distribute(secret, 1, 2) }) 105 | assert.Panics(t, func() { Distribute(secret, 1, 0) }) 106 | assert.Panics(t, func() { Distribute(secretTooBig, testN, testK) }) 107 | } 108 | 109 | func TestShareString(t *testing.T) { 110 | t.Parallel() 111 | s := Share{big.NewInt(0), big.NewInt(1)} 112 | assert.Equal(t, "0,1", s.String()) 113 | } 114 | 115 | func TestShareMarshalText_fuzz(t *testing.T) { 116 | t.Parallel() 117 | for i := 0; i < 10000; i++ { 118 | x, err := rand.Int(rand.Reader, big.NewInt(10000)) 119 | require.NoError(t, err) 120 | y, err := rand.Int(rand.Reader, big.NewInt(10000)) 121 | require.NoError(t, err) 122 | want := Share{x: x, y: y} 123 | 124 | text, err := want.MarshalText() 125 | require.NoError(t, err) 126 | var got Share 127 | err = got.UnmarshalText(text) 128 | require.NoError(t, err) 129 | assert.True(t, want.x.Cmp(got.x) == 0) 130 | assert.True(t, want.y.Cmp(got.y) == 0) 131 | } 132 | } 133 | 134 | func TestShareUnMarshalText_errors(t *testing.T) { 135 | t.Parallel() 136 | var s Share 137 | assert.Error(t, s.UnmarshalText([]byte(""))) 138 | assert.Error(t, s.UnmarshalText([]byte("1,2,3"))) 139 | assert.Error(t, s.UnmarshalText([]byte("a,1"))) 140 | assert.Error(t, s.UnmarshalText([]byte("1,a"))) 141 | } 142 | --------------------------------------------------------------------------------