-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcell.go
253 lines (221 loc) · 7.63 KB
/
cell.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
package gothemis
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/binary"
"errors"
"fmt"
"hash"
"golang.org/x/crypto/pbkdf2"
)
// min return min value from pair
func min(a, b int) int {
if a <= b {
return a
}
return b
}
// themisKDF
func themisKDF(key, label []byte, contexts [][]byte) []byte {
out := []byte{0, 0, 0, 1}
const implicitKeySize = 32
implicitKey := make([]byte, implicitKeySize)
if len(key) == 0 {
copy(implicitKey, label[:min(implicitKeySize, len(label))])
for _, context := range contexts {
if len(context) > 0 {
for j := 0; j < min(implicitKeySize, len(context)); j++ {
implicitKey[j] ^= context[j]
}
}
}
key = implicitKey
}
hmacHash := hmac.New(sha256.New, key)
hmacHash.Write(out[:4])
hmacHash.Write(label)
hmacHash.Write(out[:1])
for _, context := range contexts {
if len(context) > 0 {
hmacHash.Write(context)
}
}
return hmacHash.Sum(nil)
}
var THEMIS_SYM_KDF_KEY_LABEL = []byte("Themis secure cell message key")
const (
SOTER_SYM_256_KEY_LENGTH uint32 = 0x00000100
SOTER_SYM_AES_GCM uint32 = 0x40010000
SOTER_SYM_KDF_MASK uint32 = 0x0f000000
SOTER_SYM_NOKDF uint32 = 0x00000000
SOTER_SYM_PBKDF2 uint32 = 0x01000000
THEMIS_AUTH_SYM_KEY_LENGTH uint32 = SOTER_SYM_256_KEY_LENGTH
THEMIS_AUTH_SYM_ALG uint32 = SOTER_SYM_AES_GCM | THEMIS_AUTH_SYM_KEY_LENGTH
THEMIS_AUTH_SYM_IV_LENGTH = 12
THEMIS_AUTH_SYM_AUTH_TAG_LENGTH = 16
SOTER_SYM_MAX_KEY_LENGTH = 128
)
const authSymMessageHeaderFieldsSize = (32 / 8) * 4
const AuthSymMessageHeaderSize = authSymMessageHeaderFieldsSize + THEMIS_AUTH_SYM_IV_LENGTH + THEMIS_AUTH_SYM_AUTH_TAG_LENGTH
type AuthTagFieldLength [4]byte
type IV []byte
type AuthSymMessageHeader struct {
Alg AuthTagFieldLength
IVLength AuthTagFieldLength
AuthTagLength AuthTagFieldLength
MessageLength AuthTagFieldLength
IV IV
AuthTag AuthTag
}
type ThemisError string
func (e ThemisError) Error() string {
return string(e)
}
var errIVIncorrectLength = ThemisError("incorrect iv format")
var errIncorrectAuthTagLength = ThemisError("incorrect auth tag length")
func NewAuthSymMessageHeader(messageLength uint32, iv IV, authTag AuthTag) (*AuthSymMessageHeader, error) {
if len(iv) != THEMIS_AUTH_SYM_IV_LENGTH {
return nil, errIVIncorrectLength
}
if len(authTag) != THEMIS_AUTH_SYM_AUTH_TAG_LENGTH {
return nil, errIncorrectAuthTagLength
}
hdr := &AuthSymMessageHeader{}
binary.LittleEndian.PutUint32(hdr.IVLength[:], THEMIS_AUTH_SYM_IV_LENGTH)
binary.LittleEndian.PutUint32(hdr.AuthTagLength[:], THEMIS_AUTH_SYM_AUTH_TAG_LENGTH)
binary.LittleEndian.PutUint32(hdr.Alg[:], THEMIS_AUTH_SYM_ALG)
binary.LittleEndian.PutUint32(hdr.MessageLength[:], messageLength)
hdr.IV = iv
hdr.AuthTag = authTag
return hdr, nil
}
func (hdr *AuthSymMessageHeader) String() string {
return fmt.Sprintf("iv_length=%v, tag_length=%v, tag=%v, message_length=%v",
binary.LittleEndian.Uint32(hdr.IVLength[:]),
binary.LittleEndian.Uint32(hdr.AuthTagLength[:]), hdr.AuthTag, binary.LittleEndian.Uint32(hdr.MessageLength[:]))
}
func (hdr *AuthSymMessageHeader) Marshal() ([]byte, error) {
output := bytes.NewBuffer(make([]byte, 0, AuthSymMessageHeaderSize))
binary.Write(output, binary.LittleEndian, hdr.Alg[:])
binary.Write(output, binary.LittleEndian, hdr.IVLength[:])
binary.Write(output, binary.LittleEndian, hdr.AuthTagLength[:])
binary.Write(output, binary.LittleEndian, hdr.MessageLength[:])
binary.Write(output, binary.LittleEndian, hdr.IV[:])
binary.Write(output, binary.LittleEndian, hdr.AuthTag[:])
return output.Bytes(), nil
}
func UnmarshalAuthSymMessageHeader(data []byte) (*AuthSymMessageHeader, error) {
header := &AuthSymMessageHeader{}
reader := bytes.NewReader(data)
if err := binary.Read(reader, binary.LittleEndian, header.Alg[:]); err != nil {
return nil, err
}
if err := binary.Read(reader, binary.LittleEndian, header.IVLength[:]); err != nil {
return nil, err
}
if err := binary.Read(reader, binary.LittleEndian, header.AuthTagLength[:]); err != nil {
return nil, err
}
if err := binary.Read(reader, binary.LittleEndian, header.MessageLength[:]); err != nil {
return nil, err
}
header.IV = make([]byte, int(binary.LittleEndian.Uint32(header.IVLength[:])))
if err := binary.Read(reader, binary.LittleEndian, header.IV[:]); err != nil {
return nil, err
}
header.AuthTag = make([]byte, int(binary.LittleEndian.Uint32(header.AuthTagLength[:])))
if err := binary.Read(reader, binary.LittleEndian, header.AuthTag[:]); err != nil {
return nil, err
}
return header, nil
}
type AuthTag []byte
type Context []byte
type EncryptedData []byte
func messageToKDFContext(msg []byte) []byte {
output := make([]byte, 4)
binary.LittleEndian.PutUint32(output, uint32(len(msg)))
return output
}
var ErrInvalidKDFAlgorithm = errors.New("invalid kdf algorithm")
func soterKDF(alg uint32, key, salt []byte) ([]byte, error) {
switch alg & SOTER_SYM_KDF_MASK {
case SOTER_SYM_PBKDF2:
hmacHash := hmac.New(sha256.New, key)
return pbkdf2.Key(key, salt, 0, SOTER_SYM_MAX_KEY_LENGTH/8, func() hash.Hash { return hmacHash }), nil
case SOTER_SYM_NOKDF:
return key, nil
}
return nil, ErrInvalidKDFAlgorithm
}
func AuthenticatedSymmetricEncryptMessage(key, message []byte, context Context) (EncryptedData, *AuthSymMessageHeader, error) {
kdfKey := themisKDF(key, THEMIS_SYM_KDF_KEY_LABEL, [][]byte{messageToKDFContext(message), []byte(context)})
iv := make([]byte, THEMIS_AUTH_SYM_IV_LENGTH)
if n, err := rand.Read(iv); err != nil {
return nil, nil, err
} else if n != THEMIS_AUTH_SYM_IV_LENGTH {
return nil, nil, errors.New("can't read enough random data for IV")
}
aes, err := aes.NewCipher(kdfKey)
if err != nil {
return nil, nil, err
}
aesGCM, err := cipher.NewGCM(aes)
if err != nil {
return nil, nil, err
}
ciphertext := aesGCM.Seal(nil, iv, message, context)
encryptedData := EncryptedData(ciphertext[:len(message)])
tag := AuthTag(ciphertext[len(message):])
hdr, err := NewAuthSymMessageHeader(uint32(len(message)), IV(iv), tag)
if err != nil {
return nil, nil, err
}
return encryptedData, hdr, nil
}
func AuthenticatedSymmetricDecryptMessage(key, encryptedMessage []byte, authTag *AuthSymMessageHeader, context Context) ([]byte, error) {
kdfKey := themisKDF(key, THEMIS_SYM_KDF_KEY_LABEL, [][]byte{messageToKDFContext(encryptedMessage), []byte(context)})
aes, err := aes.NewCipher(kdfKey)
if err != nil {
return nil, err
}
aesGCM, err := cipher.NewGCM(aes)
if err != nil {
return nil, err
}
authenticatedBlock := make([]byte, 0, len(encryptedMessage)+len(authTag.AuthTag))
authenticatedBlock = append(authenticatedBlock, encryptedMessage...)
authenticatedBlock = append(authenticatedBlock, authTag.AuthTag[:]...)
decrypted, err := aesGCM.Open(nil, authTag.IV, authenticatedBlock, []byte(context))
if err != nil {
return nil, err
}
return decrypted, nil
}
type AuthenticationContext []byte
func CellSealEncrypt(key, data []byte, context Context) (EncryptedData, error) {
encryptedData, authHeader, err := AuthenticatedSymmetricEncryptMessage(key, data, context)
if err != nil {
return nil, err
}
authContext, err := authHeader.Marshal()
if err != nil {
return nil, err
}
return append(authContext, encryptedData...), nil
}
func CellSealDecrypt(key, data []byte, context Context) (EncryptedData, error) {
authHeader, err := UnmarshalAuthSymMessageHeader(data[:AuthSymMessageHeaderSize])
if err != nil {
return nil, err
}
decryptedData, err := AuthenticatedSymmetricDecryptMessage(key, data[AuthSymMessageHeaderSize:], authHeader, context)
if err != nil {
return nil, err
}
return decryptedData, nil
}