aboutsummaryrefslogtreecommitdiff
path: root/src/zencore/crypto.cpp
blob: 8a172de3ad21aefa6efa2def4520da979d497588 (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
// Copyright Epic Games, Inc. All Rights Reserved.

#include <zencore/crypto.h>
#include <zencore/intmath.h>
#include <zencore/memory/memory.h>
#include <zencore/scopeguard.h>
#include <zencore/testing.h>

#include <array>
#include <string>
#include <string_view>

// On Windows we can use the built-in BCrypt API, on other platforms we currently
// support either OpenSSL or mbedTLS. The preference is to use OpenSSL if available
// mostly for historical reasons. We should investigate making mbedTLS the default
// on non-Windows platforms in future as it is more lightweight.

#if ZEN_PLATFORM_WINDOWS
#	define ZEN_USE_BCRYPT 1
#else
#	define ZEN_USE_BCRYPT 0
#endif

#ifndef ZEN_USE_OPENSSL
#	if ZEN_USE_BCRYPT
#		define ZEN_USE_OPENSSL 0
#	else
#		define ZEN_USE_OPENSSL 1
#	endif
#endif

#ifndef ZEN_USE_MBEDTLS
#	if ZEN_PLATFORM_WINDOWS
#		define ZEN_USE_MBEDTLS 0
#	elif !ZEN_USE_OPENSSL
#		define ZEN_USE_MBEDTLS 1
#	else
#		define ZEN_USE_MBEDTLS 0
#	endif
#endif

static_assert(ZEN_USE_OPENSSL + ZEN_USE_MBEDTLS + ZEN_USE_BCRYPT <= 1, "Only one crypto backend can be selected");

ZEN_THIRD_PARTY_INCLUDES_START
#include <fmt/format.h>

#if ZEN_USE_OPENSSL
#	include <openssl/conf.h>
#	include <openssl/err.h>
#	include <openssl/evp.h>
#	include <openssl/rand.h>
#elif ZEN_USE_MBEDTLS
#	include <mbedtls/cipher.h>
#	include <mbedtls/ctr_drbg.h>
#	include <mbedtls/entropy.h>
#else
#	include <zencore/windows.h>
#	include <bcrypt.h>
#	define NT_SUCCESS(Status)	(((NTSTATUS)(Status)) >= 0)
#	define STATUS_UNSUCCESSFUL ((NTSTATUS)0xC0000001L)
#endif

#if ZEN_PLATFORM_WINDOWS
#	include <zencore/windows.h>
#	include <dpapi.h>
#elif ZEN_PLATFORM_MAC
#	include <CoreFoundation/CoreFoundation.h>
#	include <Security/Security.h>
#elif ZEN_PLATFORM_LINUX && ZEN_USE_LIBSECRET
#	include <libsecret/secret.h>
#endif
ZEN_THIRD_PARTY_INCLUDES_END

namespace zen {

using namespace std::literals;

namespace crypto {
	enum class TransformMode : uint32_t
	{
		Decrypt,
		Encrypt
	};

#if ZEN_USE_MBEDTLS

	class MbedCipherCtx
	{
	public:
		MbedCipherCtx() { mbedtls_cipher_init(&m_Ctx); }
		~MbedCipherCtx() { mbedtls_cipher_free(&m_Ctx); }

		mbedtls_cipher_context_t* operator&() { return &m_Ctx; }
		mbedtls_cipher_context_t* get() { return &m_Ctx; }

	private:
		mbedtls_cipher_context_t m_Ctx;
	};

	MemoryView Transform(TransformMode				 Mode,
						 MemoryView					 Key,
						 MemoryView					 IV,
						 MemoryView					 In,
						 MutableMemoryView			 Out,
						 std::optional<std::string>& Reason)
	{
		const mbedtls_cipher_info_t* CipherInfo = mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_256_CBC);
		if (CipherInfo == nullptr)
		{
			Reason = "failed to get mbedTLS cipher info"sv;
			return MemoryView();
		}

		MbedCipherCtx Ctx;
		int			  ret = mbedtls_cipher_setup(Ctx.get(), CipherInfo);
		if (ret != 0)
		{
			Reason = fmt::format("mbedTLS cipher setup failed, ret={}", ret);
			return MemoryView();
		}

		// key length in bits
		ret = mbedtls_cipher_setkey(Ctx.get(),
									reinterpret_cast<const unsigned char*>(Key.GetData()),
									static_cast<int>(Key.GetSize() * 8),
									(Mode == TransformMode::Encrypt) ? MBEDTLS_ENCRYPT : MBEDTLS_DECRYPT);
		if (ret != 0)
		{
			Reason = fmt::format("mbedTLS setkey failed, ret={}", ret);
			return MemoryView();
		}

		ret = mbedtls_cipher_set_iv(Ctx.get(), reinterpret_cast<const unsigned char*>(IV.GetData()), static_cast<size_t>(IV.GetSize()));
		if (ret != 0)
		{
			Reason = fmt::format("mbedTLS set_iv failed, ret={}", ret);
			return MemoryView();
		}

		ret = mbedtls_cipher_set_padding_mode(Ctx.get(), MBEDTLS_PADDING_PKCS7);

		if (ret != 0)
		{
			Reason = fmt::format("mbedTLS padding mode configuration failed, ret={}", ret);
			return MemoryView();
		}

		ret = mbedtls_cipher_reset(Ctx.get());
		if (ret != 0)
		{
			Reason = fmt::format("mbedTLS reset failed, ret={}", ret);
			return MemoryView();
		}

		size_t olen	 = 0;
		size_t total = 0;

		ret = mbedtls_cipher_update(Ctx.get(),
									reinterpret_cast<const unsigned char*>(In.GetData()),
									static_cast<size_t>(In.GetSize()),
									reinterpret_cast<unsigned char*>(Out.GetData()),
									&olen);
		if (ret != 0)
		{
			Reason = fmt::format("mbedTLS update failed, ret={}", ret);
			return MemoryView();
		}

		total = olen;

		ret = mbedtls_cipher_finish(Ctx.get(), reinterpret_cast<unsigned char*>(Out.GetData()) + total, &olen);
		if (ret != 0)
		{
			Reason = fmt::format("mbedTLS finish failed, ret={}", ret);
			return MemoryView();
		}

		total += olen;

		return Out.Left(static_cast<size_t>(total));
	}
#elif ZEN_USE_OPENSSL
	class EvpContext
	{
	public:
		EvpContext() : m_Ctx(EVP_CIPHER_CTX_new()) {}
		~EvpContext() { EVP_CIPHER_CTX_free(m_Ctx); }

		operator EVP_CIPHER_CTX*() { return m_Ctx; }

	private:
		EVP_CIPHER_CTX* m_Ctx;
	};

	MemoryView Transform(TransformMode				 Mode,
						 MemoryView					 Key,
						 MemoryView					 IV,
						 MemoryView					 In,
						 MutableMemoryView			 Out,
						 std::optional<std::string>& Reason)
	{
		const EVP_CIPHER* Cipher = EVP_aes_256_cbc();

		ZEN_ASSERT(Cipher != nullptr);

		EvpContext Ctx;

		int Err = EVP_CipherInit_ex(Ctx,
									Cipher,
									nullptr,
									reinterpret_cast<const unsigned char*>(Key.GetData()),
									reinterpret_cast<const unsigned char*>(IV.GetData()),
									static_cast<int>(Mode));

		if (Err != 1)
		{
			Reason = fmt::format("failed to initialize cipher, error code '{}'", Err);

			return MemoryView();
		}

		int EncryptedBytes		= 0;
		int TotalEncryptedBytes = 0;

		Err = EVP_CipherUpdate(Ctx,
							   reinterpret_cast<unsigned char*>(Out.GetData()),
							   &EncryptedBytes,
							   reinterpret_cast<const unsigned char*>(In.GetData()),
							   static_cast<int>(In.GetSize()));

		if (Err != 1)
		{
			Reason = fmt::format("update crypto transform failed, error code '{}'", Err);

			return MemoryView();
		}

		TotalEncryptedBytes			= EncryptedBytes;
		MutableMemoryView Remaining = Out.RightChop(EncryptedBytes);

		EncryptedBytes = static_cast<int>(Remaining.GetSize());

		Err = EVP_CipherFinal(Ctx, reinterpret_cast<unsigned char*>(Remaining.GetData()), &EncryptedBytes);

		if (Err != 1)
		{
			Reason = fmt::format("finalize crypto transform failed, error code '{}'", Err);

			return MemoryView();
		}

		TotalEncryptedBytes += EncryptedBytes;

		return Out.Left(TotalEncryptedBytes);
	}
#else
	MemoryView Transform(TransformMode				 Mode,
						 MemoryView					 Key,
						 MemoryView					 IV,
						 MemoryView					 In,
						 MutableMemoryView			 Out,
						 std::optional<std::string>& Reason)
	{
		BCRYPT_ALG_HANDLE hAesAlg = NULL;
		NTSTATUS		  Status  = STATUS_UNSUCCESSFUL;

		// Open an algorithm handle.
		if (!NT_SUCCESS(Status = BCryptOpenAlgorithmProvider(&hAesAlg, BCRYPT_AES_ALGORITHM, NULL, 0)))
		{
			Reason = fmt::format("Error 0x{:08x} returned by BCryptGetProperty"sv, Status);
			return {};
		}

		auto _ = MakeGuard([hAesAlg] { BCryptCloseAlgorithmProvider(hAesAlg, 0); });

		DWORD cbData = 0;

		DWORD cbBlockLen = 0;
		if (!NT_SUCCESS(Status = BCryptGetProperty(hAesAlg, BCRYPT_BLOCK_LENGTH, (PBYTE)&cbBlockLen, sizeof(DWORD), &cbData, 0)))
		{
			Reason = fmt::format("Error 0x{:08x} returned  by BCryptGetProperty"sv, Status);
			return {};
		}

		if (cbBlockLen > IV.GetSize())
		{
			Reason = "block length is longer than the provided IV length"sv;

			return {};
		}

		AesIV128Bit MutableIV = AesIV128Bit::FromMemoryView(IV);

		if (!NT_SUCCESS(
				Status = BCryptSetProperty(hAesAlg, BCRYPT_CHAINING_MODE, (PBYTE)BCRYPT_CHAIN_MODE_CBC, sizeof(BCRYPT_CHAIN_MODE_CBC), 0)))
		{
			Reason = fmt::format("Error 0x{:08x} returned by BCryptSetProperty"sv, Status);
			return {};
		}

		DWORD cbKeyObject = 0;
		if (!NT_SUCCESS(Status = BCryptGetProperty(hAesAlg, BCRYPT_OBJECT_LENGTH, (PBYTE)&cbKeyObject, sizeof(DWORD), &cbData, 0)))
		{
			Reason = fmt::format("Error 0x{:08x} returned  by BCryptGetProperty"sv, Status);
			return {};
		}

		PBYTE pbKeyObject = (PBYTE)Memory::Alloc(cbKeyObject);
		if (NULL == pbKeyObject)
		{
			Reason = fmt::format("memory allocation failed");
			return {};
		}

		auto __ = MakeGuard([pbKeyObject] { Memory::Free(pbKeyObject); });

		BCRYPT_KEY_HANDLE hKey = NULL;

		if (!NT_SUCCESS(Status = BCryptGenerateSymmetricKey(hAesAlg,
															&hKey,
															pbKeyObject,
															cbKeyObject,
															(PBYTE)Key.GetData(),
															(ULONG)Key.GetSize(),
															/* flags */ 0)))
		{
			Reason = fmt::format("Error 0x{:08x} returned by BCryptGenerateSymmetricKey"sv, Status);
			return {};
		}

		auto ___ = MakeGuard([hKey] { BCryptDestroyKey(hKey); });

		if (Mode == TransformMode::Encrypt)
		{
			DWORD CipherTextByteCount = 0;
			if (NT_SUCCESS(Status = BCryptEncrypt(hKey,
												  (PUCHAR)In.GetData(),
												  (ULONG)In.GetSize(),
												  NULL,
												  (PUCHAR)MutableIV.GetView().GetData(),
												  cbBlockLen,
												  NULL,
												  0,
												  &CipherTextByteCount,
												  BCRYPT_BLOCK_PADDING)))
			{
				if (Out.GetSize() < CipherTextByteCount)
				{
					Reason = "invalid output buffer size";
					return {};
				}

				if (NT_SUCCESS(Status = BCryptEncrypt(hKey,
													  (PUCHAR)In.GetData(),
													  (ULONG)In.GetSize(),
													  NULL,
													  (PUCHAR)MutableIV.GetView().GetData(),
													  cbBlockLen,
													  (PUCHAR)Out.GetData(),
													  (ULONG)Out.GetSize(),
													  &CipherTextByteCount,
													  BCRYPT_BLOCK_PADDING)))
				{
					return Out.Left(CipherTextByteCount);
				}
			}

			Reason = fmt::format("Error 0x{:08x} returned by BCryptEncrypt", Status);
			return {};
		}
		else
		{
			DWORD PlainTextByteCount = 0;

			//
			// Get the output buffer size.
			//
			if (NT_SUCCESS(Status = BCryptDecrypt(hKey,
												  (PUCHAR)In.GetData(),
												  (ULONG)In.GetSize(),
												  NULL,
												  (PUCHAR)MutableIV.GetView().GetData(),
												  cbBlockLen,
												  NULL,
												  0,
												  &PlainTextByteCount,
												  BCRYPT_BLOCK_PADDING)))
			{
				if (Out.GetSize() < PlainTextByteCount)
				{
					Reason = "invalid output buffer size"sv;
					return {};
				}

				if (NT_SUCCESS(Status = BCryptDecrypt(hKey,
													  (PUCHAR)In.GetData(),
													  (ULONG)In.GetSize(),
													  NULL,
													  (PUCHAR)MutableIV.GetView().GetData(),
													  cbBlockLen,
													  (PUCHAR)Out.GetData(),
													  (ULONG)Out.GetSize(),
													  &PlainTextByteCount,
													  BCRYPT_BLOCK_PADDING)))
				{
					return Out.Left(PlainTextByteCount);
				}
			}

			Reason = fmt::format("Error 0x{:08x} returned by BCryptDecrypt"sv, Status);
			return {};
		}
	}
#endif

	bool ValidateKeyAndIV(const AesKey256Bit& Key, const AesIV128Bit& IV, std::optional<std::string>& Reason)
	{
		if (Key.IsValid() == false)
		{
			Reason = "invalid key"sv;

			return false;
		}

		if (IV.IsValid() == false)
		{
			Reason = "invalid initialization vector"sv;

			return false;
		}

		return true;
	}

	//////////////////////////////////////////////////////////////////////////
	//
	// AES-256-GCM backends
	//

#if ZEN_USE_MBEDTLS

	MemoryView GcmTransform(TransformMode				Mode,
							const AesKey256Bit&			Key,
							MemoryView					Nonce,
							MemoryView					Aad,
							MemoryView					In,
							MutableMemoryView			Out,
							MutableMemoryView			TagOut,	 // only used for Encrypt
							MemoryView					TagIn,	 // only used for Decrypt
							std::optional<std::string>& Reason)
	{
		Reason = "AES-GCM is not implemented on the mbedTLS backend"sv;
		(void)Mode;
		(void)Key;
		(void)Nonce;
		(void)Aad;
		(void)In;
		(void)Out;
		(void)TagOut;
		(void)TagIn;
		return MemoryView();
	}

#elif ZEN_USE_OPENSSL

	MemoryView GcmTransform(TransformMode				Mode,
							const AesKey256Bit&			Key,
							MemoryView					Nonce,
							MemoryView					Aad,
							MemoryView					In,
							MutableMemoryView			Out,
							MutableMemoryView			TagOut,
							MemoryView					TagIn,
							std::optional<std::string>& Reason)
	{
		EvpContext Ctx;

		const EVP_CIPHER* Cipher = EVP_aes_256_gcm();
		ZEN_ASSERT(Cipher != nullptr);

		const bool Encrypting = (Mode == TransformMode::Encrypt);

		if (EVP_CipherInit_ex(Ctx, Cipher, nullptr, nullptr, nullptr, Encrypting ? 1 : 0) != 1)
		{
			Reason = "EVP_CipherInit_ex (algo) failed"sv;
			return {};
		}

		// Explicitly set IV length to 12; the default is 12 for GCM but pinning
		// it prevents any surprise from an OpenSSL build that defaults
		// differently.
		if (EVP_CIPHER_CTX_ctrl(Ctx, EVP_CTRL_AEAD_SET_IVLEN, (int)AesGcm::NonceSize, nullptr) != 1)
		{
			Reason = "EVP_CTRL_AEAD_SET_IVLEN failed"sv;
			return {};
		}

		if (EVP_CipherInit_ex(Ctx,
							  nullptr,
							  nullptr,
							  reinterpret_cast<const unsigned char*>(Key.GetView().GetData()),
							  reinterpret_cast<const unsigned char*>(Nonce.GetData()),
							  Encrypting ? 1 : 0) != 1)
		{
			Reason = "EVP_CipherInit_ex (key+nonce) failed"sv;
			return {};
		}

		// Feed AAD (if any) before the ciphertext/plaintext.
		if (!Aad.IsEmpty())
		{
			int AadOutLen = 0;
			if (EVP_CipherUpdate(Ctx,
								 nullptr,
								 &AadOutLen,
								 reinterpret_cast<const unsigned char*>(Aad.GetData()),
								 static_cast<int>(Aad.GetSize())) != 1)
			{
				Reason = "EVP_CipherUpdate (AAD) failed"sv;
				return {};
			}
		}

		// For decrypt, set the expected tag before calling Final so the tag
		// check can fail cleanly.
		if (!Encrypting)
		{
			if (EVP_CIPHER_CTX_ctrl(Ctx, EVP_CTRL_AEAD_SET_TAG, (int)TagIn.GetSize(), (void*)TagIn.GetData()) != 1)
			{
				Reason = "EVP_CTRL_AEAD_SET_TAG failed"sv;
				return {};
			}
		}

		int BodyLen = 0;
		if (EVP_CipherUpdate(Ctx,
							 reinterpret_cast<unsigned char*>(Out.GetData()),
							 &BodyLen,
							 reinterpret_cast<const unsigned char*>(In.GetData()),
							 static_cast<int>(In.GetSize())) != 1)
		{
			Reason = "EVP_CipherUpdate (body) failed"sv;
			return {};
		}

		int FinalLen = 0;
		if (EVP_CipherFinal_ex(Ctx, reinterpret_cast<unsigned char*>(Out.GetData()) + BodyLen, &FinalLen) != 1)
		{
			// For decrypt, this is the authentication-tag mismatch path.
			Reason = Encrypting ? std::string("EVP_CipherFinal_ex (encrypt) failed") : std::string("AES-GCM authentication tag mismatch");
			return {};
		}

		if (Encrypting)
		{
			if (EVP_CIPHER_CTX_ctrl(Ctx, EVP_CTRL_AEAD_GET_TAG, (int)TagOut.GetSize(), TagOut.GetData()) != 1)
			{
				Reason = "EVP_CTRL_AEAD_GET_TAG failed"sv;
				return {};
			}
		}

		return Out.Left(static_cast<size_t>(BodyLen + FinalLen));
	}

#else  // ZEN_USE_BCRYPT

	MemoryView GcmTransform(TransformMode				Mode,
							const AesKey256Bit&			Key,
							MemoryView					Nonce,
							MemoryView					Aad,
							MemoryView					In,
							MutableMemoryView			Out,
							MutableMemoryView			TagOut,
							MemoryView					TagIn,
							std::optional<std::string>& Reason)
	{
		BCRYPT_ALG_HANDLE hAlg	 = nullptr;
		NTSTATUS		  Status = STATUS_UNSUCCESSFUL;

		if (!NT_SUCCESS(Status = BCryptOpenAlgorithmProvider(&hAlg, BCRYPT_AES_ALGORITHM, nullptr, 0)))
		{
			Reason = fmt::format("BCryptOpenAlgorithmProvider failed, 0x{:08x}"sv, Status);
			return {};
		}
		auto CloseAlg = MakeGuard([hAlg] { BCryptCloseAlgorithmProvider(hAlg, 0); });

		if (!NT_SUCCESS(Status =
							BCryptSetProperty(hAlg, BCRYPT_CHAINING_MODE, (PUCHAR)BCRYPT_CHAIN_MODE_GCM, sizeof(BCRYPT_CHAIN_MODE_GCM), 0)))
		{
			Reason = fmt::format("BCryptSetProperty(CHAIN_MODE_GCM) failed, 0x{:08x}"sv, Status);
			return {};
		}

		BCRYPT_KEY_HANDLE hKey = nullptr;
		if (!NT_SUCCESS(Status = BCryptGenerateSymmetricKey(hAlg,
															&hKey,
															nullptr,
															0,
															(PUCHAR)Key.GetView().GetData(),
															(ULONG)Key.GetView().GetSize(),
															0)))
		{
			Reason = fmt::format("BCryptGenerateSymmetricKey failed, 0x{:08x}"sv, Status);
			return {};
		}
		auto CloseKey = MakeGuard([hKey] { BCryptDestroyKey(hKey); });

		BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO AuthInfo;
		BCRYPT_INIT_AUTH_MODE_INFO(AuthInfo);
		AuthInfo.pbNonce	= (PUCHAR)Nonce.GetData();
		AuthInfo.cbNonce	= (ULONG)Nonce.GetSize();
		AuthInfo.pbAuthData = Aad.IsEmpty() ? nullptr : (PUCHAR)Aad.GetData();
		AuthInfo.cbAuthData = (ULONG)Aad.GetSize();

		ULONG ResultLen = 0;

		if (Mode == TransformMode::Encrypt)
		{
			AuthInfo.pbTag = (PUCHAR)TagOut.GetData();
			AuthInfo.cbTag = (ULONG)TagOut.GetSize();

			Status = BCryptEncrypt(hKey,
								   (PUCHAR)In.GetData(),
								   (ULONG)In.GetSize(),
								   &AuthInfo,
								   nullptr,
								   0,
								   (PUCHAR)Out.GetData(),
								   (ULONG)Out.GetSize(),
								   &ResultLen,
								   /*flags=*/0);

			if (!NT_SUCCESS(Status))
			{
				Reason = fmt::format("BCryptEncrypt (GCM) failed, 0x{:08x}"sv, Status);
				return {};
			}
		}
		else
		{
			AuthInfo.pbTag = (PUCHAR)TagIn.GetData();
			AuthInfo.cbTag = (ULONG)TagIn.GetSize();

			Status = BCryptDecrypt(hKey,
								   (PUCHAR)In.GetData(),
								   (ULONG)In.GetSize(),
								   &AuthInfo,
								   nullptr,
								   0,
								   (PUCHAR)Out.GetData(),
								   (ULONG)Out.GetSize(),
								   &ResultLen,
								   /*flags=*/0);

			if (!NT_SUCCESS(Status))
			{
				// STATUS_AUTH_TAG_MISMATCH (0xC000A002) is the tag-failure path.
				Reason = fmt::format("BCryptDecrypt (GCM) failed, 0x{:08x}"sv, Status);
				return {};
			}
		}

		return Out.Left(ResultLen);
	}

#endif	// backend selection

	MemoryView Gcm(TransformMode			   Mode,
				   const AesKey256Bit&		   Key,
				   MemoryView				   Nonce,
				   MemoryView				   Aad,
				   MemoryView				   In,
				   MutableMemoryView		   Out,
				   MutableMemoryView		   TagOut,
				   MemoryView				   TagIn,
				   std::optional<std::string>& Reason)
	{
		if (!Key.IsValid())
		{
			Reason = "invalid key"sv;
			return {};
		}
		if (Nonce.GetSize() != AesGcm::NonceSize)
		{
			Reason = fmt::format("AES-GCM nonce must be exactly {} bytes"sv, AesGcm::NonceSize);
			return {};
		}
		if (Out.GetSize() < In.GetSize())
		{
			Reason = "AES-GCM output buffer is too small"sv;
			return {};
		}
		if (Mode == TransformMode::Encrypt)
		{
			if (TagOut.GetSize() != AesGcm::TagSize)
			{
				Reason = fmt::format("AES-GCM tag output must be exactly {} bytes"sv, AesGcm::TagSize);
				return {};
			}
		}
		else
		{
			if (TagIn.GetSize() != AesGcm::TagSize)
			{
				Reason = fmt::format("AES-GCM tag input must be exactly {} bytes"sv, AesGcm::TagSize);
				return {};
			}
		}

		return GcmTransform(Mode, Key, Nonce, Aad, In, Out, TagOut, TagIn, Reason);
	}

}  // namespace crypto

bool
SecureRandomBytes(MutableMemoryView Out)
{
	if (Out.GetSize() == 0)
	{
		return true;
	}

#if ZEN_USE_BCRYPT
	NTSTATUS Status =
		BCryptGenRandom(nullptr, static_cast<PUCHAR>(Out.GetData()), static_cast<ULONG>(Out.GetSize()), BCRYPT_USE_SYSTEM_PREFERRED_RNG);
	return NT_SUCCESS(Status);
#elif ZEN_USE_OPENSSL
	return RAND_bytes(static_cast<unsigned char*>(Out.GetData()), static_cast<int>(Out.GetSize())) == 1;
#else  // ZEN_USE_MBEDTLS
	mbedtls_entropy_context	 Entropy;
	mbedtls_ctr_drbg_context Drbg;
	mbedtls_entropy_init(&Entropy);
	mbedtls_ctr_drbg_init(&Drbg);
	auto _ = MakeGuard([&]() {
		mbedtls_ctr_drbg_free(&Drbg);
		mbedtls_entropy_free(&Entropy);
	});
	if (mbedtls_ctr_drbg_seed(&Drbg, mbedtls_entropy_func, &Entropy, nullptr, 0) != 0)
	{
		return false;
	}
	return mbedtls_ctr_drbg_random(&Drbg, static_cast<unsigned char*>(Out.GetData()), Out.GetSize()) == 0;
#endif
}

#if ZEN_PLATFORM_MAC || (ZEN_PLATFORM_LINUX && ZEN_USE_LIBSECRET)
namespace {
	// Keychain-backed wrap/unwrap. Plaintext is stored in the OS keyring under a
	// fixed service and a per-call random account id. The "wrapped" blob returned to
	// the caller is just the account id bytes; the plaintext never lands on disk.
	constexpr size_t kKeychainAccountBytes	= 16;
	constexpr char	 kKeychainServiceName[] = "org.unrealengine.zen.auth";

	bool AccountStringFromBytes(const uint8_t* Bytes, size_t Size, char* OutHex, size_t OutHexSize)
	{
		if (OutHexSize < Size * 2 + 1)
		{
			return false;
		}
		for (size_t i = 0; i < Size; ++i)
		{
			static const char kHex[] = "0123456789abcdef";
			OutHex[i * 2]			 = kHex[Bytes[i] >> 4];
			OutHex[i * 2 + 1]		 = kHex[Bytes[i] & 0x0F];
		}
		OutHex[Size * 2] = '\0';
		return true;
	}
}  // namespace
#endif

#if ZEN_PLATFORM_LINUX && ZEN_USE_LIBSECRET
namespace {
	// Schema name is shared across zen installs on the machine — uniqueness per
	// install comes from the random `account` attribute.
	const SecretSchema* ZenAuthSchema()
	{
		static const SecretSchema Schema = {"org.unrealengine.zen.AuthMachineKey",
											SECRET_SCHEMA_NONE,
											{
												{"account", SECRET_SCHEMA_ATTRIBUTE_STRING},
												{nullptr, SecretSchemaAttributeType(0)},
											},
											// reserved
											0,
											0,
											0,
											0,
											0,
											0,
											0};
		return &Schema;
	}
}  // namespace
#endif

bool
TryProtectData(MemoryView Plaintext, std::vector<uint8_t>& OutProtected)
{
#if ZEN_PLATFORM_WINDOWS
	DATA_BLOB In{static_cast<DWORD>(Plaintext.GetSize()), const_cast<BYTE*>(static_cast<const BYTE*>(Plaintext.GetData()))};
	DATA_BLOB Out{};
	if (!CryptProtectData(&In, L"zen auth machine key", nullptr, nullptr, nullptr, 0, &Out))
	{
		return false;
	}
	auto _ = MakeGuard([&Out]() { LocalFree(Out.pbData); });
	OutProtected.assign(Out.pbData, Out.pbData + Out.cbData);
	return true;
#elif ZEN_PLATFORM_MAC
	uint8_t AccountBytes[kKeychainAccountBytes];
	if (!SecureRandomBytes(MutableMemoryView(AccountBytes, sizeof(AccountBytes))))
	{
		return false;
	}
	char AccountHex[sizeof(AccountBytes) * 2 + 1];
	AccountStringFromBytes(AccountBytes, sizeof(AccountBytes), AccountHex, sizeof(AccountHex));

	CFStringRef Account = CFStringCreateWithCString(nullptr, AccountHex, kCFStringEncodingASCII);
	if (Account == nullptr)
	{
		return false;
	}
	auto _A = MakeGuard([&]() { CFRelease(Account); });

	CFDataRef Secret = CFDataCreate(nullptr, static_cast<const UInt8*>(Plaintext.GetData()), static_cast<CFIndex>(Plaintext.GetSize()));
	if (Secret == nullptr)
	{
		return false;
	}
	auto _S = MakeGuard([&]() { CFRelease(Secret); });

	const void*		Keys[]	 = {kSecClass, kSecAttrService, kSecAttrAccount, kSecValueData, kSecAttrAccessible};
	const void*		Values[] = {kSecClassGenericPassword,
							CFSTR("org.unrealengine.zen.auth"),
							Account,
							Secret,
							kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly};
	CFDictionaryRef Attrs	 = CFDictionaryCreate(nullptr,
												  Keys,
												  Values,
												  sizeof(Keys) / sizeof(*Keys),
												  &kCFTypeDictionaryKeyCallBacks,
												  &kCFTypeDictionaryValueCallBacks);
	if (Attrs == nullptr)
	{
		return false;
	}
	auto _D = MakeGuard([&]() { CFRelease(Attrs); });

	OSStatus Status = SecItemAdd(Attrs, nullptr);
	if (Status != errSecSuccess)
	{
		return false;
	}
	OutProtected.assign(AccountBytes, AccountBytes + sizeof(AccountBytes));
	return true;
#elif ZEN_PLATFORM_LINUX && ZEN_USE_LIBSECRET
	uint8_t AccountBytes[kKeychainAccountBytes];
	if (!SecureRandomBytes(MutableMemoryView(AccountBytes, sizeof(AccountBytes))))
	{
		return false;
	}
	char AccountHex[sizeof(AccountBytes) * 2 + 1];
	AccountStringFromBytes(AccountBytes, sizeof(AccountBytes), AccountHex, sizeof(AccountHex));

	// libsecret password APIs take UTF-8 strings, so base64 the raw key material
	// before handing it to the keyring. Decoded back on lookup.
	gchar* Encoded = g_base64_encode(static_cast<const guchar*>(Plaintext.GetData()), Plaintext.GetSize());
	if (Encoded == nullptr)
	{
		return false;
	}
	auto _E = MakeGuard([&]() { g_free(Encoded); });

	GError*	 Err = nullptr;
	gboolean Ok	 = secret_password_store_sync(ZenAuthSchema(),
											  SECRET_COLLECTION_DEFAULT,
											  "zen auth machine key",
											  Encoded,
											  nullptr,
											  &Err,
											  "account",
											  AccountHex,
											  nullptr);
	if (Err != nullptr)
	{
		g_error_free(Err);
	}
	if (!Ok)
	{
		return false;
	}
	OutProtected.assign(AccountBytes, AccountBytes + sizeof(AccountBytes));
	return true;
#else
	(void)Plaintext;
	(void)OutProtected;
	return false;
#endif
}

bool
TryUnprotectData(MemoryView Protected, std::vector<uint8_t>& OutPlaintext)
{
#if ZEN_PLATFORM_WINDOWS
	DATA_BLOB In{static_cast<DWORD>(Protected.GetSize()), const_cast<BYTE*>(static_cast<const BYTE*>(Protected.GetData()))};
	DATA_BLOB Out{};
	if (!CryptUnprotectData(&In, nullptr, nullptr, nullptr, nullptr, 0, &Out))
	{
		return false;
	}
	auto _ = MakeGuard([&Out]() { LocalFree(Out.pbData); });
	OutPlaintext.assign(Out.pbData, Out.pbData + Out.cbData);
	return true;
#elif ZEN_PLATFORM_MAC
	if (Protected.GetSize() != kKeychainAccountBytes)
	{
		return false;
	}
	char AccountHex[kKeychainAccountBytes * 2 + 1];
	AccountStringFromBytes(static_cast<const uint8_t*>(Protected.GetData()), kKeychainAccountBytes, AccountHex, sizeof(AccountHex));

	CFStringRef Account = CFStringCreateWithCString(nullptr, AccountHex, kCFStringEncodingASCII);
	if (Account == nullptr)
	{
		return false;
	}
	auto _A = MakeGuard([&]() { CFRelease(Account); });

	const void*		Keys[]	 = {kSecClass, kSecAttrService, kSecAttrAccount, kSecReturnData, kSecMatchLimit};
	const void*		Values[] = {kSecClassGenericPassword, CFSTR("org.unrealengine.zen.auth"), Account, kCFBooleanTrue, kSecMatchLimitOne};
	CFDictionaryRef Query	 = CFDictionaryCreate(nullptr,
												  Keys,
												  Values,
												  sizeof(Keys) / sizeof(*Keys),
												  &kCFTypeDictionaryKeyCallBacks,
												  &kCFTypeDictionaryValueCallBacks);
	if (Query == nullptr)
	{
		return false;
	}
	auto _D = MakeGuard([&]() { CFRelease(Query); });

	CFTypeRef Result = nullptr;
	OSStatus  Status = SecItemCopyMatching(Query, &Result);
	if (Status != errSecSuccess || Result == nullptr)
	{
		return false;
	}
	auto _R = MakeGuard([&]() { CFRelease(Result); });

	if (CFGetTypeID(Result) != CFDataGetTypeID())
	{
		return false;
	}
	CFDataRef	  Data	  = static_cast<CFDataRef>(Result);
	const UInt8*  DataPtr = CFDataGetBytePtr(Data);
	const CFIndex DataLen = CFDataGetLength(Data);
	OutPlaintext.assign(DataPtr, DataPtr + DataLen);
	return true;
#elif ZEN_PLATFORM_LINUX && ZEN_USE_LIBSECRET
	if (Protected.GetSize() != kKeychainAccountBytes)
	{
		return false;
	}
	char AccountHex[kKeychainAccountBytes * 2 + 1];
	AccountStringFromBytes(static_cast<const uint8_t*>(Protected.GetData()), kKeychainAccountBytes, AccountHex, sizeof(AccountHex));

	GError* Err		= nullptr;
	gchar*	Encoded = secret_password_lookup_sync(ZenAuthSchema(), nullptr, &Err, "account", AccountHex, nullptr);
	if (Err != nullptr)
	{
		g_error_free(Err);
	}
	if (Encoded == nullptr)
	{
		return false;
	}
	// `secret_password_free` zeroes memory before freeing; use it rather than g_free.
	auto _E = MakeGuard([&]() { secret_password_free(Encoded); });

	gsize	DecodedLen = 0;
	guchar* Decoded	   = g_base64_decode(Encoded, &DecodedLen);
	if (Decoded == nullptr)
	{
		return false;
	}
	auto _D = MakeGuard([&]() { g_free(Decoded); });

	OutPlaintext.assign(Decoded, Decoded + DecodedLen);
	return true;
#else
	(void)Protected;
	(void)OutPlaintext;
	return false;
#endif
}

MemoryView
Aes::Encrypt(const AesKey256Bit& Key, const AesIV128Bit& IV, MemoryView In, MutableMemoryView Out, std::optional<std::string>& Reason)
{
	if (crypto::ValidateKeyAndIV(Key, IV, Reason) == false)
	{
		return MemoryView();
	}

	return crypto::Transform(crypto::TransformMode::Encrypt, Key.GetView(), IV.GetView(), In, Out, Reason);
}

MemoryView
Aes::Decrypt(const AesKey256Bit& Key, const AesIV128Bit& IV, MemoryView In, MutableMemoryView Out, std::optional<std::string>& Reason)
{
	if (crypto::ValidateKeyAndIV(Key, IV, Reason) == false)
	{
		return MemoryView();
	}

	return crypto::Transform(crypto::TransformMode::Decrypt, Key.GetView(), IV.GetView(), In, Out, Reason);
}

MemoryView
AesGcm::Encrypt(const AesKey256Bit&			Key,
				MemoryView					Nonce,
				MemoryView					Aad,
				MemoryView					Plaintext,
				MutableMemoryView			Out,
				MutableMemoryView			OutTag,
				std::optional<std::string>& Reason)
{
	return crypto::Gcm(crypto::TransformMode::Encrypt, Key, Nonce, Aad, Plaintext, Out, OutTag, /*TagIn*/ {}, Reason);
}

MemoryView
AesGcm::Decrypt(const AesKey256Bit&			Key,
				MemoryView					Nonce,
				MemoryView					Aad,
				MemoryView					Ciphertext,
				MemoryView					Tag,
				MutableMemoryView			Out,
				std::optional<std::string>& Reason)
{
	return crypto::Gcm(crypto::TransformMode::Decrypt, Key, Nonce, Aad, Ciphertext, Out, /*TagOut*/ {}, Tag, Reason);
}

//////////////////////////////////////////////////////////////////////////
//
// CryptoRandom
//

bool
CryptoRandom::Fill(MutableMemoryView Buffer, std::optional<std::string>* Reason)
{
	if (Buffer.GetSize() == 0)
	{
		return true;
	}

	auto SetReason = [&](std::string Msg) {
		if (Reason)
		{
			*Reason = std::move(Msg);
		}
	};

#if ZEN_USE_BCRYPT
	// BCRYPT_USE_SYSTEM_PREFERRED_RNG draws from the OS CSPRNG without
	// requiring the caller to manage an algorithm handle.
	const NTSTATUS Status = BCryptGenRandom(nullptr, (PUCHAR)Buffer.GetData(), (ULONG)Buffer.GetSize(), BCRYPT_USE_SYSTEM_PREFERRED_RNG);
	if (!NT_SUCCESS(Status))
	{
		SetReason(fmt::format("BCryptGenRandom failed, 0x{:08x}", static_cast<uint32_t>(Status)));
		return false;
	}
	return true;
#elif ZEN_USE_OPENSSL
	// RAND_bytes returns 1 on success, 0 on failure, -1 if not supported.
	const int Rc = RAND_bytes(reinterpret_cast<unsigned char*>(Buffer.GetData()), static_cast<int>(Buffer.GetSize()));
	if (Rc != 1)
	{
		SetReason(fmt::format("RAND_bytes failed (rc={})", Rc));
		return false;
	}
	return true;
#else
	// mbedTLS: no CSPRNG wired up here yet.  Callers on this backend must
	// provide their own random source until a proper wiring is added.
	SetReason("CryptoRandom::Fill is not implemented on the mbedTLS backend");
	(void)Buffer;
	return false;
#endif
}

#if ZEN_WITH_TESTS

void
crypto_forcelink()
{
}

TEST_SUITE_BEGIN("core.crypto");

TEST_CASE("crypto.bits")
{
	using CryptoBits256Bit = CryptoBits<256>;

	CryptoBits256Bit Bits;

	CHECK(Bits.IsNull());
	CHECK(Bits.IsValid() == false);

	CHECK(Bits.GetBitCount() == 256);
	CHECK(Bits.GetSize() == 32);

	Bits = CryptoBits256Bit::FromString("Addff"sv);
	CHECK(Bits.IsValid() == false);

	Bits = CryptoBits256Bit::FromString("abcdefghijklmnopqrstuvxyz0123456"sv);
	CHECK(Bits.IsValid());

	auto SmallerBits = CryptoBits<128>::FromString("abcdefghijklmnopqrstuvxyz0123456"sv);
	CHECK(SmallerBits.IsValid() == false);
}

TEST_CASE("crypto.aes")
{
	SUBCASE("basic")
	{
		const uint8_t	   InitVector[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
		const AesKey256Bit Key			= AesKey256Bit::FromString("abcdefghijklmnopqrstuvxyz0123456"sv);
		const AesIV128Bit  IV			= AesIV128Bit::FromMemoryView(MakeMemoryView(InitVector));

		std::string_view PlainText = "The quick brown fox jumps over the lazy dog"sv;

		std::vector<uint8_t>	   EncryptionBuffer;
		std::vector<uint8_t>	   DecryptionBuffer;
		std::optional<std::string> Reason;

		EncryptionBuffer.resize(PlainText.size() + Aes::BlockSize);
		DecryptionBuffer.resize(PlainText.size() + Aes::BlockSize);

		MemoryView EncryptedView = Aes::Encrypt(Key, IV, MakeMemoryView(PlainText), MakeMutableMemoryView(EncryptionBuffer), Reason);
		CHECK(Reason.has_value() == false);
		MemoryView DecryptedView = Aes::Decrypt(Key, IV, EncryptedView, MakeMutableMemoryView(DecryptionBuffer), Reason);
		CHECK(Reason.has_value() == false);

		std::string_view EncryptedDecryptedText =
			std::string_view(reinterpret_cast<const char*>(DecryptedView.GetData()), DecryptedView.GetSize());

		CHECK(EncryptedDecryptedText == PlainText);
	}
}

TEST_CASE("crypto.aesgcm")
{
	const AesKey256Bit Key							 = AesKey256Bit::FromString("abcdefghijklmnopqrstuvxyz0123456"sv);
	const uint8_t	   NonceBytes[AesGcm::NonceSize] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
	const MemoryView   Nonce						 = MakeMemoryView(NonceBytes);

	SUBCASE("round trip without AAD")
	{
		std::string_view Plain = "The quick brown fox jumps over the lazy dog"sv;

		std::vector<uint8_t>	   Cipher(Plain.size());
		std::vector<uint8_t>	   Tag(AesGcm::TagSize);
		std::optional<std::string> Reason;

		MemoryView CipherView = AesGcm::Encrypt(Key,
												Nonce,
												/*Aad*/ {},
												MakeMemoryView(Plain),
												MakeMutableMemoryView(Cipher),
												MakeMutableMemoryView(Tag),
												Reason);
		REQUIRE(!Reason.has_value());
		CHECK_EQ(CipherView.GetSize(), Plain.size());

		std::vector<uint8_t> Decoded(Plain.size());
		MemoryView			 DecodedView =
			AesGcm::Decrypt(Key, Nonce, /*Aad*/ {}, CipherView, MakeMemoryView(Tag), MakeMutableMemoryView(Decoded), Reason);
		REQUIRE(!Reason.has_value());
		CHECK_EQ(DecodedView.GetSize(), Plain.size());

		std::string_view DecodedText(reinterpret_cast<const char*>(DecodedView.GetData()), DecodedView.GetSize());
		CHECK_EQ(DecodedText, Plain);
	}

	SUBCASE("round trip with AAD")
	{
		std::string_view Plain = "payload"sv;
		std::string_view Aad   = "header bits that are authenticated but not encrypted"sv;

		std::vector<uint8_t>	   Cipher(Plain.size());
		std::vector<uint8_t>	   Tag(AesGcm::TagSize);
		std::optional<std::string> Reason;

		MemoryView CipherView = AesGcm::Encrypt(Key,
												Nonce,
												MakeMemoryView(Aad),
												MakeMemoryView(Plain),
												MakeMutableMemoryView(Cipher),
												MakeMutableMemoryView(Tag),
												Reason);
		REQUIRE(!Reason.has_value());

		std::vector<uint8_t> Decoded(Plain.size());
		MemoryView			 DecodedView =
			AesGcm::Decrypt(Key, Nonce, MakeMemoryView(Aad), CipherView, MakeMemoryView(Tag), MakeMutableMemoryView(Decoded), Reason);
		REQUIRE(!Reason.has_value());
		CHECK_EQ(DecodedView.GetSize(), Plain.size());
	}

	SUBCASE("tampered ciphertext fails authentication")
	{
		std::string_view Plain = "important"sv;

		std::vector<uint8_t>	   Cipher(Plain.size());
		std::vector<uint8_t>	   Tag(AesGcm::TagSize);
		std::optional<std::string> Reason;

		MemoryView CipherView = AesGcm::Encrypt(Key,
												Nonce,
												/*Aad*/ {},
												MakeMemoryView(Plain),
												MakeMutableMemoryView(Cipher),
												MakeMutableMemoryView(Tag),
												Reason);
		REQUIRE(!Reason.has_value());

		// Flip a bit in the ciphertext.
		Cipher[0] ^= 0x01;

		std::vector<uint8_t> Decoded(Plain.size());
		MemoryView			 DecodedView =
			AesGcm::Decrypt(Key, Nonce, /*Aad*/ {}, CipherView, MakeMemoryView(Tag), MakeMutableMemoryView(Decoded), Reason);
		CHECK(Reason.has_value());
		CHECK(DecodedView.IsEmpty());
	}

	SUBCASE("tampered tag fails authentication")
	{
		std::string_view Plain = "important"sv;

		std::vector<uint8_t>	   Cipher(Plain.size());
		std::vector<uint8_t>	   Tag(AesGcm::TagSize);
		std::optional<std::string> Reason;

		MemoryView CipherView = AesGcm::Encrypt(Key,
												Nonce,
												/*Aad*/ {},
												MakeMemoryView(Plain),
												MakeMutableMemoryView(Cipher),
												MakeMutableMemoryView(Tag),
												Reason);
		REQUIRE(!Reason.has_value());

		Tag[0] ^= 0x80;

		std::vector<uint8_t> Decoded(Plain.size());
		MemoryView			 DecodedView =
			AesGcm::Decrypt(Key, Nonce, /*Aad*/ {}, CipherView, MakeMemoryView(Tag), MakeMutableMemoryView(Decoded), Reason);
		CHECK(Reason.has_value());
		CHECK(DecodedView.IsEmpty());
	}

	SUBCASE("AAD mismatch fails authentication")
	{
		std::string_view Plain = "payload"sv;
		std::string_view AadOk = "expected header"sv;
		std::string_view AadNo = "different header"sv;

		std::vector<uint8_t>	   Cipher(Plain.size());
		std::vector<uint8_t>	   Tag(AesGcm::TagSize);
		std::optional<std::string> Reason;

		MemoryView CipherView = AesGcm::Encrypt(Key,
												Nonce,
												MakeMemoryView(AadOk),
												MakeMemoryView(Plain),
												MakeMutableMemoryView(Cipher),
												MakeMutableMemoryView(Tag),
												Reason);
		REQUIRE(!Reason.has_value());

		std::vector<uint8_t> Decoded(Plain.size());
		MemoryView			 DecodedView =
			AesGcm::Decrypt(Key, Nonce, MakeMemoryView(AadNo), CipherView, MakeMemoryView(Tag), MakeMutableMemoryView(Decoded), Reason);
		CHECK(Reason.has_value());
		CHECK(DecodedView.IsEmpty());
	}

	SUBCASE("wrong nonce size is rejected")
	{
		std::string_view Plain = "x"sv;

		const uint8_t			   TooShort[8] = {0};
		std::vector<uint8_t>	   Cipher(Plain.size());
		std::vector<uint8_t>	   Tag(AesGcm::TagSize);
		std::optional<std::string> Reason;

		MemoryView CipherView = AesGcm::Encrypt(Key,
												MakeMemoryView(TooShort),
												/*Aad*/ {},
												MakeMemoryView(Plain),
												MakeMutableMemoryView(Cipher),
												MakeMutableMemoryView(Tag),
												Reason);
		CHECK(Reason.has_value());
		CHECK(CipherView.IsEmpty());
	}
}

TEST_CASE("crypto.random")
{
	SUBCASE("fills buffer with non-zero bytes")
	{
		uint8_t			  Buffer[32] = {};
		MutableMemoryView View		 = MakeMutableMemoryView(Buffer);
		const bool		  Ok		 = CryptoRandom::Fill(View);
		REQUIRE(Ok);

		// Probability of 32 all-zero bytes from a CSPRNG is 2^-256 — we
		// accept it as "effectively never".
		bool AnyNonZero = false;
		for (uint8_t B : Buffer)
		{
			if (B != 0)
			{
				AnyNonZero = true;
				break;
			}
		}
		CHECK(AnyNonZero);
	}

	SUBCASE("two calls produce different output")
	{
		uint8_t A[32] = {};
		uint8_t B[32] = {};
		CHECK(CryptoRandom::Fill(MakeMutableMemoryView(A)));
		CHECK(CryptoRandom::Fill(MakeMutableMemoryView(B)));
		CHECK(memcmp(A, B, 32) != 0);
	}

	SUBCASE("zero-size buffer is a no-op success")
	{
		uint8_t Dummy = 0xAB;
		CHECK(CryptoRandom::Fill(MutableMemoryView(&Dummy, size_t{0})));
		CHECK_EQ(Dummy, 0xAB);
	}
}

TEST_CASE("crypto.securerandom")
{
	std::array<uint8_t, 64> A{};
	std::array<uint8_t, 64> B{};
	CHECK(SecureRandomBytes(MutableMemoryView(A.data(), A.size())));
	CHECK(SecureRandomBytes(MutableMemoryView(B.data(), B.size())));
	// Vanishingly small probability two 64-byte draws match.
	CHECK(A != B);
}

TEST_CASE("crypto.protectdata")
{
	const uint8_t		 Plain[48] = {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};
	std::vector<uint8_t> Wrapped;
	const bool			 WrapOk = TryProtectData(MakeMemoryView(Plain), Wrapped);
#	if ZEN_PLATFORM_WINDOWS
	REQUIRE(WrapOk);
	CHECK(Wrapped.size() != sizeof(Plain));	 // DPAPI envelope adds overhead
	CHECK(memcmp(Wrapped.data(), Plain, std::min(Wrapped.size(), sizeof(Plain))) != 0);

	std::vector<uint8_t> Unwrapped;
	REQUIRE(TryUnprotectData(MakeMemoryView(Wrapped), Unwrapped));
	CHECK(Unwrapped.size() == sizeof(Plain));
	CHECK(memcmp(Unwrapped.data(), Plain, sizeof(Plain)) == 0);
#	elif ZEN_PLATFORM_MAC
	// Keychain may not be accessible in headless / CI contexts. Round-trip is
	// asserted only when Wrap succeeds; otherwise the test is a no-op.
	if (WrapOk)
	{
		CHECK(Wrapped.size() == 16);  // Keychain account id
		std::vector<uint8_t> Unwrapped;
		REQUIRE(TryUnprotectData(MakeMemoryView(Wrapped), Unwrapped));
		CHECK(Unwrapped.size() == sizeof(Plain));
		CHECK(memcmp(Unwrapped.data(), Plain, sizeof(Plain)) == 0);

		// Delete the Keychain entry we just added so tests don't accumulate residue.
		static const char kHex[] = "0123456789abcdef";
		char			  AccountHex[33];
		for (size_t i = 0; i < 16; ++i)
		{
			AccountHex[i * 2]	  = kHex[Wrapped[i] >> 4];
			AccountHex[i * 2 + 1] = kHex[Wrapped[i] & 0x0F];
		}
		AccountHex[32]			 = '\0';
		CFStringRef		Account	 = CFStringCreateWithCString(nullptr, AccountHex, kCFStringEncodingASCII);
		const void*		Keys[]	 = {kSecClass, kSecAttrService, kSecAttrAccount};
		const void*		Values[] = {kSecClassGenericPassword, CFSTR("org.unrealengine.zen.auth"), Account};
		CFDictionaryRef Query =
			CFDictionaryCreate(nullptr, Keys, Values, 3, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
		SecItemDelete(Query);
		CFRelease(Query);
		CFRelease(Account);
	}
#	elif ZEN_PLATFORM_LINUX && ZEN_USE_LIBSECRET
	// libsecret round-trip only when a Secret Service daemon is reachable. On
	// headless / container CI with no D-Bus session, WrapOk is false and we fall
	// back to the raw-bytes path at the authutils level, so the test is a no-op.
	if (WrapOk)
	{
		CHECK(Wrapped.size() == 16);
		std::vector<uint8_t> Unwrapped;
		REQUIRE(TryUnprotectData(MakeMemoryView(Wrapped), Unwrapped));
		CHECK(Unwrapped.size() == sizeof(Plain));
		CHECK(memcmp(Unwrapped.data(), Plain, sizeof(Plain)) == 0);

		// Clean up the keyring entry we just created.
		static const char kHex[] = "0123456789abcdef";
		char			  AccountHex[33];
		for (size_t i = 0; i < 16; ++i)
		{
			AccountHex[i * 2]	  = kHex[Wrapped[i] >> 4];
			AccountHex[i * 2 + 1] = kHex[Wrapped[i] & 0x0F];
		}
		AccountHex[32] = '\0';
		GError* Err	   = nullptr;
		secret_password_clear_sync(ZenAuthSchema(), nullptr, &Err, "account", AccountHex, nullptr);
		if (Err != nullptr)
		{
			g_error_free(Err);
		}
	}
#	else
	// No OS-level implementation compiled in; both calls must report failure.
	CHECK(WrapOk == false);
	std::vector<uint8_t> Unwrapped;
	CHECK(TryUnprotectData(MakeMemoryView(Plain), Unwrapped) == false);
#	endif
}

TEST_SUITE_END();

#endif

}  // namespace zen