Skip to content

Commit 17bad7b

Browse files
committedMay 12, 2023
test: Clarify Shamir secret sharing algorithm implementation
- Improve documentation of Shamir's secret sharing algorithm - Add test case for combining parts with a different key - Remove unnecessary offset addition from parts dictionary
1 parent 8587d0b commit 17bad7b

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed
 

‎crypto/threshold/shamir/shamir.go

+4
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ import (
2525
// the secret. The total and threshold must be at least 2, and less
2626
// than 256. The returned shares are each one byte longer than the secret
2727
// as they attach a tag used to reconstruct the secret.
28+
//
29+
// the key and values of members are both important to combine.
2830
func Split(secret []byte, total, threshold int) (members map[byte][]byte, err error) {
2931
switch {
3032
case threshold < 2 || threshold >= 256:
@@ -44,6 +46,8 @@ func Split(secret []byte, total, threshold int) (members map[byte][]byte, err er
4446

4547
// Combine is used to reverse a Split and reconstruct a secret
4648
// once a `threshold` number of parts are available.
49+
//
50+
// the key and value are must as same as splited result.
4751
func Combine(parts map[byte][]byte) ([]byte, error) {
4852
if len(parts) < 2 {
4953
return nil, errors.Errorf("length of parts should >= 2")

‎crypto/threshold/shamir/shamir_test.go

+17-1
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,22 @@ func TestSplit(t *testing.T) {
5151
}
5252
})
5353

54+
t.Run("fulfill threshold with different key", func(t *testing.T) {
55+
for i := 0; i < 10; i++ {
56+
k := randor.Intn(tt.args.total-tt.args.threshold) + tt.args.threshold
57+
58+
parts := map[byte][]byte{}
59+
for i, b := range gutils.RandomChoice(ks, k) {
60+
parts[byte(i)] = members[b]
61+
}
62+
63+
cipher, err := Combine(parts)
64+
t.Logf("total: %d, threshold: %d, parts: %d", tt.args.total, tt.args.threshold, k)
65+
require.NoError(t, err)
66+
require.NotEqual(t, tt.args.secret, cipher)
67+
}
68+
})
69+
5470
t.Run("less than threshold", func(t *testing.T) {
5571
for i := 0; i < 10; i++ {
5672
k := randor.Intn(tt.args.threshold)
@@ -60,7 +76,7 @@ func TestSplit(t *testing.T) {
6076

6177
parts := map[byte][]byte{}
6278
for _, b := range gutils.RandomChoice(ks, k) {
63-
parts[b+33] = members[b]
79+
parts[b] = members[b]
6480
}
6581

6682
cipher, err := Combine(parts)

0 commit comments

Comments
 (0)
Please sign in to comment.