-
Notifications
You must be signed in to change notification settings - Fork 1
/
proj2.go
742 lines (590 loc) · 24.1 KB
/
proj2.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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
package proj2
// You MUST NOT change what you import. If you add ANY additional
// imports it will break the autograder, and we will be Very Upset.
import (
// You neet to add with
// go get github.com/cs161-staff/userlib
"github.com/cs161-staff/userlib"
// Life is much easier with json: You are
// going to want to use this so you can easily
// turn complex structures into strings etc...
"encoding/json"
// Likewise useful for debugging etc
"encoding/hex"
// UUIDs are generated right based on the crypto RNG
// so lets make life easier and use those too...
//
// You need to add with "go get github.com/google/uuid"
"github.com/google/uuid"
// Useful for debug messages, or string manipulation for datastore keys
"strings"
// Want to import errors
"errors"
// optional
_ "strconv"
// if you are looking for fmt, we don't give you fmt, but you can use userlib.DebugMsg
// see someUsefulThings() below
)
// This serves two purposes: It shows you some useful primitives and
// it suppresses warnings for items not being imported
func someUsefulThings() {
// Creates a random UUID
f := uuid.New()
userlib.DebugMsg("UUID as string:%v", f.String())
// Example of writing over a byte of f
f[0] = 10
userlib.DebugMsg("UUID as string:%v", f.String())
// takes a sequence of bytes and renders as hex
h := hex.EncodeToString([]byte("fubar"))
userlib.DebugMsg("The hex: %v", h)
// Marshals data into a JSON representation
// Will actually work with go structures as well
d, _ := json.Marshal(f)
userlib.DebugMsg("The json data: %v", string(d))
var g uuid.UUID
json.Unmarshal(d, &g)
userlib.DebugMsg("Unmashaled data %v", g.String())
// This creates an error type
userlib.DebugMsg("Creation of error %v", errors.New(strings.ToTitle("This is an error")))
// And a random RSA key. In this case, ignoring the error
// return value
var pk userlib.PKEEncKey
var sk userlib.PKEDecKey
pk, sk, _ = userlib.PKEKeyGen()
userlib.DebugMsg("Key is %v, %v", pk, sk)
}
// Helper function: Takes the first 16 bytes and
// converts it into the UUID type
func bytesToUUID(data []byte) (ret uuid.UUID) {
for x := range ret {
ret[x] = data[x]
}
return
}
// The structure definition for a user record
type User struct {
Username string
PasswordHash []byte
Salt []byte
SymmetricKey []byte
HmacKey []byte
PrivateKey userlib.PKEDecKey
SignKey userlib.DSSignKey
Uuid uuid.UUID
Files map[string]UserFile //maps filename to fsr uuid and fsrkey uuid
// You can add other fields here if you want...
// Note for JSON to marshal/unmarshal, the fields need to
// be public (start with a capital letter)
}
type UserFile struct {
FsrUuid uuid.UUID
FsrKeyUuid uuid.UUID
}
//type File struct {
// Uuid uuid.UUID
// SymmetricKey []byte
// HmacKey []byte
//}
type FileData struct {
MetaData []byte
Data []byte
}
type MetaData struct {
Shares []Share
Appends []int
}
type Share struct {
Sender string
Recipient string
FsrUuid uuid.UUID
FsrKeyUuid uuid.UUID
}
type SharingRecord struct {
HmacKey []byte //to ensure integrity
FileUuid uuid.UUID
FileSymmetricKey []byte
FileHmacKey []byte
}
// This creates a user. It will only be called once for a user
// (unless the keystore and datastore are cleared during testing purposes)
// It should store a copy of the userdata, suitably encrypted, in the
// datastore and should store the user's public key in the keystore.
// The datastore may corrupt or completely erase the stored
// information, but nobody outside should be able to get at the stored
// User data: the name used in the datastore should not be guessable
// without also knowing the password and username.
// You are not allowed to use any global storage other than the
// keystore and the datastore functions in the userlib library.
// You can assume the user has a STRONG password
func InitUser(username string, password string) (userdataptr *User, err error) {
var userdata User
userdataptr = &userdata
userdata.Files = make(map[string]UserFile)
userdata.Username = username
userdata.Salt = userlib.RandomBytes(16)
//generate 32 byte key from password
keyString := userlib.Argon2Key([]byte(password), userdata.Salt, 32)
userdata.SymmetricKey = keyString[:16]
userdata.HmacKey = keyString[16:]
//generate user's key pairs
publicKey,privateKey,_ := userlib.PKEKeyGen()
signKey, verifyKey,_ := userlib.DSKeyGen()
//write private Keys to userdata
userdata.PrivateKey = privateKey
userdata.SignKey = signKey
//store public keys to keystore
userlib.KeystoreSet(username+"pke", publicKey)
userlib.KeystoreSet(username+"ds", verifyKey)
//generate and store user uuid
uuidString := userlib.Argon2Key([]byte(username+password), []byte(""), 16)
userdata.Uuid,_ = uuid.FromBytes(uuidString)
//encrypt userdata
jsonUserdata,_ := json.Marshal(userdata)
encrypted := userlib.SymEnc(userdata.SymmetricKey, userlib.RandomBytes(16), jsonUserdata)
ciphertext := append(userdata.Salt, encrypted...)
//hmac encrypted data
hmac,_ := userlib.HMACEval(userdata.HmacKey, encrypted)
securedData := append(hmac, ciphertext...)
//store secured data to datastore
userlib.DatastoreSet(userdata.Uuid, securedData)
return userdataptr, nil
}
// This fetches the user information from the Datastore. It should
// fail with an error if the user/password is invalid, or if the user
// data was corrupted, or if the user can't be found.
func GetUser(username string, password string) (userdataptr *User, err error) {
var userdata User
userdataptr = &userdata
//retrieve secured data from datastore
uuidString := userlib.Argon2Key([]byte(username+password), []byte(""), 16)
userUuid,_ := uuid.FromBytes(uuidString)
securedData,fileExist := userlib.DatastoreGet(userUuid)
if !fileExist {
return userdataptr, errors.New("invalid username/password")
}
hmac := securedData[:64]
salt := securedData[64:80]
ciphertext := securedData[80:]
//generate 32 byte key from password
keyString := userlib.Argon2Key([]byte(password), salt, 32)
symmetricKey := keyString[:16]
hmacKey := keyString[16:]
//check if file is corrupted or tampered
receivedHmac,_ := userlib.HMACEval(hmacKey, ciphertext)
if !userlib.HMACEqual(hmac, receivedHmac) {
return nil, errors.New("userdata corrupted")
}
//decrypt encrypted user data
decrypted := userlib.SymDec(symmetricKey, ciphertext)
err = json.Unmarshal(decrypted, userdataptr)
if err != nil{
return nil, errors.New("decrypt failed")
}
return userdataptr, nil
}
// This stores a file in the datastore.
//
// The name and length of the file should NOT be revealed to the datastore!
func (userdata *User) StoreFile(filename string, data []byte) {
//create file uuid
fileUuidString := userlib.Argon2Key([]byte(userdata.Username+filename), []byte(""), 16)
fileUuid,_ := uuid.FromBytes(fileUuidString)
//create new keys to encrypt file
keyString,_ := userlib.HMACEval(userlib.RandomBytes(16), data)
symmetricKey := keyString[:16]
hmacKey := keyString[16:32]
//create file metadata
var metaData MetaData
metaData.Shares = make([]Share, 100)
//encrypt file data with symmetric key
encryptedFile := userlib.SymEnc(symmetricKey, userlib.RandomBytes(16), data)
hmacFile,_ := userlib.HMACEval(hmacKey, encryptedFile)
secured := append(hmacFile, encryptedFile...)
//update file metadata
metaData.Appends = append(metaData.Appends, len(secured))
marshalledMetaData,_ := json.Marshal(metaData)
//encrypt file metadata with symmetric key
encryptedMetaData := userlib.SymEnc(symmetricKey, userlib.RandomBytes(16), marshalledMetaData)
hmacMetaData,_ := userlib.HMACEval(hmacKey, encryptedMetaData)
securedMetaData := append(hmacMetaData, encryptedMetaData...)
//create file data
var fileData FileData
fileData.Data = secured
fileData.MetaData = securedMetaData
marshalledFileData,_ := json.Marshal(fileData)
//store file to datastore
userlib.DatastoreSet(fileUuid, marshalledFileData)
//generate uuid for sharing record
srUuidSeed := userlib.Argon2Key([]byte(userdata.Username+userdata.Username+filename),
userlib.RandomBytes(16), 32)
srUuid,_ := uuid.FromBytes(srUuidSeed[:16])
fsrKey := srUuidSeed[16:]
//create file sharing record
userdata.CreateNewFileSharingRecord(srUuid, fileUuid, symmetricKey, hmacKey,fsrKey)
//create fsrkeyrecord
encryptedFsrKeyUuid := uuid.New()
userdata.CreateFSRKeyDump(userdata.Username, fsrKey, encryptedFsrKeyUuid)
//update files in userdata
var userFile UserFile
userFile.FsrKeyUuid = encryptedFsrKeyUuid
userFile.FsrUuid = srUuid
userdata.Files[filename] = userFile
//encrypt userdata
jsonUserdata,_ := json.Marshal(userdata)
encrypted := userlib.SymEnc(userdata.SymmetricKey, userlib.RandomBytes(16), jsonUserdata)
ciphertext := append(userdata.Salt, encrypted...)
//hmac encrypted data
hmac,_ := userlib.HMACEval(userdata.HmacKey, encrypted)
securedData := append(hmac, ciphertext...)
//store secured data to datastore
userlib.DatastoreSet(userdata.Uuid, securedData)
return
}
// This adds on to an existing file.
//
// Append should be efficient, you shouldn't rewrite or reencrypt the
// existing file, but only whatever additional information and
// metadata you need.
func (userdata *User) AppendFile(filename string, data []byte) (err error) {
//retrieve file information from filename
userFile := userdata.Files[filename]
fsrKeyUuid := userFile.FsrKeyUuid
fsrUuid := userFile.FsrUuid
//retrieve encrypted fsr key
encryptedFsrKey,_ := userlib.DatastoreGet(fsrKeyUuid)
//decrypt encrypted fsr key
fsrKey,_ := userlib.PKEDec(userdata.PrivateKey, encryptedFsrKey)
//retrieve secured fsr
securedFsr,_ := userlib.DatastoreGet(fsrUuid)
var sharingRecord SharingRecord
decryptedSR := userlib.SymDec(fsrKey, securedFsr[64:])
json.Unmarshal(decryptedSR, &sharingRecord)
//check sr hmac
receivedHmac,_ := userlib.HMACEval(sharingRecord.HmacKey, securedFsr[64:])
if !userlib.HMACEqual(securedFsr[:64], receivedHmac){
return errors.New("hmac not equal")
}
//retrieve filedata from datastore
marshalledFileData,_ := userlib.DatastoreGet(sharingRecord.FileUuid)
var fileData FileData
json.Unmarshal(marshalledFileData, &fileData)
encryptedMetaData := fileData.MetaData[64:]
encryptedMetaDataHmac := fileData.MetaData[:64]
//check if metadata is corrupted
receivedMetaDataHmac,_ := userlib.HMACEval(sharingRecord.FileHmacKey, encryptedMetaData)
if !userlib.HMACEqual(encryptedMetaDataHmac, receivedMetaDataHmac) {
return errors.New("file metadata corrupted")
}
//decrypt encrypted metadata
marshalledMetaData := userlib.SymDec(sharingRecord.FileSymmetricKey, encryptedMetaData)
var metaData MetaData
json.Unmarshal(marshalledMetaData, &metaData)
//encrypt newly appended data
appendedEncData := userlib.SymEnc(sharingRecord.FileSymmetricKey, userlib.RandomBytes(16), data)
appendedHmac,_ := userlib.HMACEval(sharingRecord.FileHmacKey, appendedEncData)
appendedSecureData := append(appendedHmac, appendedEncData...)
fileData.Data = append(fileData.Data, appendedSecureData...)
metaData.Appends = append(metaData.Appends, len(appendedSecureData))
//encrypt file metadata with symmetric key
updatedMarshalledMetaData,_ := json.Marshal(metaData)
updatedEncMetaData := userlib.SymEnc(sharingRecord.FileSymmetricKey, userlib.RandomBytes(16), updatedMarshalledMetaData)
updatedHmacMetaData,_ := userlib.HMACEval(sharingRecord.FileHmacKey, updatedEncMetaData)
securedMetaData := append(updatedHmacMetaData, updatedEncMetaData...)
//update file data
fileData.MetaData = securedMetaData
updatedMarshalledFileData,_ := json.Marshal(fileData)
//store file to datastore
userlib.DatastoreSet(sharingRecord.FileUuid, updatedMarshalledFileData)
return
}
// This loads a file from the Datastore.
//
// It should give an error if the file is corrupted in any way.
func (userdata *User) LoadFile(filename string) (data []byte, err error) {
//retrieve file information from filename
userFile := userdata.Files[filename]
fsrKeyUuid := userFile.FsrKeyUuid
fsrUuid := userFile.FsrUuid
//retrieve encrypted fsr key
encryptedFsrKey,_ := userlib.DatastoreGet(fsrKeyUuid)
//decrypt encrypted fsr key
fsrKey,_ := userlib.PKEDec(userdata.PrivateKey, encryptedFsrKey)
//retrieve secured fsr
securedFsr,_ := userlib.DatastoreGet(fsrUuid)
var sharingRecord SharingRecord
decryptedSR := userlib.SymDec(fsrKey, securedFsr[64:])
json.Unmarshal(decryptedSR, &sharingRecord)
//check sr hmac
receivedHmac,_ := userlib.HMACEval(sharingRecord.HmacKey, securedFsr[64:])
if !userlib.HMACEqual(securedFsr[:64], receivedHmac){
return nil, errors.New("hmac not equal")
}
//retrieve filedata from datastore
marshalledFileData,_ := userlib.DatastoreGet(sharingRecord.FileUuid)
var fileData FileData
json.Unmarshal(marshalledFileData, &fileData)
encryptedData := fileData.Data
encryptedMetaData := fileData.MetaData[64:]
encryptedMetaDataHmac := fileData.MetaData[:64]
//check if metadata is corrupted
receivedMetaDataHmac,_ := userlib.HMACEval(sharingRecord.FileHmacKey, encryptedMetaData)
if !userlib.HMACEqual(encryptedMetaDataHmac, receivedMetaDataHmac) {
return nil, errors.New("file metadata corrupted")
}
//decrypt encrypted metadata
marshalledMetaData := userlib.SymDec(sharingRecord.FileSymmetricKey, encryptedMetaData)
var metaData MetaData
json.Unmarshal(marshalledMetaData, &metaData)
var count = 0
var decryptedData []byte
for i := 0; i < len(metaData.Appends); i++ {
encryptedPortion := encryptedData[count:count+metaData.Appends[i]]
//check if encrypted portion is corrupted
encryptedPortionHmac := encryptedPortion[:64]
receivedPortionHmac,_ := userlib.HMACEval(sharingRecord.FileHmacKey, encryptedPortion[64:])
if !userlib.HMACEqual(encryptedPortionHmac, receivedPortionHmac) {
return nil, errors.New("file metadata corrupted")
}
//decrypt encrypted portion
decryptedPortion := userlib.SymDec(sharingRecord.FileSymmetricKey, encryptedPortion[64:])
decryptedData = append(decryptedData, decryptedPortion...)
count += metaData.Appends[i]
}
data = decryptedData
return data, nil
}
// This creates a sharing record, which is a key pointing to something
// in the datastore to share with the recipient.
// This enables the recipient to access the encrypted file as well
// for reading/appending.
// Note that neither the recipient NOR the datastore should gain any
// information about what the sender calls the file. Only the
// recipient can access the sharing record, and only the recipient
// should be able to know the sender.
func (userdata *User) ShareFile(filename string, recipient string) (
magic_string string, err error) {
//retrieve file information from filename
userFile := userdata.Files[filename]
fsrKeyUuid := userFile.FsrKeyUuid
fsrUuid := userFile.FsrUuid
//retrieve encrypted fsr key
encryptedFsrKey,_ := userlib.DatastoreGet(fsrKeyUuid)
//decrypt encrypted fsr key
fsrKey,_ := userlib.PKEDec(userdata.PrivateKey, encryptedFsrKey)
//retrieve secured fsr
securedFsr,_ := userlib.DatastoreGet(fsrUuid)
var sharingRecord SharingRecord
decryptedSR := userlib.SymDec(fsrKey, securedFsr[64:])
json.Unmarshal(decryptedSR, &sharingRecord)
//check sr hmac
receivedHmac,_ := userlib.HMACEval(sharingRecord.HmacKey, securedFsr[64:])
if !userlib.HMACEqual(securedFsr[:64], receivedHmac){
return "", errors.New("hmac not equal")
}
//retrieve filedata from datastore
marshalledFileData,_ := userlib.DatastoreGet(sharingRecord.FileUuid)
var fileData FileData
json.Unmarshal(marshalledFileData, &fileData)
encryptedMetaData := fileData.MetaData[64:]
encryptedMetaDataHmac := fileData.MetaData[:64]
//check if metadata is corrupted
receivedMetaDataHmac,_ := userlib.HMACEval(sharingRecord.FileHmacKey, encryptedMetaData)
if !userlib.HMACEqual(encryptedMetaDataHmac, receivedMetaDataHmac) {
return "", errors.New("file metadata corrupted")
}
//decrypt encrypted metadata
marshalledMetaData := userlib.SymDec(sharingRecord.FileSymmetricKey, encryptedMetaData)
var metaData MetaData
json.Unmarshal(marshalledMetaData, &metaData)
//generate uuid for sharing record
srUuidSeed := userlib.Argon2Key([]byte(userdata.Username+recipient+filename),
userlib.RandomBytes(16), 32)
srUuid,_ := uuid.FromBytes(srUuidSeed[:16])
newFsrKey := srUuidSeed[16:]
//create new filesharing record
userdata.CreateNewFileSharingRecord(srUuid, sharingRecord.FileUuid, sharingRecord.FileSymmetricKey,
sharingRecord.FileHmacKey, newFsrKey)
//encrypt fsr key and store to datastore
encryptedFsrKeyUuid := uuid.New()
userdata.CreateFSRKeyDump(recipient, newFsrKey, encryptedFsrKeyUuid)
//update shares in file information
var share Share
share.Recipient = recipient
share.Sender = userdata.Username
share.FsrKeyUuid = encryptedFsrKeyUuid
share.FsrUuid = srUuid
metaData.Shares = append(metaData.Shares, share)
updatedMarshalledMetaData,_ := json.Marshal(metaData)
//encrypt and secure metadata
updatedEncryptedMetaData := userlib.SymEnc(sharingRecord.FileSymmetricKey, userlib.RandomBytes(16), updatedMarshalledMetaData)
updatedHmacMetaData,_ := userlib.HMACEval(sharingRecord.FileHmacKey, updatedEncryptedMetaData)
updatedSecuredMetaData := append(updatedHmacMetaData, updatedEncryptedMetaData...)
fileData.MetaData = updatedSecuredMetaData
// store updated file
updatedMarshalledFileData,_ := json.Marshal(fileData)
//store file to datastore
userlib.DatastoreSet(sharingRecord.FileUuid, updatedMarshalledFileData)
//generate magic string (sr uiid) and sign with ds
encryptedFsrKeyUuidByte,_ := encryptedFsrKeyUuid.MarshalBinary()
srUuidByte,_ := srUuid.MarshalBinary()
combined := append(encryptedFsrKeyUuidByte, srUuidByte...)
srDigSig,_ := userlib.DSSign(userdata.SignKey, combined)
magicByte := append(srDigSig, combined...)
return hex.EncodeToString(magicByte), nil
}
func (userdata *User) CreateNewFileSharingRecord(srUuid uuid.UUID, fileUuid uuid.UUID,
fileSymKey []byte, fileHmacKey []byte, fsrKey []byte) {
//create a sharing record
var sharingRecord SharingRecord
sharingRecord.HmacKey = userlib.RandomBytes(16)
sharingRecord.FileUuid = fileUuid
sharingRecord.FileSymmetricKey = fileSymKey
sharingRecord.FileHmacKey = fileHmacKey
//encrypt sharing record with fsr key
srJson,_ := json.Marshal(sharingRecord)
encryptedFSR := userlib.SymEnc(fsrKey, userlib.RandomBytes(16), srJson)
//add mac to encrypted sharing record
srHmac,_ := userlib.HMACEval(sharingRecord.HmacKey, encryptedFSR)
securedSr := append(srHmac, encryptedFSR...)
//store sharing record to data store
userlib.DatastoreSet(srUuid, securedSr)
}
//encrypts fsr key with recipient's public key and stores to specified location in datastore
func (userdata *User) CreateFSRKeyDump(recipient string, fsrKey []byte, targetUuid uuid.UUID) (err error){
recipientPubKey,_ := userlib.KeystoreGet(recipient+"pke")
encryptedFsrKey,err1 := userlib.PKEEnc(recipientPubKey, fsrKey)
if err1 != nil {
return err1
}
userlib.DatastoreSet(targetUuid, encryptedFsrKey)
return nil
}
// Note recipient's filename can be different from the sender's filename.
// The recipient should not be able to discover the sender's view on
// what the filename even is! However, the recipient must ensure that
// it is authentically from the sender.
func (userdata *User) ReceiveFile(filename string, sender string,
magic_string string) error {
// verify digital signature
senderVerify,_ := userlib.KeystoreGet(sender+"ds")
magicByte,_ := hex.DecodeString(magic_string)
srDigSig := magicByte[:256]
combined := magicByte[256:]
signatureError := userlib.DSVerify(senderVerify, combined, srDigSig)
if signatureError != nil{
return signatureError
}
//extract information from combined
encryptedFsrKeyUuidByte := combined[:16]
encryptedFsrKeyUuid := bytesToUUID(encryptedFsrKeyUuidByte)
srUuidByte := combined[16:]
srUuid := bytesToUUID(srUuidByte)
//write file to userdata
var userFile UserFile
userFile.FsrUuid = srUuid
userFile.FsrKeyUuid = encryptedFsrKeyUuid
userdata.Files[filename] = userFile
//encrypt userdata
jsonUserdata,_ := json.Marshal(userdata)
encrypted := userlib.SymEnc(userdata.SymmetricKey, userlib.RandomBytes(16), jsonUserdata)
ciphertext := append(userdata.Salt, encrypted...)
//hmac encrypted data
hmac,_ := userlib.HMACEval(userdata.HmacKey, encrypted)
securedData := append(hmac, ciphertext...)
//store secured data to datastore
userlib.DatastoreSet(userdata.Uuid, securedData)
return nil
}
// Removes target user's access.
func (userdata *User) RevokeFile(filename string, target_username string) (err error) {
//retrieve file information from filename
userFile := userdata.Files[filename]
fsrKeyUuid := userFile.FsrKeyUuid
fsrUuid := userFile.FsrUuid
//retrieve encrypted fsr key
encryptedFsrKey,_ := userlib.DatastoreGet(fsrKeyUuid)
//decrypt encrypted fsr key
fsrKey,_ := userlib.PKEDec(userdata.PrivateKey, encryptedFsrKey)
//retrieve secured fsr
securedFsr,_ := userlib.DatastoreGet(fsrUuid)
var sharingRecord SharingRecord
decryptedSR := userlib.SymDec(fsrKey, securedFsr[64:])
json.Unmarshal(decryptedSR, &sharingRecord)
//check sr hmac
receivedHmac,_ := userlib.HMACEval(sharingRecord.HmacKey, securedFsr[64:])
if !userlib.HMACEqual(securedFsr[:64], receivedHmac){
return errors.New("hmac not equal")
}
//retrieve filedata from datastore
marshalledFileData,_ := userlib.DatastoreGet(sharingRecord.FileUuid)
var fileData FileData
json.Unmarshal(marshalledFileData, &fileData)
encryptedMetaData := fileData.MetaData[64:]
encryptedMetaDataHmac := fileData.MetaData[:64]
//check if metadata is corrupted
receivedMetaDataHmac,_ := userlib.HMACEval(sharingRecord.FileHmacKey, encryptedMetaData)
if !userlib.HMACEqual(encryptedMetaDataHmac, receivedMetaDataHmac) {
return errors.New("file metadata corrupted")
}
//decrypt encrypted metadata
marshalledMetaData := userlib.SymDec(sharingRecord.FileSymmetricKey, encryptedMetaData)
var metaData MetaData
json.Unmarshal(marshalledMetaData, &metaData)
//decrypt filedata for re encryption
var count = 0
var decryptedData []byte
encryptedData := fileData.Data
for i := 0; i < len(metaData.Appends); i++ {
encryptedPortion := encryptedData[count:count+metaData.Appends[i]]
//check if encrypted portion is corrupted
encryptedPortionHmac := encryptedPortion[:64]
receivedPortionHmac,_ := userlib.HMACEval(sharingRecord.FileHmacKey, encryptedPortion[64:])
if !userlib.HMACEqual(encryptedPortionHmac, receivedPortionHmac) {
return errors.New("file data corrupted")
}
//decrypt encrypted portion
decryptedPortion := userlib.SymDec(sharingRecord.FileSymmetricKey, encryptedPortion[64:])
decryptedData = append(decryptedData, decryptedPortion...)
count += metaData.Appends[i]
}
//create new keys to encrypt file
keyString,_ := userlib.HMACEval(userlib.RandomBytes(16), sharingRecord.FileSymmetricKey)
newSymmetricKey := keyString[:16]
newHmacKey := keyString[16:32]
//encrypt file data again
newEncryptedData := userlib.SymEnc(newSymmetricKey, userlib.RandomBytes(16), decryptedData)
newHmacData,_ := userlib.HMACEval(newHmacKey, newEncryptedData)
newSecuredData := append(newHmacData, newEncryptedData...)
fileData.Data = newSecuredData
//update shares in file information
var shares []Share
for i := 0; i < len(metaData.Shares); i++ {
if metaData.Shares[i].Sender != target_username && metaData.Shares[i].Recipient != target_username {
shares = append(shares, metaData.Shares[i])
}
}
metaData.Shares = shares
var newAppends []int
newAppends = append(newAppends, len(newSecuredData))
metaData.Appends = newAppends
//encrypt and secure metadata
updatedMarshalledMetaData,_ := json.Marshal(metaData)
updatedEncryptedMetaData := userlib.SymEnc(newSymmetricKey, userlib.RandomBytes(16), updatedMarshalledMetaData)
updatedHmacMetaData,_ := userlib.HMACEval(newHmacKey, updatedEncryptedMetaData)
updatedSecuredMetaData := append(updatedHmacMetaData, updatedEncryptedMetaData...)
fileData.MetaData = updatedSecuredMetaData
// store updated file
updatedMarshalledFileData,_ := json.Marshal(fileData)
//store file to datastore
userlib.DatastoreSet(sharingRecord.FileUuid, updatedMarshalledFileData)
//update relevant fsrs
for i := 0; i < len(shares); i++ {
share := shares[i]
//generate uuid for sharing record
srUuidSeed,_ := userlib.HMACEval(userlib.RandomBytes(16), fsrKey)
newFsrKey := srUuidSeed[:16]
userdata.CreateNewFileSharingRecord(share.FsrUuid, sharingRecord.FileUuid, newSymmetricKey, newHmacKey, newFsrKey)
userdata.CreateFSRKeyDump(share.Recipient, newFsrKey, share.FsrKeyUuid)
}
return
}