-
Notifications
You must be signed in to change notification settings - Fork 13
/
messages_encrypt.go
258 lines (217 loc) · 6.53 KB
/
messages_encrypt.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
package mixin
import (
"bytes"
"context"
"crypto/aes"
"crypto/cipher"
"crypto/ed25519"
"crypto/rand"
"encoding/base64"
"encoding/binary"
"fmt"
"strings"
"github.com/gofrs/uuid"
"golang.org/x/crypto/curve25519"
)
const (
encryptedCategoryLabel = "ENCRYPTED_"
plainCategoryLabel = "PLAIN_"
)
type MessageLocker interface {
Lock(data []byte, sessions []*Session) ([]byte, error)
Unlock(data []byte) ([]byte, error)
}
func IsEncryptedMessageCategory(category string) bool {
return strings.Contains(category, encryptedCategoryLabel)
}
func IsPlainMessageCategory(category string) bool {
return strings.Contains(category, plainCategoryLabel)
}
func EncryptMessageCategory(category string) string {
return strings.ReplaceAll(category, plainCategoryLabel, encryptedCategoryLabel)
}
func DecryptMessageCategory(category string) string {
return strings.ReplaceAll(category, encryptedCategoryLabel, plainCategoryLabel)
}
func dumpRawData(req *MessageRequest) ([]byte, error) {
if req.DataBase64 != "" {
return base64.RawURLEncoding.DecodeString(req.DataBase64)
}
return base64.StdEncoding.DecodeString(req.Data)
}
func (c *Client) EncryptMessageRequest(req *MessageRequest, sessions []*Session) error {
if plain := IsPlainMessageCategory(req.Category); !plain {
return nil
}
if ok := IsEncryptedMessageSupported(sessions); !ok {
return nil
}
data, err := dumpRawData(req)
if err != nil {
return err
}
encryptedData, err := c.Lock(data, sessions)
if err != nil {
return err
}
req.Data = ""
req.DataBase64 = base64.RawURLEncoding.EncodeToString(encryptedData)
req.Category = EncryptMessageCategory(req.Category)
req.Checksum = GenerateSessionChecksum(sessions)
for _, s := range sessions {
req.RecipientSessions = append(req.RecipientSessions, RecipientSession{
SessionID: s.SessionID,
})
}
return nil
}
const (
EncryptedMessageReceiptStateSuccess = "SUCCESS"
EncryptedMessageReceiptStateFailed = "FAILED"
)
type EncryptedMessageReceipt struct {
MessageID string `json:"message_id"`
RecipientID string `json:"recipient_id"`
State string `json:"state"`
Sessions []*Session `json:"sessions"`
}
func (c *Client) SendEncryptedMessages(ctx context.Context, messages []*MessageRequest) ([]*EncryptedMessageReceipt, error) {
var receipts []*EncryptedMessageReceipt
if err := c.Post(ctx, "/encrypted_messages", messages, &receipts); err != nil {
return nil, err
}
for _, receipt := range receipts {
for _, s := range receipt.Sessions {
s.UserID = receipt.RecipientID
}
}
return receipts, nil
}
func EncryptMessageData(data []byte, sessions []*Session, private ed25519.PrivateKey) ([]byte, error) {
key := make([]byte, 16)
if _, err := rand.Read(key); err != nil {
return nil, err
}
nonce := make([]byte, 12)
if _, err := rand.Read(nonce); err != nil {
return nil, err
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
ciphertext := aesgcm.Seal(nil, nonce, data, nil)
var sessionLen [2]byte
binary.LittleEndian.PutUint16(sessionLen[:], uint16(len(sessions)))
pub, _ := publicKeyToCurve25519(ed25519.PublicKey(private[32:]))
var sessionsBytes []byte
for _, s := range sessions {
clientPublic, err := base64.RawURLEncoding.DecodeString(s.PublicKey)
if err != nil {
return nil, err
}
var dst, priv, clientPub [32]byte
copy(clientPub[:], clientPublic[:])
privateKeyToCurve25519(&priv, private)
curve25519.ScalarMult(&dst, &priv, &clientPub)
block, err := aes.NewCipher(dst[:])
if err != nil {
return nil, err
}
padding := aes.BlockSize - len(key)%aes.BlockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
shared := make([]byte, len(key))
copy(shared[:], key[:])
shared = append(shared, padtext...)
ciphertext := make([]byte, aes.BlockSize+len(shared))
iv := ciphertext[:aes.BlockSize]
_, err = rand.Read(iv)
if err != nil {
return nil, err
}
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext[aes.BlockSize:], shared)
id, err := uuid.FromString(s.SessionID)
if err != nil {
return nil, err
}
sessionsBytes = append(sessionsBytes, id.Bytes()...)
sessionsBytes = append(sessionsBytes, ciphertext...)
}
result := []byte{1}
result = append(result, sessionLen[:]...)
result = append(result, pub[:]...)
result = append(result, sessionsBytes...)
result = append(result, nonce[:]...)
result = append(result, ciphertext...)
return result, nil
}
func DecryptMessageData(data []byte, sessionID string, private ed25519.PrivateKey) ([]byte, error) {
size := 16 + 48 // session id data + encrypted key data size
total := len(data)
if total < 1+2+32+size+12 {
return nil, fmt.Errorf("invalid data size")
}
sessionLen := int(binary.LittleEndian.Uint16(data[1:3]))
prefixSize := 35 + sessionLen*size
var key []byte
for i := 35; i < prefixSize; i += size {
if uid, _ := uuid.FromBytes(data[i : i+16]); uid.String() == sessionID {
var dst, priv, pub [32]byte
copy(pub[:], data[3:35])
privateKeyToCurve25519(&priv, private)
curve25519.ScalarMult(&dst, &priv, &pub)
block, err := aes.NewCipher(dst[:])
if err != nil {
return nil, err
}
iv := data[i+16 : i+16+aes.BlockSize]
key = data[i+16+aes.BlockSize : i+size]
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(key, key)
key = key[:16]
break
}
}
if len(key) != 16 {
return nil, fmt.Errorf("session id not found")
}
nonce := data[prefixSize : prefixSize+12]
block, err := aes.NewCipher(key)
if err != nil {
return nil, fmt.Errorf("failed to create aes cipher: %w", err)
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return nil, fmt.Errorf("failed to create aes gcm: %w", err)
}
raw, err := aesgcm.Open(nil, nonce, data[prefixSize+12:], nil)
if err != nil {
return nil, fmt.Errorf("failed to decrypt data: %w", err)
}
return raw, nil
}
type messageLockNotSupported struct{}
func (m *messageLockNotSupported) Error() string {
return "message encrypt & decrypt not supported"
}
func (m *messageLockNotSupported) Lock(data []byte, sessions []*Session) ([]byte, error) {
return nil, m
}
func (m *messageLockNotSupported) Unlock(data []byte) ([]byte, error) {
return nil, m
}
type ed25519MessageLocker struct {
sessionID string
key ed25519.PrivateKey
}
func (m *ed25519MessageLocker) Lock(data []byte, sessions []*Session) ([]byte, error) {
return EncryptMessageData(data, sessions, m.key)
}
func (m *ed25519MessageLocker) Unlock(data []byte) ([]byte, error) {
return DecryptMessageData(data, m.sessionID, m.key)
}