-
Notifications
You must be signed in to change notification settings - Fork 2
/
protoData.go
81 lines (66 loc) · 1.49 KB
/
protoData.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
package protocrypt
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"github.com/golang/protobuf/proto"
"github.com/racerxdl/protocrypt/internal"
)
type protoData struct {
Fields map[uint]protoField
}
func (pd *protoData) Unmarshal(pb proto.Message) error {
return proto.Unmarshal(pd.Serialize(), pb)
}
func (pd *protoData) DecryptAndUnmarshal(fieldsToEncrypt []uint, key []byte, pb proto.Message) error {
err := pd.DecryptFields(fieldsToEncrypt, key)
if err != nil {
return err
}
return pd.Unmarshal(pb)
}
func (pd *protoData) EncryptFields(fieldsToEncrypt []uint, key []byte) error {
fte := internal.UIntSlice(fieldsToEncrypt)
c, err := aes.NewCipher(key)
if err != nil {
return err
}
gcm, _ := cipher.NewGCM(c)
fte.Sort()
for _, fieldNum := range fte {
if src, ok := pd.Fields[fieldNum]; ok {
dst, err := encryptField(src, gcm)
if err != nil {
return err
}
pd.Fields[fieldNum] = dst
}
}
return nil
}
func (pd *protoData) DecryptFields(fieldsToDecrypt []uint, key []byte) error {
ftd := internal.UIntSlice(fieldsToDecrypt)
c, err := aes.NewCipher(key)
if err != nil {
return err
}
gcm, _ := cipher.NewGCM(c)
for _, fieldNum := range ftd {
if src, ok := pd.Fields[fieldNum]; ok {
dst, err := decryptField(src, gcm)
if err != nil {
return err
}
pd.Fields[fieldNum] = dst
}
}
ftd.Sort()
return nil
}
func (pd *protoData) Serialize() []byte {
b := bytes.NewBuffer(nil)
for _, v := range pd.Fields {
b.Write(v.Encode())
}
return b.Bytes()
}