This repository has been archived by the owner on Dec 29, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
encryption.go
255 lines (193 loc) · 5.97 KB
/
encryption.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
package gosn
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
crand "crypto/rand"
"crypto/sha256"
"crypto/sha512"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"strconv"
"strings"
"golang.org/x/crypto/pbkdf2"
)
func unPad(cipherText []byte) []byte {
c := cipherText[len(cipherText)-1]
n := int(c)
return cipherText[:len(cipherText)-n]
}
func decryptString(stringToDecrypt, encryptionKey, authKey, uuid string) (output string, err error) {
components := strings.Split(stringToDecrypt, ":")
version := components[0]
authHash := components[1]
localUUID := components[2]
IV := components[3]
cipherText := components[4]
if components[2] != uuid {
err = fmt.Errorf("aborting as uuid in string to decrypt: \"%s\" is not equal to passed uuid: \"%s\"",
localUUID, uuid)
return
}
stringToAuth := fmt.Sprintf("%s:%s:%s:%s", version, localUUID, IV, cipherText)
var deHexedAuthKey []byte
deHexedAuthKey, err = hex.DecodeString(authKey)
if err != nil {
return
}
localAuthHasher := hmac.New(sha256.New, deHexedAuthKey)
_, err = localAuthHasher.Write([]byte(stringToAuth))
if err != nil {
return
}
localAuthHash := hex.EncodeToString(localAuthHasher.Sum(nil))
if localAuthHash != authHash {
err = fmt.Errorf("auth hash does not match. possible tampering or server issue")
return
}
var deHexedEncKey []byte
deHexedEncKey, err = hex.DecodeString(encryptionKey)
if err != nil {
return
}
var aesCipher cipher.Block
aesCipher, err = aes.NewCipher(deHexedEncKey)
if err != nil {
return
}
unHexedIv, _ := hex.DecodeString(IV)
mode := cipher.NewCBCDecrypter(aesCipher, unHexedIv)
var b64DecodedCipherText []byte
b64DecodedCipherText, err = base64.StdEncoding.DecodeString(cipherText)
if err != nil {
return
}
mode.CryptBlocks(b64DecodedCipherText, b64DecodedCipherText)
b64DecodedCipherText = unPad(b64DecodedCipherText)
output = string(b64DecodedCipherText)
return output, err
}
func encryptString(stringToEncrypt, encryptionKey, authKey, uuid string, IVOverride []byte) (result string, err error) {
bytesToEncrypt := []byte(stringToEncrypt)
bytesToEncrypt = padToAESBlockSize(bytesToEncrypt)
// hex decode encryption key
var deHexedEncKey []byte
deHexedEncKey, err = hex.DecodeString(encryptionKey)
if err != nil {
return
}
var IV []byte
if IVOverride != nil {
IV = IVOverride
} else {
IV = make([]byte, 16)
_, err = crand.Read(IV)
if err != nil {
return
}
}
// create cipher block
var aesCipher cipher.Block
aesCipher, err = aes.NewCipher(deHexedEncKey)
if err != nil {
return
}
cipherText := make([]byte, len(bytesToEncrypt))
mode := cipher.NewCBCEncrypter(aesCipher, IV)
mode.CryptBlocks(cipherText, bytesToEncrypt)
b64EncodedCipher := base64.StdEncoding.EncodeToString(cipherText)
cipherText = []byte(b64EncodedCipher)
var deHexedAuthKey []byte
deHexedAuthKey, err = hex.DecodeString(authKey)
if err != nil {
return
}
IVString := hex.EncodeToString(IV)
stringToAuth := fmt.Sprintf("003:%s:%s:%s", uuid, IVString, string(cipherText))
localAuthHasher := hmac.New(sha256.New, deHexedAuthKey)
_, err = localAuthHasher.Write([]byte(stringToAuth))
if err != nil {
return
}
localAuthHash := hex.EncodeToString(localAuthHasher.Sum(nil))
result = fmt.Sprintf("003:%s:%s:%s:%s", localAuthHash, uuid, IVString, cipherText)
return result, err
}
func generateEncryptedPasswordAndKeys(input generateEncryptedPasswordInput) (pw, mk, ak string, err error) {
if input.Version == "003" && input.PasswordCost < 100000 {
err = fmt.Errorf("password cost too low")
return
}
saltSource := input.Identifier + ":" + "SF" + ":" + input.Version + ":" + strconv.Itoa(int(input.PasswordCost)) + ":" + input.PasswordNonce
h := sha256.New()
h.Write([]byte(saltSource))
preSalt := sha256.Sum256([]byte(saltSource))
salt := make([]byte, hex.EncodedLen(len(preSalt)))
hex.Encode(salt, preSalt[:])
hashedPassword := pbkdf2.Key([]byte(input.userPassword), []byte(string(salt)), int(input.PasswordCost), 96, sha512.New)
hexedHashedPassword := hex.EncodeToString(hashedPassword)
splitLength := len(hexedHashedPassword) / 3
pw = hexedHashedPassword[:splitLength]
mk = hexedHashedPassword[splitLength : splitLength*2]
ak = hexedHashedPassword[splitLength*2 : splitLength*3]
return
}
func getBodyContent(input []byte) (output syncResponse, err error) {
err = json.Unmarshal(input, &output)
if err != nil {
return
}
return
}
func padToAESBlockSize(b []byte) []byte {
n := aes.BlockSize - (len(b) % aes.BlockSize)
pb := make([]byte, len(b)+n)
copy(pb, b)
copy(pb[len(b):], bytes.Repeat([]byte{byte(n)}, n))
return pb
}
func encryptItems(decItems *Items, mk, ak string, debug bool) (encryptedItems EncryptedItems, err error) {
debugPrint(debug, fmt.Sprintf("encryptItems | encrypting %d items", len(*decItems)))
for _, decItem := range *decItems {
var e EncryptedItem
e, err = encryptItem(decItem, mk, ak)
encryptedItems = append(encryptedItems, e)
}
return
}
func encryptItem(item Item, mk, ak string) (encryptedItem EncryptedItem, err error) {
encryptedItem.UpdatedAt = item.UpdatedAt
encryptedItem.CreatedAt = item.CreatedAt
encryptedItem.Deleted = item.Deleted
// Generate Item Key
itemKeyBytes := make([]byte, 64)
_, err = crand.Read(itemKeyBytes)
if err != nil {
panic(err)
}
itemKey := hex.EncodeToString(itemKeyBytes)
// get Item Encryption Key
itemEncryptionKey := itemKey[:len(itemKey)/2]
// get Item Auth Key
itemAuthKey := itemKey[len(itemKey)/2:]
// encrypt Item Content
var encryptedContent string
mContent, _ := json.Marshal(item.Content)
encryptedContent, err = encryptString(string(mContent), itemEncryptionKey, itemAuthKey, item.UUID, nil)
if err != nil {
return
}
encryptedItem.Content = encryptedContent
var encryptedKey string
encryptedKey, err = encryptString(itemKey, mk, ak, item.UUID, nil)
if err != nil {
return
}
encryptedItem.EncItemKey = encryptedKey
encryptedItem.UUID = item.UUID
encryptedItem.ContentType = item.ContentType
return encryptedItem, err
}