From 4bc034f24ad2507bffea40bfe00696f8f919141a Mon Sep 17 00:00:00 2001 From: saepire Date: Wed, 31 Jul 2024 23:21:49 +0900 Subject: [PATCH] better readability and error handling --- cmd/sss/main.go | 8 ++++---- shamir.go | 21 +++++---------------- 2 files changed, 9 insertions(+), 20 deletions(-) diff --git a/cmd/sss/main.go b/cmd/sss/main.go index 7357686..54a484d 100644 --- a/cmd/sss/main.go +++ b/cmd/sss/main.go @@ -17,8 +17,8 @@ func main() { encoding := flag.String("encoding", "base64", "Encoding: base64 or hex") secret := flag.String("secret", "", "The secret to split (for split mode)") sharesStr := flag.String("shares", "", "Comma-separated shares (for combine mode)") - N := flag.Int("n", 5, "Total number of shares") - T := flag.Int("t", 3, "Number of shares needed to reconstruct the secret") + n := flag.Int("n", 5, "Total number of shares") + t := flag.Int("t", 3, "Number of shares needed to reconstruct the secret") flag.Parse() switch *mode { @@ -31,9 +31,9 @@ func main() { os.Exit(1) } inputSecret = strings.TrimSpace(inputSecret) - splitSecret(inputSecret, *N, *T, *encoding) + splitSecret(inputSecret, *n, *t, *encoding) } else { - splitSecret(*secret, *N, *T, *encoding) + splitSecret(*secret, *n, *t, *encoding) } case "combine": if *sharesStr == "" { diff --git a/shamir.go b/shamir.go index 1e86a15..4af9eca 100644 --- a/shamir.go +++ b/shamir.go @@ -36,10 +36,6 @@ func newPolynomial(intercept, degree uint8) (*polynomial, error) { } func (p *polynomial) evaluate(x uint8) uint8 { - if x == 0 { - return p.coeffs[0] - } - result := p.coeffs[len(p.coeffs)-1] for i := len(p.coeffs) - 2; i >= 0; i-- { result = gfAdd(gfMult(result, x), p.coeffs[i]) @@ -65,15 +61,10 @@ func Split(secret []byte, n, t int) ([][]byte, error) { return nil, ErrEmptySecret } - xCoords := make([]uint8, n) - for i := 0; i < n; i++ { - xCoords[i] = uint8(i + 1) - } - shares := make([][]byte, n) for i := range shares { shares[i] = make([]byte, len(secret)+1) - shares[i][len(secret)] = xCoords[i] + shares[i][len(secret)] = uint8(i + 1) } for i, b := range secret { @@ -82,8 +73,8 @@ func Split(secret []byte, n, t int) ([][]byte, error) { return nil, err } - for j := 0; j < n; j++ { - shares[j][i] = p.evaluate(xCoords[j]) + for j := range shares { + shares[j][i] = p.evaluate(uint8(j + 1)) } } @@ -180,12 +171,10 @@ func gfDiv(a, b uint8) (uint8, error) { } func gfInverse(a uint8) uint8 { - var inv uint8 for b := uint8(1); b != 0; b++ { if gfMult(a, b) == 1 { - inv = b - break + return b } } - return inv + return 0 // This should never be reached if the input is non-zero }