-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathEasyPQC.cs
More file actions
1088 lines (796 loc) · 40.3 KB
/
Copy pathEasyPQC.cs
File metadata and controls
1088 lines (796 loc) · 40.3 KB
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
using System.Text;
using Org.BouncyCastle.Pqc.Crypto.Crystals.Dilithium;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Pqc.Crypto.Crystals.Kyber;
using Data.HashFunction.Blake3;
using EasyCompressor;
using K4os.Compression.LZ4;
using Walker.Crypto;
using Org.BouncyCastle.Crypto.Digests;
using System.Data.HashFunction;
using Org.BouncyCastle.Utilities;
using static Walker.Crypto.SimpleAESEncryption;
using SecureData = WISecureData.SecureData;
namespace Pariah_Cybersecurity
{
//TODO; Parameterize and add error checks to everything
//Replace file readbytes with something faster (MMap?)
//Turn a few of these into structs (Heap safety, use classes for big files only)
//Convert a few strings to SecureData
//CLEAN UP MESS
//Change all SecureData.ConvertToString(true) to ConvertToString
//Add await to where it needs to be added
public class EasyPQC
{
public class Signatures //Used for fingerprint, Dilithium
{
public static async Task<(Dictionary<string, byte[]>, Dictionary<string, byte[]>)> CreateKeys()
{
try
{
// Initialize the random generator
var randomgen = new SecureRandom();
// Set up the key generation parameters for Dilithium5
var param = new DilithiumKeyGenerationParameters(randomgen, DilithiumParameters.Dilithium5);
// Create a key pair generator and initialize it with the parameters
var keyPairGenerator = new DilithiumKeyPairGenerator();
keyPairGenerator.Init(param);
// Generate the key pair
var keyPair = keyPairGenerator.GenerateKeyPair();
// Extract the public and private key parameters
var publicParameter = (DilithiumPublicKeyParameters)keyPair.Public;
var privateParameter = (DilithiumPrivateKeyParameters)keyPair.Private;
// Serialize the keys into byte arrays
var pubkeyBytes = Encode(publicParameter);
var privkeyBytes = Encode(privateParameter);
// Return the keys as a ByteReturnPair
return (pubkeyBytes, privkeyBytes);
}
catch
{
throw new Exception("Failed to Create Keys.");
}
}
public static async Task<byte[]> CreateSignature(Dictionary<string, byte[]> privatekeyBytes, string input)
{
try
{
var gensign = new DilithiumSigner();
var privateKey = DecodePrivate(privatekeyBytes);
gensign.Init(true, privateKey);
var inputBytes = Encoding.UTF8.GetBytes(input);
var signature = gensign.GenerateSignature(inputBytes);
return signature;
}
catch
{
throw new Exception("Failed to Create Signature.");
}
}
public async static Task<bool> VerifySignature(Dictionary<string, byte[]> publickeyBytes, byte[] signature, string input)
{
try
{
var gensign = new DilithiumSigner();
var publicKey = DecodePublic(publickeyBytes);
Console.Write(publicKey);
gensign.Init(false, publicKey);
var inputBytes = Encoding.UTF8.GetBytes(input);
return gensign.VerifySignature(inputBytes, signature);
}
catch
{
throw new Exception("Failed to Verify Signature");
}
}
public async static Task<bool> VerifySignature(Dictionary<string, byte[]> publickeyBytes, byte[] signature, byte[] inputBytes)
{
try
{
var gensign = new DilithiumSigner();
var publicKey = DecodePublic(publickeyBytes);
gensign.Init(false, publicKey);
return gensign.VerifySignature(inputBytes, signature);
}
catch
{
throw new Exception("Failed to Verify Signature");
}
}
internal static Dictionary<string, byte[]> Encode(DilithiumPublicKeyParameters key)
{
try
{
byte[] encoded = key.GetEncoded();
byte[] rho = Arrays.CopyOfRange(encoded, 0, 32);
byte[] t1 = Arrays.CopyOfRange(encoded, 32, encoded.Length);
var encodedval = new Dictionary<string, byte[]>();
encodedval.Add("rho", rho);
encodedval.Add("t1", t1);
return encodedval;
}
catch
{
throw new Exception("Failed To Encode");
}
}
internal static Dictionary<string, byte[]> Encode(DilithiumPrivateKeyParameters key)
{
try
{
var rho = key.Rho;
var k = key.K;
var tr = key.Tr;
var s1 = key.S1;
var s2 = key.S2;
var t0 = key.T0;
var t1 = key.T1;
var encodedval = new Dictionary<string, byte[]>
{
["rho"] = key.Rho,
["k"] = key.K,
["tr"] = key.Tr,
["s1"] = key.S1,
["s2"] = key.S2,
["t0"] = key.T0,
["t1"] = Arrays.Clone(key.T1)
};
return encodedval;
}
catch
{
throw new Exception("Failed To Encode");
}
}
internal static DilithiumPublicKeyParameters DecodePublic(Dictionary<string, byte[]> key)
{
try
{
byte[] rho = key["rho"];
byte[] t1 = key["t1"];
var decodedval = new DilithiumPublicKeyParameters(DilithiumParameters.Dilithium5, rho, t1);
return decodedval;
}
catch
{
throw new Exception("Decoding Public Key Failed");
}
}
internal static DilithiumPrivateKeyParameters DecodePrivate(Dictionary<string, byte[]> key)
{
try
{
var rho = key["rho"];
var k = key["k"];
var tr = key["tr"];
var s1 = key["s1"];
var s2 = key["s2"];
var t0 = key["t0"];
var t1 = key["t1"];
var decodedval = new DilithiumPrivateKeyParameters(DilithiumParameters.Dilithium5, rho, k, tr, s1, s2, t0, t1);
return decodedval;
}
catch
{
throw new Exception("Decoding Private Key Failed");
}
}
}
public class Keys //Used for secrets, onetime passes, signing, kyber
{
public struct KeyAndEncryptedText
{
public byte[] key { get; private set; }
public byte[] text { get; private set; }
public KeyAndEncryptedText(byte[] key, byte[] text)
{
this.key = key;
this.text = text;
}
}
public static (Dictionary<string, byte[]>, Dictionary<string, byte[]>) Initiate()
{
try
{
var randomgen = new SecureRandom();
var keyparams = new KyberKeyGenerationParameters(randomgen, KyberParameters.kyber1024);
var KyberPairGen = new KyberKeyPairGenerator();
KyberPairGen.Init(keyparams);
var keys = KyberPairGen.GenerateKeyPair();
var publickey = Encode((KyberPublicKeyParameters)keys.Public);
var privatekey = Encode((KyberPrivateKeyParameters)keys.Private);
return (publickey, privatekey);
}
catch
{
throw new Exception("Key Initialization Failed");
}
}
public static KeyAndEncryptedText CreateSecret(Dictionary<string, byte[]> givenkey)
{
try
{
var randomgen = new SecureRandom();
var keygen = new KyberKemGenerator(randomgen);
var deserializedpub = DecodePublic(givenkey);
var encapsulatedSecret = keygen.GenerateEncapsulated(deserializedpub);
var newsecret = encapsulatedSecret.GetSecret();
var cipher = encapsulatedSecret.GetEncapsulation();
var returnval = new KeyAndEncryptedText(newsecret, cipher);
return returnval; //Key is saved by user B, text is sent to user A
}
catch
{
throw new Exception("Failed To Create Secret I");
}
}
public static byte[] CreateSecretTwo(Dictionary<string, byte[]> privkey, byte[] cipher)
{
try
{
var deserializedpriv = DecodePrivate(privkey);
var extractor = new KyberKemExtractor(deserializedpriv);
return extractor.ExtractSecret(cipher);
}
catch
{
throw new Exception("Failed To Create Secret II");
}
}
//This took all 5 braincells to figure out, screw this >:'(
internal static Dictionary<string, byte[]> Encode(KyberPrivateKeyParameters key)
{
try
{
byte[] encoded = key.GetEncoded();
int symBytes = key.Parameters.SessionKeySize;
int totalLen = encoded.Length;
int knownTail = symBytes * 3;
byte[] sAndT = Arrays.CopyOfRange(encoded, 0, totalLen - knownTail);
byte[] rho = Arrays.CopyOfRange(encoded, totalLen - 3 * symBytes, totalLen - 2 * symBytes);
byte[] hpk = Arrays.CopyOfRange(encoded, totalLen - 2 * symBytes, totalLen - symBytes);
byte[] nonce = Arrays.CopyOfRange(encoded, totalLen - symBytes, totalLen);
int half = sAndT.Length / 2;
byte[] s = Arrays.CopyOfRange(sAndT, 0, half);
byte[] t = Arrays.CopyOfRange(sAndT, half, sAndT.Length);
return new Dictionary<string, byte[]>
{
["s"] = s,
["t"] = t,
["rho"] = rho,
["hpk"] = hpk,
["nonce"] = nonce
};
}
catch
{
throw new Exception("Decoding Private Key Failed");
}
}
internal static Dictionary<string, byte[]> Encode(KyberPublicKeyParameters key)
{
try
{
byte[] encoded = key.GetEncoded();
int symBytes = key.Parameters.SessionKeySize;
byte[] t = Arrays.CopyOfRange(encoded, 0, encoded.Length - symBytes);
byte[] rho = Arrays.CopyOfRange(encoded, encoded.Length - symBytes, encoded.Length);
return new Dictionary<string, byte[]>
{
["t"] = t,
["rho"] = rho
};
}
catch
{
throw new Exception("Decoding Public Key Failed");
}
}
internal static KyberPublicKeyParameters DecodePublic(Dictionary<string, byte[]> key)
{
try
{
var t = key["t"];
var rho = key["rho"];
return new KyberPublicKeyParameters(KyberParameters.kyber1024, t, rho); // Use the correct KyberParameters variant
}
catch
{
throw new Exception("Decoding Public Key Failed");
}
}
internal static KyberPrivateKeyParameters DecodePrivate(Dictionary<string, byte[]> key)
{
try
{
var s = key["s"];
var t = key["t"];
var rho = key["rho"];
var hpk = key["hpk"];
var nonce = key["nonce"];
return new KyberPrivateKeyParameters(KyberParameters.kyber1024, s, hpk, nonce, t, rho); // Again, use the correct parameter set
}
catch
{
throw new Exception("Decoding Private Key Failed");
}
}
}
public class FileOperations //Compresses data using LZ4 and Hashes using Blake3 (signing), great for files, messages, etc.
{
//EVERYTHING IN FILE OPERATIONS NEEDS TO BE FIXED
public struct PackedFile
{
public string FilePath { get; private set; }
public string Signature { get; private set; }
public PackedFile(string filePath, string signature)
{
this.FilePath = filePath;
this.Signature = signature;
}
public override string ToString()
{
return $"{FilePath}|{Signature}";
}
public static PackedFile FromString(string packedFileString)
{
var parts = packedFileString.Split('|');
if (parts.Length != 2)
{
throw new ArgumentException("Invalid packed file string format");
}
return new PackedFile(parts[0], parts[1]);
}
}
public enum CompressionLevel { Fast, Balanced, Max }
public delegate void CompressionProgress(long current, long fileSize, int percentage);
//Use this if you like this kind of suffering
public static async Task<string> CompressFileAsync(string fileInput, string fileOutput, CompressionProgress compressionProgress, CompressionLevel compressionType)
{
try
{
var fileInfo = new FileInfo(fileInput);
long fileSize = fileInfo.Length;
LZ4Level comptype = compressionType switch
{
CompressionLevel.Fast => LZ4Level.L00_FAST,
CompressionLevel.Balanced => LZ4Level.L09_HC,
CompressionLevel.Max => LZ4Level.L12_MAX,
_ => LZ4Level.L00_FAST
};
var compressor = new LZ4Compressor(comptype);
using var sourceStream = File.Open(fileInput, FileMode.Open, FileAccess.Read);
using var fileBytestream = new MemoryStream();
await sourceStream.CopyToAsync(fileBytestream);
fileBytestream.Position = 0;
using var compDatastream = new MemoryStream();
await compressor.CompressAsync(fileBytestream, compDatastream);
await EasyPQC.WriteAllBytesAsync(fileOutput, compDatastream.ToArray(), null);
return fileOutput;
}
catch (Exception ex)
{
Console.WriteLine($"Compression failed: {ex.Message}");
return string.Empty;
}
}
public static async Task<string> DecompressFileAsync(string fileInput, string fileOutput, CompressionProgress compressionProgress, CompressionLevel compressionType)
{
try
{
var fileInfo = new FileInfo(fileInput);
long fileSize = fileInfo.Length;
LZ4Level comptype = compressionType switch
{
CompressionLevel.Fast => LZ4Level.L00_FAST,
CompressionLevel.Balanced => LZ4Level.L09_HC,
CompressionLevel.Max => LZ4Level.L12_MAX,
_ => LZ4Level.L00_FAST
};
var compressor = new LZ4Compressor(comptype);
using var sourceStream = File.Open(fileInput, FileMode.Open, FileAccess.Read);
using var fileBytestream = new MemoryStream();
await sourceStream.CopyToAsync(fileBytestream);
fileBytestream.Position = 0;
using var compDatastream = new MemoryStream();
await compressor.DecompressAsync(fileBytestream, compDatastream);
await EasyPQC.WriteAllBytesAsync(fileOutput, compDatastream.ToArray(), null);
return fileOutput;
}
catch (Exception ex)
{
Console.WriteLine($"Decompression failed: {ex.Message}");
return string.Empty;
}
}
public static async Task<byte[]> HashFile(Stream fileData)
{
var hashFunction = (IHashFunctionAsync)Blake3Factory.Instance.Create();
var bytes = await hashFunction.ComputeHashAsync(fileData);
return bytes.Hash;
}
public static async Task<bool> VerifyHash(Stream fileData, byte[] signature)
{
var fileBytes = await HashFile(fileData);
return fileBytes.SequenceEqual(signature);
}
//Use this if you want an easy life
//Compresses the file and creates a signed filehash, make sure you use .ConvertToString(true) to make this sendable
public static async Task<PackedFile> PackFiles(
string fileInput,
string fileOutput,
Dictionary<string, byte[]> privateKey,
SecureData sessionkey,
CompressionProgress compressionProgress,
CompressionLevel compressionType,
bool encryptFile)
{
string filename = Pariah_Cybersecurity.PasswordGenerator.GeneratePassword(24, true, false, false, false);
LZ4Level comptype = compressionType switch
{
CompressionLevel.Fast => LZ4Level.L00_FAST,
CompressionLevel.Balanced => LZ4Level.L09_HC,
CompressionLevel.Max => LZ4Level.L12_MAX,
_ => LZ4Level.L00_FAST
};
var compressor = new LZ4Compressor(comptype);
byte[] fileBytes = await EasyPQC.ReadAllBytesAsync(fileInput);
using var inputStream = new MemoryStream(fileBytes);
using var compressedStream = new MemoryStream();
await compressor.CompressAsync(inputStream, compressedStream);
byte[] compressedData = compressedStream.ToArray();
string packedFilePath = $"{fileOutput}{filename}.pack";
await EasyPQC.WriteAllBytesAsync(packedFilePath, compressedData, null);
if (encryptFile)
{
string encryptedPath = $"{fileOutput}{filename}.encpack";
await Walker.Crypto.AESFileEncryptor.EncryptFileAsync(packedFilePath, encryptedPath, sessionkey);
File.Delete(packedFilePath);
packedFilePath = encryptedPath;
}
var finalpriv = Signatures.DecodePrivate(privateKey);
var privateKeyBytes = Signatures.Encode(finalpriv);
// ← here: wrap compressedData in a MemoryStream for hashing
using var hashStream = new MemoryStream(compressedData);
byte[] signatureHash = await HashFile(hashStream);
byte[] rawSignature = await Signatures.CreateSignature(
privateKeyBytes,
Convert.ToBase64String(signatureHash));
string encryptedSign = SimpleAESEncryption
.Encrypt(Convert.ToBase64String(rawSignature), sessionkey)
.ToString();
return new PackedFile(packedFilePath, encryptedSign);
}
public static async Task<bool> UnpackFile(
PackedFile inputFile,
string outputPath,
Dictionary<string, byte[]> publicKey,
CompressionProgress compressionProgress,
CompressionLevel compressionType,
SecureData sessionkey)
{
bool isEncrypted = Path.GetExtension(inputFile.FilePath) == ".encpack";
string tempFilePath = inputFile.FilePath;
if (isEncrypted)
{
tempFilePath = Path.Combine(
Path.GetTempPath(),
Path.GetFileNameWithoutExtension(inputFile.FilePath) + ".decrypted");
await Walker.Crypto.AESFileEncryptor.DecryptFileAsync(inputFile.FilePath, tempFilePath, sessionkey);
}
var decryptedSign = SimpleAESEncryption.Decrypt(
AESEncryptedText.FromString(inputFile.Signature),
sessionkey);
byte[] expectedSignature = Convert.FromBase64String(decryptedSign.ConvertToString());
byte[] compressedBytes = await EasyPQC.ReadAllBytesAsync(tempFilePath);
// ← here: wrap compressedBytes in a MemoryStream for hashing
using var hashStream = new MemoryStream(compressedBytes);
byte[] actualHash = await HashFile(hashStream);
string base64Hash = Convert.ToBase64String(actualHash);
var finalpub = Signatures.DecodePublic(publicKey);
var publicKeyBytes = Signatures.Encode(finalpub);
if (!await Signatures.VerifySignature(publicKeyBytes, expectedSignature, base64Hash))
{
if (isEncrypted) File.Delete(tempFilePath);
return false;
}
LZ4Level comptype = compressionType switch
{
CompressionLevel.Fast => LZ4Level.L00_FAST,
CompressionLevel.Balanced => LZ4Level.L09_HC,
CompressionLevel.Max => LZ4Level.L12_MAX,
_ => LZ4Level.L00_FAST
};
var compressor = new LZ4Compressor(comptype);
using var compressedStream = new MemoryStream(compressedBytes);
using var decompressedStream = new MemoryStream();
await compressor.DecompressAsync(compressedStream, decompressedStream);
string finalOutputPath = Path.Combine(outputPath, Path.GetFileNameWithoutExtension(tempFilePath));
await EasyPQC.WriteAllBytesAsync(finalOutputPath, decompressedStream.ToArray(), null);
if (isEncrypted) File.Delete(tempFilePath);
return true;
}
}
public class Rotation //Handling rotating a key, AKA creating a new session key, THIS should be used as session keys
{
//Imagine an event here says "Time to rotate!", we will make verification logic later in Pariah Networking
//Honestly? I completely forgot how I was gonna do this LOL the below is a general draft, ignore it for now
public async Task<(string, string)> CreateInitialKey(string key)
{
try
{
// UTF-8 directly, no Base64 for salt
var saltBytes = Encoding.UTF8.GetBytes(
Pariah_Cybersecurity.PasswordGenerator.GeneratePassword(32, true, true, true, false)
);
var keyBytes = UTF8Encoding.UTF8.GetBytes(key); // key is still Base64-encoded
var shakeDigest = new ShakeDigest(256);
for (int i = 0; i < 1000; i++)
{
shakeDigest.BlockUpdate(keyBytes, 0, keyBytes.Length);
shakeDigest.BlockUpdate(saltBytes, 0, saltBytes.Length);
keyBytes = new byte[shakeDigest.GetDigestSize()];
shakeDigest.DoFinal(keyBytes, 0);
shakeDigest.Reset();
}
return (Convert.ToBase64String(saltBytes), Convert.ToBase64String(keyBytes)); // still returns Base64 output
}
catch
{
throw new Exception("Creating Initial Key Failed");
}
}
public async Task<string> RotateKey(SecureData key, int rotations, string salt)
{
try
{
var utf8Key = key.ConvertToString();
var keyBytes = UTF8Encoding.UTF8.GetBytes(utf8Key);
var saltBytes = UTF8Encoding.UTF8.GetBytes(salt);
var shakeDigest = new ShakeDigest(256);
for (int i = 0; i < rotations; i++)
{
shakeDigest.BlockUpdate(keyBytes, 0, keyBytes.Length);
shakeDigest.BlockUpdate(saltBytes, 0, saltBytes.Length);
keyBytes = new byte[shakeDigest.GetDigestSize()];
shakeDigest.DoFinal(keyBytes, 0);
shakeDigest.Reset(); // Optional again
}
return Convert.ToBase64String(keyBytes);
}
catch
{
throw new Exception("Key Rotation Failed");
}
}
public static string ToBase64(string input)
{
try
{
var bytes = System.Text.Encoding.UTF8.GetBytes(input);
return Convert.ToBase64String(bytes);
}
catch
{
throw new Exception("Conversion To Base64 Failed");
}
}
}
public static async Task WriteAllBytesAsync(string path, byte[] bytes, Action<int> progressCallback = null)
{
try
{
using (var sourceStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true))
{
long totalBytes = bytes.Length;
long bytesWritten = 0;
int bufferSize = 4096;
for (int i = 0; i < bytes.Length; i += bufferSize)
{
int bytesToWrite = Math.Min(bufferSize, bytes.Length - i);
await sourceStream.WriteAsync(bytes, i, bytesToWrite);
bytesWritten += bytesToWrite;
progressCallback?.Invoke((int)((bytesWritten * 100) / totalBytes));
}
await sourceStream.FlushAsync();
}
}
catch
{
throw new Exception("Writing To Bytes Failed");
}
}
public static async Task WriteAllBytesAsync(string path, byte[] bytes, Action<int> progressCallback = null, CancellationToken cancellationToken = default)
{
try
{
using (var sourceStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true))
{
long totalBytes = bytes.Length;
long bytesWritten = 0;
int bufferSize = 4096;
for (int i = 0; i < bytes.Length; i += bufferSize)
{
cancellationToken.ThrowIfCancellationRequested();
int bytesToWrite = Math.Min(bufferSize, bytes.Length - i);
await sourceStream.WriteAsync(bytes, i, bytesToWrite, cancellationToken);
bytesWritten += bytesToWrite;
progressCallback?.Invoke((int)((bytesWritten * 100) / totalBytes));
}
await sourceStream.FlushAsync(cancellationToken);
}
}
catch
{
throw new Exception("Writing To Bytes Failed");
}
}
public static async Task<byte[]> ReadAllBytesAsync(string path)
{
try
{
using (var sourceStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true))
{
var buffer = new byte[sourceStream.Length];
int totalRead = 0;
while (totalRead < buffer.Length)
{
int bytesRead = await sourceStream.ReadAsync(buffer, totalRead, buffer.Length - totalRead);
if (bytesRead == 0)
break;
totalRead += bytesRead;
}
return buffer;
}
}
catch
{
throw new Exception("Reading From Bytes Failed");
}
}
public class Chat //AES256-GCM based encryption with key turning
{
//The sections shows are manuals on how to use the library; this will be in a fancy github wiki later
#region Ideaology
//One of my hardest scripts, but this has key turning in it (Constnatly making an encryption key available to everyone that's part of the group)
//First, the leader creates a Kyber public private key pair and the public key is shared
//Everyone uses the public key to create a key encapsulation, this is our session key
//We encrypt the session key using AES256GCM and give it to everyone
//Everyone signs their key using Dilithium, then when a message is sent we always verify it
//(Done)
//When a message is sent, we encrypt the message with the current version of the session key
//A nonce is created/signed for every message (contains a counter, the username, previous session key and message hash)
//Automatically we know the user is the user if the nonce is able to be both decrypted and read
//(Done)
//The session key is evolved with SHAKE256
//After an interval (could be time or amount of messages), we create a new kyber key, with dilithium used for authenticity (rotation)
//The below will be handled in PariahNetworking (AKA Spire)
//If someone was removed or left, we reauthenticate everyone who is active in the last hour
//If someone is added or talks, they go through SectionA (public/private key)
//Instead of rotating and switching everyone, it might be worth it to store user references as their name + their lave/join amount + rotation
//This way, instead of doing complex and intensive things we can just make sure the user needs a new key if they rejoin
//If they leave, others can still then see their messages without someone being able to act like they're them and stuff
//When someone new joins or someone is removed, we simply rotate with them
//Offline messages are handled as session keys are stored on a sender's device
//The keys are then given to the recepient when they're back, with the public kyber key for delivery, signed with dilitium
//We have an action function that handles roles, messages, etc.
//Also need CRDT and Audit Log with both being used to verify a sent in session
//I'm not sure if for searching for messages and stuff it'll use Homomorphic Encryption or something yet
#endregion
#region SectionA Example
//var leaderKeyPair = Keys.Intiiate();
//share the public key with the group, hold the private key
//Each member does var encapsulated = Keys.CreateSecret(leaderPublicKey);
//Share the encapsulated.text with the leader, store the session key leader, leader checks all verificatiosn with VerifySignature()
//The header does Keys.CreateSecretTwo(leaderPrivateKey, encryptedSessionKeyFromMember); once, save it to a dictionary with (memberID, encryptedsessionkey)
//To create a good session key, let's use PasswordGenerator.GeneratePassword(32, true, true, true, true).ToSecureData(); BUT we aren't done yet
//Now we use SimpleAESEncryption.Encrypt(encryptionkey.ConvertToString(true)(), recoverykey).ConvertToString(true)(); and we share the string with the user
//The user decrypts the string (Turn it to SimpleAESEncryption.AESEncryptedText first) to get the shared session key
//When sending out a message, we sign with the private key and send it to the others using CreateSignature()
//We verify the signature with VerifySignature() when accepting a message, the input is the nonce referenced in the dilithium section
#endregion
#region SectionB2
//It's important to create a simple, yet capable pipeline for files; we want to ensure the data is protected, comes from who it says it comes from and isn't tampered
//We will use AES256GCM, Kyber and Blake3 Respectively
//User creates a message struct with a construted MessageData and AttachmentData function; remember to use PackFiles() and UnpackFiles()
//Add more detail later
//Create function to decrypt MessageData and AttachmentData later
#endregion
public class MessageData
{
// Unique ID for the message
public string MessageId { get; }
// Name of the sender (could be a bot name or user display name, use the technical version, for example spire would be "Kirito@AnIncarnatingRadius.XYZ" or something)
public string SenderName { get; }
// Content of the message
public string Content { get; }
public DateTime Timestamp { get; }
// Flag indicating whether the message was sent by a bot
public bool IsBot { get; }
// ID of the channel the message was sent in (could be used for group chat, channels, etc.)
public string ChannelId { get; }
//The last key to be used before the rotation
public string PreviousKey { get; }
//The number of rotations done
public int Rotation { get; }
//Content is the message
public MessageData(string messageId, string senderName, string content, DateTime timestamp, bool isBot, string channelId, string previouskey, int rotation, SecureData SessionKey)
{
MessageId = messageId;
SenderName = senderName;
Content = Walker.Crypto.SimpleAESEncryption.Encrypt(content, SessionKey).ToString();
Timestamp = timestamp;
IsBot = isBot;
ChannelId = channelId;
PreviousKey = previouskey;
Rotation = rotation;
}
public override string ToString()
{
return string.Join("\n",
$"MessageId: {MessageId}",
$"SenderName: {SenderName}",
$"Content: {Content}",
$"Timestamp: {Timestamp:yyyy-MM-dd HH:mm:ss}",
$"IsBot: {IsBot}",
$"ChannelId: {ChannelId}",
$"PreviousKey: {PreviousKey}",
$"Rotation: {Rotation}");
}
public static MessageData FromString(string formattedString, SecureData ChatKey)
{
var lines = formattedString.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
string messageId = lines[0].Substring(11);
string senderName = lines[2].Substring(12);
string content = lines[3].Substring(9);
DateTime timestamp = DateTime.Parse(lines[4].Substring(11));
bool isBot = bool.Parse(lines[5].Substring(8));