forked from simonfrey/s4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paths4.go
93 lines (75 loc) · 2.03 KB
/
s4.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
package s4
import (
"bytes"
"github.com/hashicorp/vault/shamir"
"github.com/pkg/errors"
"s4/crypto"
)
type Shares [][]byte
var splitCode []byte = []byte("\n*=_=_=_=*\n\n")
func DistributeBytes(in []byte, n, k uint64) (Shares, error) {
if len(in) == 0 {
return nil, errors.New("in must not be empty")
}
return shamir.Split(in, int(n), int(k))
}
func RecoverBytes(in Shares) ([]byte, error) {
if len(in) == 0 {
return nil, errors.New("in must not be empty")
}
return shamir.Combine(in)
}
func DistributeBytesAES(in []byte, n, k uint64) (Shares, error) {
if len(in) == 0 {
return nil, errors.New("in must not be empty")
}
key := crypto.NewEncryptionKey()
byteShares, err := DistributeBytes(key[:], n, k)
if err != nil {
return nil, errors.Wrap(err, "could not distribute bytes")
}
ciphertext, err := crypto.Encrypt(in, key)
if err != nil {
return nil, errors.Wrap(err, "could not aes encrypt input")
}
finalShares := make(Shares, len(byteShares))
for k, byteShare := range byteShares {
finalShares[k] = append(append(byteShare, splitCode...), ciphertext...)
}
return finalShares, nil
}
func RecoverBytesAES(in Shares) ([]byte, error) {
if len(in) == 0 {
return nil, errors.New("in must not be empty")
}
var cipherText []byte
shares := make(Shares, len(in))
for k, s := range in {
s := bytes.Split(s, splitCode)
if len(s) != 2 {
return nil, errors.New("invalid aes base")
}
if len(cipherText) == 0 {
cipherText = s[1]
} else if !bytes.Equal(cipherText, s[1]) {
return nil, errors.New("AES cipher text differs between shares")
}
shares[k] = s[0]
}
recoveredKey, err := RecoverBytes(shares)
if err != nil {
return nil, errors.Wrap(err, "could not recover bytes of key")
}
if len(recoveredKey) != 32 {
return nil, errors.New("recovered key is not size 32 byte")
}
key := [32]byte{}
for k, v := range recoveredKey {
key[k] = v
}
clearText, err := crypto.Decrypt(cipherText, &key)
if err != nil {
return nil, errors.Wrap(err, "could not aes decrypt input")
}
return clearText, nil
}