-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjmessage_client_unfinished (6).go
1465 lines (1227 loc) · 41.2 KB
/
jmessage_client_unfinished (6).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
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bufio"
"bytes"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/base64"
b64 "encoding/base64"
"encoding/binary"
"encoding/hex"
"encoding/json"
"errors"
"flag"
"fmt"
"hash/crc32"
"io"
"io/ioutil"
"log"
"math/big"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
//"io/ioutil"
//"log"
"gitlab.com/yawning/chacha20.git"
)
// Globals
var (
serverPort int
serverDomain string
serverDomainAndPort string
serverProtocol string
noTLS bool
strictTLS bool
username string
password string
apiKey string
doUserRegister bool
headlessMode bool
messageIDCounter int
attachmentsDir string
globalPubKey PubKeyStruct
globalPrivKey PrivKeyStruct
attack string
victim string
)
type PubKeyStruct struct {
EncPK string `json:"encPK"`
SigPK string `json:"sigPK"`
}
type PrivKeyStruct struct {
EncSK string `json:"encSK"`
SigSK string `json:"sigSK"`
}
type FilePathStruct struct {
Path string `json:"path"`
}
type APIKeyStruct struct {
APIkey string `json:"APIkey"`
}
type MessageStruct struct {
From string `json:"from"`
To string `json:"to"`
Id int `json:"id"`
ReceiptID int `json:"receiptID"`
Payload string `json:"payload"`
decrypted string
url string
localPath string
}
type UserStruct struct {
Username string `json:"username"`
CreationTime int `json:"creationTime"`
CheckedTime int `json:"lastCheckedTime"`
}
type CiphertextStruct struct {
C1 string `json:"C1"`
C2 string `json:"C2"`
Sig string `json:"Sig"`
}
// PrettyPrint to print struct in a readable way
func PrettyPrint(i interface{}) string {
s, _ := json.MarshalIndent(i, "", "\t")
return string(s)
}
// Do a POST request and return the result
func doPostRequest(postURL string, postContents []byte) (int, []byte, error) {
// Initialize a client
client := &http.Client{}
req, err := http.NewRequest("POST", postURL, bytes.NewBuffer(postContents))
if err != nil {
return 0, nil, err
}
// Set up some fake headers
req.Header = http.Header{
"Content-Type": {"application/json"},
"User-Agent": {"Mozilla/5.0 (Macintosh"},
}
// Make the POST request
resp, err := client.Do(req)
if err != nil {
return 0, nil, err
}
// Extract the body contents
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
return resp.StatusCode, body, nil
}
// Do a GET request and return the result
func doGetRequest(getURL string) (int, []byte, error) {
// Initialize a client
client := &http.Client{}
req, err := http.NewRequest("GET", getURL, nil)
if err != nil {
return 0, nil, err
}
// Set up some fake headers
req.Header = http.Header{
"Content-Type": {"application/json"},
"User-Agent": {"Mozilla/5.0 (Macintosh"},
}
// Make the GET request
resp, err := client.Do(req)
if err != nil {
fmt.Println(err)
return 0, nil, err
}
// Extract the body contents
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
return resp.StatusCode, body, nil
}
// Upload a file to the server
func uploadFileToServer(filename string) (string, error) {
file, err := os.Open(filename)
if err != nil {
return "", err
}
defer file.Close()
posturl := serverProtocol + "://" + serverDomainAndPort + "/uploadFile/" +
username + "/" + apiKey
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, _ := writer.CreateFormFile("filefield", filename)
io.Copy(part, file)
writer.Close()
r, _ := http.NewRequest("POST", posturl, body)
r.Header.Set("Content-Type", writer.FormDataContentType())
client := &http.Client{}
resp, err := client.Do(r)
defer resp.Body.Close()
// Read the response body
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
// Handle error
fmt.Println("Error while reading the response bytes:", err)
return "", err
}
// Unmarshal the JSON into a map or a struct
var resultStruct FilePathStruct
err = json.Unmarshal(respBody, &resultStruct)
if err != nil {
// Handle error
fmt.Println("Error while parsing JSON:", err)
return "", err
}
// Construct a URL
fileURL := serverProtocol + "://" + serverDomainAndPort + "/downloadFile" +
resultStruct.Path
return fileURL, nil
}
// Download a file from the server and return its local path
func downloadFileFromServer(geturl string, localPath string) error {
// Get the file data
resp, err := http.Get(geturl)
if err != nil {
return err
}
defer resp.Body.Close()
// no errors; return
if resp.StatusCode != 200 {
return errors.New("Bad result code")
}
// Create the file
out, err := os.Create(localPath)
if err != nil {
return err
}
defer out.Close()
// Write the body to file
_, err = io.Copy(out, resp.Body)
return err
}
// Log in to server
func serverLogin(username string, password string) (string, error) {
geturl := serverProtocol + "://" + serverDomainAndPort + "/login/" +
username + "/" + password
code, body, err := doGetRequest(geturl)
if err != nil {
return "", err
}
if code != 200 {
return "", errors.New("Bad result code")
}
// Parse JSON into an APIKey struct
var result APIKeyStruct
if err := json.Unmarshal(body, &result); err != nil { // Parse []byte to go struct pointer
fmt.Println("Can not unmarshal JSON")
}
return result.APIkey, nil
}
// Log in to server
func getPublicKeyFromServer(forUser string) (*PubKeyStruct, error) {
geturl := serverProtocol + "://" + serverDomainAndPort + "/lookupKey/" + forUser
code, body, err := doGetRequest(geturl)
if err != nil {
return nil, err
}
if code != 200 {
return nil, errors.New("Bad result code")
}
// Parse JSON into an PubKeyStruct
var result PubKeyStruct
if err := json.Unmarshal(body, &result); err != nil { // Parse []byte to go struct pointer
fmt.Println("Can not unmarshal JSON")
}
return &result, nil
}
// Register username with the server
func registerUserWithServer(username string, password string) error {
geturl := serverProtocol + "://" + serverDomainAndPort + "/registerUser/" +
username + "/" + password
code, _, err := doGetRequest(geturl)
if err != nil {
return err
}
if code != 200 {
return errors.New("Bad result code")
}
return nil
}
// Get messages from the server
func getMessagesFromServer(globalPriv1 PrivKeyStruct) ([]MessageStruct, error) {
geturl := serverProtocol + "://" + serverDomainAndPort + "/getMessages/" +
username + "/" + apiKey
// Make the request to the server
code, body, err := doGetRequest(geturl)
if err != nil {
return nil, err
}
if code != 200 {
return nil, errors.New("Bad result code")
}
// Parse JSON into an array of MessageStructs
var result []MessageStruct
if err := json.Unmarshal(body, &result); err != nil { // Parse []byte to go struct pointer
fmt.Println("Can not unmarshal JSON")
}
// TODO: Implement decryption
decryptMessages(result, globalPriv1)
return result, nil
}
func getMessagesFromServer1(globalPriv1 PrivKeyStruct, username string) ([]MessageStruct, error) {
geturl := serverProtocol + "://" + serverDomainAndPort + "/getMessages/" +
username + "/" + apiKey
// Make the request to the server
code, body, err := doGetRequest(geturl)
if err != nil {
return nil, err
}
if code != 200 {
return nil, errors.New("Bad result code")
}
// Parse JSON into an array of MessageStructs
var result []MessageStruct
if err := json.Unmarshal(body, &result); err != nil { // Parse []byte to go struct pointer
fmt.Println("Can not unmarshal JSON")
}
// TODO: Implement decryption
decryptMessages(result, globalPriv1)
return result, nil
}
// Get messages from the server
func getUserListFromServer() ([]UserStruct, error) {
geturl := serverProtocol + "://" + serverDomainAndPort + "/listUsers"
// Make the request to the server
code, body, err := doGetRequest(geturl)
if err != nil {
return nil, err
}
if code != 200 {
return nil, errors.New("Bad result code")
}
// Parse JSON into an array of MessageStructs
var result []UserStruct
if err := json.Unmarshal(body, &result); err != nil { // Parse []byte to go struct pointer
fmt.Println("Can not unmarshal JSON")
}
// Sort the user list by timestamp
sort.Slice(result, func(i, j int) bool {
return result[i].CheckedTime > result[j].CheckedTime
})
return result, nil
}
// Post a message to the server
func sendMessageToServer(sender string, recipient string, message []byte, readReceiptID int) error {
posturl := serverProtocol + "://" + serverDomainAndPort + "/sendMessage/" +
username + "/" + apiKey
// Format the message as a JSON object and increment the message ID counter
messageIDCounter++
msg := MessageStruct{sender, recipient, messageIDCounter, readReceiptID, b64.StdEncoding.EncodeToString(message), "", "", ""}
body, err := json.Marshal(msg)
if err != nil {
return err
}
// Post it to the server
code, _, err := doPostRequest(posturl, body)
if err != nil {
return err
}
if code != 200 {
return errors.New("Bad result code")
}
return nil
}
// Post a message to the server copied!
func sendMessageToServer1(sender string, recipient string, message []byte, readReceiptID int) error {
posturl := serverProtocol + "://" + serverDomainAndPort + "/sendMessage/" +
sender + "/" + apiKey
// Format the message as a JSON object and increment the message ID counter
messageIDCounter++
msg := MessageStruct{sender, recipient, messageIDCounter, readReceiptID, b64.StdEncoding.EncodeToString(message), "", "", ""}
body, err := json.Marshal(msg)
if err != nil {
return err
}
// Post it to the server
code, _, err := doPostRequest(posturl, body)
if err != nil {
return err
}
if code != 200 {
return errors.New("Bad result code")
}
return nil
}
// Read in a message from the command line and then send it to the serve
func doReadAndSendMessage(recipient string, messageBody string, globalPriv1 PrivKeyStruct) error {
keepReading := true
reader := bufio.NewReader(os.Stdin)
// First, obtain the recipient's public key
pubkey, err := getPublicKeyFromServer(recipient)
if err != nil {
fmt.Printf("Could not obtain public key for user %s.\n", recipient)
return err
}
// If there is no message given, we read one in from the user
if messageBody == "" {
// Next, read in a multi-line message, ending when we get an empty line (\n)
fmt.Println("Enter message contents below. Finish the message with a period.")
for keepReading == true {
input, err := reader.ReadString('\n')
if err != nil {
fmt.Println("An error occured while reading input. Please try again", err)
}
if strings.TrimSpace(input) == "." {
keepReading = false
} else {
messageBody = messageBody + input
}
}
}
// Now encrypt the message
encryptedMessage := encryptMessage([]byte(messageBody), username, pubkey, globalPriv1)
// Check if the "cipher.txt" file exists and delete it
if _, err := os.Stat("cipher.txt"); err == nil {
err := os.Remove("cipher.txt")
if err != nil {
fmt.Println("Error deleting existing file:", err)
return err
}
}
// Save the ciphertext to a file named "cipher.txt"
file, err := os.Create("cipher.txt")
if err != nil {
fmt.Println("Error creating file:", err)
return err
}
defer file.Close()
_, err = file.WriteString(string(encryptedMessage))
if err != nil {
fmt.Println("Error writing to file:", err)
}
return sendMessageToServer(username, recipient, []byte(encryptedMessage), 0)
}
// Request a key from the server
func getKeyFromServer(user_key string) {
geturl := serverProtocol + "://" + serverDomain + ":" + strconv.Itoa(serverPort) + "/lookupKey?" + user_key
fmt.Println(geturl)
}
func FixCRC(c2Ciphertext []byte, XoringB []byte) []byte {
modifiedCiphertext := make([]byte, len(c2Ciphertext))
copy(modifiedCiphertext, c2Ciphertext)
//XOR modifiedCiphertext except the last 4 bytes with XOringB
// XOR modifiedCiphertext except the last 4 bytes with XoringB
for i := 0; i < len(modifiedCiphertext)-4; i++ {
modifiedCiphertext[i] ^= XoringB[i]
}
// Calculate the CRC32 checksum of the original plaintext CRC(A)
crc32Original := binary.BigEndian.Uint32(c2Ciphertext[len(c2Ciphertext)-4:])
// Calculate the CRC32 checksum of the modifiemodifiedc2d ciphertext CRC(B)
crc32Modified := crc32.ChecksumIEEE(XoringB)
// CRC(0) checksum
hex := make([]byte, len(c2Ciphertext)-4)
for i := range hex {
hex[i] = 0x00
}
checksum_zero := crc32.ChecksumIEEE(hex)
// XOR the original CRC32 checksum with the modified CRC32 checksum CRC(0) XOR CRC(A) COR CRC(B)
crc32New := crc32Original ^ crc32Modified ^ checksum_zero
// Update the last 4 bytes of the modified ciphertext with the new CRC32 checksum
binary.BigEndian.PutUint32(modifiedCiphertext[len(modifiedCiphertext)-4:], crc32New)
return modifiedCiphertext
}
func performAttack(ciphertext CiphertextStruct, victimUsername string, username string, privKey PrivKeyStruct) string {
//Victim2
SenderUsername := "charlie"
// Decode the C2 component from base64
c2Bytes, err := base64.StdEncoding.DecodeString(ciphertext.C2)
if err != nil {
fmt.Printf("Failed to decode C2: %v\n", err)
return ""
}
ciphertextLength := len(c2Bytes)
// Create a slice to store the decrypted plaintext
plaintext := make([]byte, ciphertextLength-4-len(SenderUsername)-1)
//Xoring B and initiate to 0
XoringB := make([]byte, ciphertextLength-4)
for i := range XoringB {
XoringB[i] = 0x00
}
// maSenderUsernameke delimiter to a
XoringB[len(SenderUsername)] = 0x5B
//Index to bruteforce
// Bruteforce the current character by XORing with 2^7 bits
modifiedCiphertext := make([]byte, ciphertextLength)
for i := 0; i < len(plaintext); i++ {
fmt.Println("Attacking ciphertext......")
forceI := len(SenderUsername) + 1 + i
for j := 0; j < 128; j++ {
fmt.Print(".")
copy(modifiedCiphertext, c2Bytes)
XoringB[forceI] = byte(j)
//Fixcrc
modifiedCiphertext = FixCRC(modifiedCiphertext, XoringB)
// Encode the modified ciphertext back to base64
modifiedC2 := base64.StdEncoding.EncodeToString(modifiedCiphertext)
// Create a new replay with the modified C2
replay := ciphertext
replay.C2 = modifiedC2
// Sign the modified ciphertext using Mallory's private key
replay.Sig = signMessage(replay, privKey)
// Send the modified ciphertext to Alice
jsonMessage, err := json.Marshal(replay)
if err != nil {
fmt.Printf("Failed to marshal modified ciphertext: %v\n", err)
continue
}
err = sendMessageToServer1(username, victimUsername, jsonMessage, 0)
if err != nil {
fmt.Printf("Failed to send message to Alice: %v, sending message to this username %s \n", err, username)
continue
}
// Wait for a short duration (e.g., 100ms) to allow Alice to process the message
time.Sleep(300 * time.Millisecond)
// Check if a read receipt was received from Alice
messageList, err := getMessagesFromServer1(privKey, username)
if err != nil {
fmt.Printf("Failed to retrieve messages: %v\n", err)
continue
}
readReceiptReceived := false
for _, message := range messageList {
if message.ReceiptID != 0 && message.From == victimUsername {
readReceiptReceived = true
fmt.Println("Got a Read Reciept for this j value", j)
break
}
}
if readReceiptReceived {
// The current character decrypted to 0x3A (':')
plaintext[i] = byte(j) ^ 0x3A
fmt.Println("Found PLaintext: ", string(plaintext[i]))
XoringB[forceI] = plaintext[i] ^ 0x61
break
}
}
// Increasing the size of the username by an additional character
username = username + "a"
fmt.Println("New username", username)
apiKey := ""
privKey, apiKey = Reregister(username)
_ = apiKey
}
return string(plaintext)
}
// Upload a new public key to the server
func registerPublicKeyWithServer(username string, pubKeyEncoded PubKeyStruct) error {
posturl := serverProtocol + "://" + serverDomainAndPort + "/uploadKey/" +
username + "/" + apiKey
body, err := json.Marshal(pubKeyEncoded)
if err != nil {
return err
}
// Post it to the server
code, _, err := doPostRequest(posturl, body)
if err != nil {
return err
}
if code != 200 {
return errors.New("Bad result code")
}
return nil
}
//******************************
// Cryptography functions
//******************************
// Encrypts a file on disk into a new ciphertext file on disk, returns the HEX encoded key
// and file hash, or an error.
func encryptAttachment(plaintextFilePath string) (string, string, error) {
// Read the plaintext file contents
plaintextData, err := ioutil.ReadFile(plaintextFilePath)
if err != nil {
return "", "", err
}
// Generate a random 256-bit ChaCha20 key
key := make([]byte, 32)
_, err = rand.Read(key)
if err != nil {
return "", "", err
}
// Create a new ChaCha20 cipher with the key and zero nonce
var nonce [chacha20.NonceSize]byte
cipher, err := chacha20.New(key, nonce[:])
if err != nil {
return "", "", err
}
// Encrypt the file contents
encryptedData := make([]byte, len(plaintextData))
cipher.XORKeyStream(encryptedData, plaintextData)
// Calculate the SHA256 hash of the encrypted file
hash := sha256.Sum256(encryptedData)
hashStr := hex.EncodeToString(hash[:])
// Encode the key as base64
keyStr := base64.StdEncoding.EncodeToString(key)
// Create a new file with the ".enc" extension to store the encrypted data
encryptedFilePath := plaintextFilePath + ".enc"
err = ioutil.WriteFile(encryptedFilePath, encryptedData, 0644)
if err != nil {
return "", "", err
}
return keyStr, hashStr, nil
}
func decodePrivateSigningKey(privKey PrivKeyStruct) (*ecdsa.PrivateKey, error) {
sigSKBytes, err := base64.StdEncoding.DecodeString(privKey.SigSK)
if err != nil {
return nil, fmt.Errorf("failed to decode private signing key: %v", err)
}
sigSK, err := x509.ParsePKCS8PrivateKey(sigSKBytes)
if err != nil {
return nil, fmt.Errorf("failed to parse private signing key: %v", err)
}
ecdsaPrivateKey, ok := sigSK.(*ecdsa.PrivateKey)
if !ok {
return nil, errors.New("invalid private key format")
}
return ecdsaPrivateKey, nil
}
// Sign a string using ECDSA
func ECDSASign(message []byte, privKey PrivKeyStruct) []byte {
// TODO: IMPLEMENT
hasher := sha256.New()
hasher.Write([]byte(message))
hash := hasher.Sum(nil)
_ = hash
// Decode privkey
signkey := privKey.SigSK
signkeyBase64, err := base64.StdEncoding.DecodeString(signkey)
if err != nil {
log.Fatalf("Failed to decode BASE64: %v", err)
}
_ = signkeyBase64
return nil
}
// Encrypts a byte string under a (Base64-encoded) public string, and returns a
// byte slice as a result.
func decryptMessage(payload string, senderUsername string, senderPubKey *PubKeyStruct, recipientPrivKey *PrivKeyStruct) ([]byte, error) {
var ciphertext CiphertextStruct
decodedPayload, err := base64.StdEncoding.DecodeString(payload)
if err != nil {
fmt.Println("base64 decode error")
return nil, err
}
err = json.Unmarshal(decodedPayload, &ciphertext)
if err != nil {
fmt.Println("Unmarshall error")
return nil, err
}
// Verify the signature
toVerify := ciphertext.C1 + ciphertext.C2
sigPKBytes, _ := base64.StdEncoding.DecodeString(senderPubKey.SigPK)
sigPK, err := x509.ParsePKIXPublicKey(sigPKBytes)
if err != nil {
fmt.Println("ParsePKIXPublicKey")
return nil, err
}
sigPKECDSA := sigPK.(*ecdsa.PublicKey)
signature, _ := base64.StdEncoding.DecodeString(ciphertext.Sig)
hash := sha256.Sum256([]byte(toVerify))
r := new(big.Int).SetBytes(signature[:32])
s := new(big.Int).SetBytes(signature[32:])
if !ecdsa.Verify(sigPKECDSA, hash[:], r, s) {
return nil, errors.New("signature verification failed")
}
// Decrypt C1 to obtain the shared secret K
encSKBytes, _ := base64.StdEncoding.DecodeString(recipientPrivKey.EncSK)
encSK, err := x509.ParsePKCS8PrivateKey(encSKBytes)
if err != nil {
fmt.Println("ParsePKCS8PrivateKey")
return nil, err
}
encSKECDSA := encSK.(*ecdsa.PrivateKey)
C1Bytes, _ := base64.StdEncoding.DecodeString(ciphertext.C1)
pubKeyInterface, err := x509.ParsePKIXPublicKey(C1Bytes)
if err != nil {
return nil, errors.New("invalid parsing error")
}
pubKey, ok := pubKeyInterface.(*ecdsa.PublicKey)
if !ok {
return nil, errors.New("not a ECSSA pubkic key")
}
sskX, _ := encSKECDSA.Curve.ScalarMult(pubKey.X, pubKey.Y, encSKECDSA.D.Bytes())
K := sha256.Sum256(sskX.Bytes())
// Decrypt C2 using the shared secret K
C2Bytes, _ := base64.StdEncoding.DecodeString(ciphertext.C2)
var nonce [chacha20.NonceSize]byte
cipher, err := chacha20.New(K[:], nonce[:])
if err != nil {
return nil, err
}
decryptedBytes := make([]byte, len(C2Bytes))
cipher.XORKeyStream(decryptedBytes, C2Bytes)
// Verify the integrity of the plaintext message
delimiterIndex := bytes.IndexByte(decryptedBytes[:len(decryptedBytes)-4], 0x3A)
if delimiterIndex == -1 {
return nil, errors.New("invalid plaintext format")
}
username := string(decryptedBytes[:delimiterIndex])
plaintext := decryptedBytes[delimiterIndex+1 : len(decryptedBytes)-4]
checksum := binary.BigEndian.Uint32(decryptedBytes[len(decryptedBytes)-4:])
expectedChecksum := crc32.ChecksumIEEE(decryptedBytes[:len(decryptedBytes)-4])
if checksum != expectedChecksum {
return nil, errors.New("checksum verification failed")
}
// Check if the sender's username matches the expected username
if username != senderUsername {
return nil, errors.New("sender username mismatch")
}
return plaintext, nil
}
// Encrypts a byte string under a (Base64-encoded) public string, and returns a
// byte slice as a result.
func encryptMessage(message []byte, senderUsername string, pubkey *PubKeyStruct, globalPriv1 PrivKeyStruct) []byte {
encPK := pubkey.EncPK
// BASE64 decode the string to get the DER-encoded public key
derEncodedPubKey, err := base64.StdEncoding.DecodeString(encPK)
if err != nil {
log.Fatalf("Failed to decode BASE64: %v", err)
}
// Parse the DER-encoded public key
pubKeyInterface, err := x509.ParsePKIXPublicKey(derEncodedPubKey)
if err != nil {
log.Fatalf("Failed to parse public key: %v", err)
}
// Assert the type to *ecdsa.PublicKey to get the public key in usable form
pubKey, ok := pubKeyInterface.(*ecdsa.PublicKey)
if !ok {
log.Fatalf("Not an ECDSA public key")
}
// Check if the curve is P-256
if pubKey.Curve != elliptic.P256() {
log.Fatalf("Public key is not on P-256 curve")
}
// generater a random scarler c
c, err := rand.Int(rand.Reader, pubKey.Params().N)
if err != nil {
fmt.Println("Error someting!", err)
}
//compute epk = cP
epkX, epkY := pubKey.Curve.ScalarBaseMult(c.Bytes())
//ssk
sskX, _ := pubKey.Curve.ScalarMult(pubKey.X, pubKey.Y, c.Bytes())
// compute hash of k
K := sha256.Sum256((sskX.Bytes()))
//Computing C1 now - not doing parsing here again TODO
epkPublicKey := &ecdsa.PublicKey{
Curve: pubKey.Curve,
X: epkX,
Y: epkY,
}
epkBytes, err := x509.MarshalPKIXPublicKey(epkPublicKey)
if err != nil {
log.Fatalf("Failed to encode: %v", err)
}
// Base64-encode
C1 := base64.StdEncoding.EncodeToString(epkBytes)
//Computing C2 now:
senderBytes := []byte(senderUsername)
delimiter := []byte{0x3A}
MPrime := append(senderBytes, delimiter...)
MPrime = append(MPrime, message...)
// Compute CHECK
checksum := crc32.ChecksumIEEE(MPrime)
checksumBytes := []byte{byte(checksum >> 24), byte(checksum >> 16), byte(checksum >> 8), byte(checksum)}
MDoublePrime := append(MPrime, checksumBytes...)
var nonce [chacha20.NonceSize]byte // Zero nonce
cipher, err := chacha20.New(K[:], nonce[:])
if err != nil {
log.Fatalf("Failed to create ChaCha20 cipher: %v", err)
}
encryptedMDoublePrime := make([]byte, len(MDoublePrime))
cipher.XORKeyStream(encryptedMDoublePrime, MDoublePrime)
// C2 is the BASE64-encoded encrypted M''
C2 := base64.StdEncoding.EncodeToString(encryptedMDoublePrime)
// Signature
toSign := C1 + C2
// Decode the sender's private signing key
sigSKBytes, _ := base64.StdEncoding.DecodeString(globalPriv1.SigSK)
sigSK, err := x509.ParsePKCS8PrivateKey(sigSKBytes)
if err != nil {
log.Fatalf("Failed to parse SigSK cipher: %v", err)
}
signSk1, ok := sigSK.(*ecdsa.PrivateKey)
if !ok {
return nil
}
// Sign toSign using ECDSA
hasher := sha256.New()
hasher.Write([]byte(toSign))
hash := hasher.Sum(nil)
r, s, _ := ecdsa.Sign(rand.Reader, signSk1, hash)
signature := append(r.Bytes(), s.Bytes()...)
// Encode signature into Sig
Sig := base64.StdEncoding.EncodeToString(signature)
// Construct the final ciphertext payload
payload := CiphertextStruct{C1, C2, Sig}
payloadBytes, _ := json.Marshal(payload)
return payloadBytes
}
// Decrypt a list of messages in place
func decryptMessages(messageArray []MessageStruct, globalPriv1 PrivKeyStruct) {
for i := range messageArray {
message := &messageArray[i]
if message.ReceiptID != 0 {
// Skip read receipt messages
continue
}
senderPubKey, err := getPublicKeyFromServer(message.From)
if err != nil {
fmt.Printf("Failed to retrieve public key for sender %s: %v\n", message.From, err)
continue
}
decryptedMessage, err := decryptMessage(message.Payload, message.From, senderPubKey, &globalPriv1)
if err != nil {
fmt.Printf("Failed to decrypt message from %s: %v\n", message.From, err)
continue
}
//Check if the decrypted message contains an attachment
if strings.HasPrefix(string(decryptedMessage), ">>>MSGURL=") {
parts := strings.Split(string(decryptedMessage), "?")
if len(parts) == 3 {
message.url = parts[0][10:]
keyPart := parts[1]
hashPart := parts[2]
if strings.HasPrefix(keyPart, "KEY=") && strings.HasPrefix(hashPart, "H=") {
key := keyPart[4:]
expectedHash := hashPart[2:]
// Download the attachment file
localPath := getTempFilePath()
err := downloadFileFromServer(message.url, localPath)
if err != nil {
fmt.Printf("Failed to download attachment from %s: %v\n", message.url, err)
continue
}
// Verify the hash of the downloaded file
fileHash, err := calculateFileHash(localPath)
if err != nil {
fmt.Printf("Failed to calculate hash of the downloaded file: %v\n", err)
continue
}
if fileHash != expectedHash {
fmt.Printf("Hash verification failed for the downloaded file\n")
continue
}
// Decrypt the attachment file
decryptedFilePath := getTempFilePath()
err = decryptAttachmentFile(localPath, decryptedFilePath, key)
if err != nil {
fmt.Printf("Failed to decrypt the attachment file: %v\n", err)
continue
}
message.localPath = decryptedFilePath
err = sendMessageToServer(username, message.From, nil, message.Id)
if err != nil {
fmt.Printf("Failed to send read receipt to %s: %v\n", message.From, err)
}
}
}
} else {