-
Notifications
You must be signed in to change notification settings - Fork 0
/
share.go
86 lines (66 loc) · 1.85 KB
/
share.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package shamir
import (
"encoding/base64"
"fmt"
"regexp"
"strconv"
)
const SharePrefix string = "shamir"
type Share struct {
secret_id string
primitivePoly int64
x GfElement // x coordinate
y []GfElement // y coordinates
}
func NewShare(secret_id string, primitivePoly int64, x GfElement, y []GfElement) Share {
return Share{secret_id: secret_id, primitivePoly: primitivePoly, x: x, y: y}
}
func NewSharesFromString(input string) ([]Share, error) {
r := regexp.MustCompile(`shamir-(\w+)-(\w+)-(\w+)-([\w\+\/]+)`)
shares := make([]Share, 0)
matches := r.FindAllStringSubmatch(input, -1)
for _, match := range matches {
secret_id := string(match[1])
primitivePoly, err := strconv.ParseInt(string(match[2]), 16, 64)
if err != nil {
return nil, err
}
xdata, err := strconv.ParseInt(string(match[3]), 10, 64)
if err != nil {
return nil, err
}
ydata, err := base64.RawStdEncoding.DecodeString(string(match[4]))
if err != nil {
return nil, err
}
x := GfElement(xdata)
y := make([]GfElement, len(ydata))
for i := range ydata {
y[i] = GfElement(ydata[i])
}
shares = append(shares, NewShare(secret_id, primitivePoly, x, y))
}
return shares, nil
}
func (share Share) ShareLabel() string {
return fmt.Sprintf("%s-%s-%x-%s", SharePrefix, share.secret_id, share.primitivePoly, share.GetXString())
}
func (share Share) String() string {
return fmt.Sprintf("%s-%s", share.ShareLabel(), share.GetYString())
}
func (share Share) GetSecretId() string {
return share.secret_id
}
func (share Share) GetPrimitivePoly() int64 {
return share.primitivePoly
}
func (share Share) GetXString() string {
return fmt.Sprintf("%d", share.x)
}
func (share Share) GetYString() string {
b := make([]byte, len(share.y))
for i := range b {
b[i] = byte(share.y[i])
}
return base64.RawStdEncoding.EncodeToString(b)
}