This repository has been archived by the owner on Mar 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
secret.go
113 lines (95 loc) · 2.21 KB
/
secret.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
/*
Secret Sharing wrapper functionality
*/
package backuplib
import (
"github.com/iden3/go-backup/ff"
"github.com/iden3/go-backup/shamir"
)
type Share struct {
Px int
Py []byte
}
type Shares struct {
Data []Share
}
type Secret struct {
shamir.Shamir
}
func GetNShares() int {
shares := GetShares()
return len(shares.Data)
}
func GetShare(n int) *Share {
shares := GetShares()
if n < len(shares.Data) {
return &shares.Data[n]
} else {
return nil
}
}
// Generate shares from secret
func GenerateShares(secret []byte) {
// convert secret to right format
secretFF, _ := ff.NewElement(PRIME)
secretFF.FromByte(secret)
secretCfg := GetSecretCfg()
sharesGo, _ := secretCfg.GenerateShares(secretFF)
sharesMobile := GetShares()
sharesMobile.Data = fromShares(sharesGo)
SetShares(sharesMobile)
}
func toShares(shares *Shares) []shamir.Share {
sharesGo := make([]shamir.Share, 0)
secretConfig := GetSecretCfg()
for _, share := range shares.Data {
newEl, _ := ff.NewElement(secretConfig.GetElType())
newShareGo := shamir.Share{Px: share.Px,
Py: newEl.FromByte(share.Py)}
sharesGo = append(sharesGo, newShareGo)
}
return sharesGo
}
func fromShares(shares []shamir.Share) []Share {
sharesMobile := make([]Share, 0)
for _, share := range shares {
newShareMobile := Share{Px: share.Px,
Py: share.Py.ToByte()}
sharesMobile = append(sharesMobile, newShareMobile)
}
return sharesMobile
}
// Generate secret from shares
func GenerateKey() []byte {
sharesGo := toShares(GetShares())
return generateKey(sharesGo, GetSecretCfg())
}
func generateKey(shares []shamir.Share, sharingCfg *Secret) []byte {
sharesPool := make([]shamir.Share, 0)
for _, share := range shares {
sharesPool = append(sharesPool, share)
if len(sharesPool) == sharingCfg.GetMinShares() {
break
}
}
secret, err := sharingCfg.GenerateSecret(sharesPool)
if err != nil {
panic(err)
}
return secret.ToByte()
}
func initSecretCfg() {
var secretCfg Secret
cfg, err := shamir.NewConfig(MIN_N_SHARES, MAX_N_SHARES, PRIME)
if err != nil {
panic(err)
}
secretCfg.Shamir = *cfg
SetSecretCfg(&secretCfg)
}
func initSecretShares() {
var shares Shares
shareData := make([]Share, 0)
shares.Data = shareData
SetShares(&shares)
}