Skip to content

Commit d6661ac

Browse files
committed
fix shamir share parsing
1 parent a115f2b commit d6661ac

2 files changed

Lines changed: 54 additions & 3 deletions

File tree

utils/shamir/shamir.go

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"errors"
66
"fmt"
77
. "math/big"
8+
"strings"
89

910
"auth_next/utils"
1011
)
@@ -30,9 +31,17 @@ func (share Share) ToString() string {
3031

3132
func FromString(rawShare string) (Share, error) {
3233
share := Share{new(Int), new(Int)}
33-
_, err := fmt.Sscanf(rawShare, "%v\n%v", share.X, share.Y)
34-
if err != nil {
35-
return share, err
34+
35+
fields := strings.Fields(rawShare)
36+
if len(fields) != 2 {
37+
return share, fmt.Errorf("invalid share format: expected exactly two decimal integer coordinates, got %d", len(fields))
38+
}
39+
40+
if _, ok := share.X.SetString(fields[0], 10); !ok {
41+
return share, errors.New("invalid share x coordinate: expected a decimal integer")
42+
}
43+
if _, ok := share.Y.SetString(fields[1], 10); !ok {
44+
return share, errors.New("invalid share y coordinate: expected a decimal integer")
3645
}
3746
return share, nil
3847
}

utils/shamir/shamir_test.go

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package shamir
33
import (
44
"fmt"
55
. "math/big"
6+
"strings"
67
"testing"
78
)
89

@@ -18,6 +19,47 @@ func TestFromString(t *testing.T) {
1819
t.Log(share)
1920
}
2021

22+
func TestFromStringAllowsSurroundingWhitespace(t *testing.T) {
23+
share, err := FromString(" \r\n12333333333333333333333333\r\n45666666666666666666666666666\n ")
24+
if err != nil {
25+
t.Fatal(err)
26+
}
27+
if share.X.String() != "12333333333333333333333333" {
28+
t.Fatalf("unexpected x coordinate: %s", share.X)
29+
}
30+
if share.Y.String() != "45666666666666666666666666666" {
31+
t.Fatalf("unexpected y coordinate: %s", share.Y)
32+
}
33+
}
34+
35+
func TestFromStringRejectsEmptyShare(t *testing.T) {
36+
_, err := FromString("")
37+
if err == nil {
38+
t.Fatal("expected empty share to fail")
39+
}
40+
if strings.Contains(err.Error(), "number has no digits") {
41+
t.Fatalf("expected a clear share format error, got %q", err)
42+
}
43+
}
44+
45+
func TestFromStringRejectsInvalidCoordinate(t *testing.T) {
46+
_, err := FromString("123\n")
47+
if err == nil {
48+
t.Fatal("expected incomplete share to fail")
49+
}
50+
if !strings.Contains(err.Error(), "expected exactly two decimal integer coordinates") {
51+
t.Fatalf("unexpected error: %v", err)
52+
}
53+
54+
_, err = FromString("123\nabc")
55+
if err == nil {
56+
t.Fatal("expected invalid y coordinate to fail")
57+
}
58+
if !strings.Contains(err.Error(), "invalid share y coordinate") {
59+
t.Fatalf("unexpected error: %v", err)
60+
}
61+
}
62+
2163
func TestEncryptAndDecrypt(t *testing.T) {
2264
secret := "123456"
2365
shares, err := Encrypt(secret, 7, 4)

0 commit comments

Comments
 (0)