-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmethod.go
113 lines (83 loc) · 2.06 KB
/
method.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package main
import (
"bytes"
"encoding/base64"
"errors"
"log"
"strings"
"time"
sss "github.com/dsprenkels/sss-go"
"github.com/google/uuid"
)
type Secret struct {
UnsealPools map[string]*Pool
}
type CreateInput struct {
Name, Secret string
KeepersNum, KeepersRequired int
}
type UnsealInput struct {
Pool, Share string
}
type Share string
type Shares []Share
func NewSecret() *Secret {
s := &Secret{UnsealPools: make(map[string]*Pool)}
return s
}
func (e *Secret) StartUnseal(_, reply *string) error {
if len(e.UnsealPools) >= 10000 {
return errors.New("to_many_unseals")
}
id := uuid.New().String()
*reply = id
e.UnsealPools[id] = NewPool()
go func() {
<-time.After(10 * time.Minute)
delete(e.UnsealPools, id)
}()
return nil
}
func (e *Secret) Unseal(in *UnsealInput, reply *string) error {
pool, ok := e.UnsealPools[in.Pool]
if !ok {
return errors.New("no_unseal")
}
pool.Add(in.Share)
restored, err := sss.CombineShares(pool.Shares)
if err != nil {
return errors.New("restoration_failed")
}
secret := string(bytes.Trim(restored, "\x00"))
if !strings.HasPrefix(secret, "~!") || !strings.HasSuffix(secret, "!~") {
return errors.New("need_more_shares")
}
secret = strings.TrimPrefix(secret, "~!")
secret = strings.TrimSuffix(secret, "!~")
secret = strings.TrimSpace(secret)
*reply = secret
return nil
}
func (e *Secret) Seal(in *CreateInput, reply *Shares) error {
in.Secret = strings.TrimSpace(in.Secret)
if len([]byte(in.Secret)) > 60 {
return errors.New("Secret is too long")
}
secret := []byte("~!" + in.Secret + "!~")
if in.KeepersNum > 255 {
return errors.New("Too many secret keepers")
}
if in.KeepersRequired > in.KeepersNum {
return errors.New("The number of keepers required must be less than their total number")
}
data := make([]byte, 64)
copy(data, secret)
shares, err := sss.CreateShares(data, in.KeepersNum, in.KeepersRequired)
if err != nil {
log.Fatalln(err)
}
for _, s := range shares {
*reply = append(*reply, Share(base64.StdEncoding.EncodeToString(s)))
}
return nil
}