gmcrypto-c 1.9.0

C ABI for gmcrypto-core — cdylib + staticlib exposing SM2/SM3/SM4/HMAC/PBKDF2 to C / C++ / Python / Go / Zig callers via opaque handles
Documentation
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
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
/*
 * gmcrypto-c — C ABI for gmcrypto-core (pure-Rust SM2/SM3/SM4 SDK).
 *
 * AUTO-GENERATED by cbindgen. DO NOT EDIT BY HAND.
 * Regenerate via: cargo build -p gmcrypto-c --features regen-header
 *
 * Failure-mode invariant (v0.4 W4 / Q4.8 of docs/v0.4-scope.md):
 * every int return is 0 on success, non-zero on failure. Non-zero
 * codes are NOT enumerated — they are equivalent `Failed` per the
 * crate's failure-mode discipline.
 *
 * Pointer / length preconditions (caller-upheld — violating them is
 * undefined behavior, NOT a GMCRYPTO_ERR): every non-null pointer argument
 * must point to at least the stated number of bytes (e.g. a key pointer to
 * its KEY_SIZE, an iv to 16 bytes), each *_len must not exceed the real
 * allocation, and out/out_capacity pairs must describe a writable buffer of
 * at least out_capacity bytes. A null pointer is reported as GMCRYPTO_ERR;
 * an out-of-bounds or mis-sized non-null pointer is undefined behavior.
 */

#ifndef GMCRYPTO_H_
#define GMCRYPTO_H_

/* Warning: this file is auto-generated by cbindgen; do not edit. */

#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdint.h>

/*
 * Output-buffer size required by gmcrypto_sm4_cbc_encrypt() for a plaintext of
 * `pt_len` bytes: PKCS#7 always appends a full padding block, so the size is
 * ((pt_len / 16) + 1) * 16. The caller must ensure this does not overflow
 * size_t.
 */
#define GMCRYPTO_SM4_CBC_OUTPUT_SIZE(pt_len) ((((size_t)(pt_len) / 16u) + 1u) * 16u)

/*
 * Best-effort secret scrub: overwrite `len` bytes at `ptr` with zeros through a
 * volatile pointer the compiler may not optimize away. Evaluates `ptr` and
 * `len` exactly once. Prefer a platform secure-zero (memset_s / explicit_bzero
 * / SecureZeroMemory) where one is available.
 */
#define GMCRYPTO_ZEROIZE(ptr, len) \
    do { \
        volatile unsigned char *gmcrypto_zptr_ = (volatile unsigned char *)(ptr); \
        size_t gmcrypto_zlen_ = (size_t)(len); \
        while (gmcrypto_zlen_ != 0u) { *gmcrypto_zptr_++ = 0u; gmcrypto_zlen_--; } \
    } while (0)


/*
 Success return code.
 */
#define GMCRYPTO_OK 0

/*
 Generic failure return code. All non-zero returns are equivalent
 per the failure-mode invariant; this constant exists only as a
 convenience for C callers that want a named symbol for the
 not-success case.
 */
#define GMCRYPTO_ERR -1

/*
 SM3 digest output size in bytes (32 = 256 bits).
 */
#define GMCRYPTO_SM3_DIGEST_SIZE 32

/*
 SM4 block size in bytes (16 = 128 bits).
 */
#define GMCRYPTO_SM4_BLOCK_SIZE 16

/*
 SM4 key size in bytes (16 = 128 bits).
 */
#define GMCRYPTO_SM4_KEY_SIZE 16

/*
 SM4-XTS key size in bytes (32 = `Key1 ‖ Key2`, two 128-bit keys).
 */
#define GMCRYPTO_SM4_XTS_KEY_SIZE (2 * GMCRYPTO_SM4_KEY_SIZE)

/*
 SEC1 uncompressed-point size for SM2 public keys
 (`04 || X || Y` = 65 bytes).
 */
#define GMCRYPTO_SM2_SEC1_UNCOMPRESSED_SIZE 65

/*
 SM2 private-key scalar size in bytes (32 = 256 bits big-endian).
 */
#define GMCRYPTO_SM2_SCALAR_SIZE 32

/*
 SM2 key-exchange confirmation-tag size in bytes (`S_A` / `S_B` are
 SM3 digests; v1.2). Ephemeral points `R_A` / `R_B` use
 [`GMCRYPTO_SM2_SEC1_UNCOMPRESSED_SIZE`] (65).
 */
#define GMCRYPTO_SM2_KX_CONFIRM_SIZE 32

/*
 TLCP master-secret length (bytes).
 */
#define GMCRYPTO_TLCP_MASTER_SECRET_LEN 48

/*
 TLCP Finished `verify_data` length (bytes).
 */
#define GMCRYPTO_TLCP_FINISHED_VERIFY_DATA_LEN 12

/*
 SM4-CBC record key-block length (bytes) for `gmcrypto_tlcp_record_keys_cbc_new`.
 */
#define GMCRYPTO_TLCP_CBC_KEY_BLOCK_LEN 128

/*
 SM4-GCM record key-block length (bytes) for `gmcrypto_tlcp_record_keys_gcm_new`.
 */
#define GMCRYPTO_TLCP_GCM_KEY_BLOCK_LEN 40

/*
 Maximum chain length `gmcrypto_x509_verify_chain` accepts.
 */
#define GMCRYPTO_X509_MAX_CHAIN_DEPTH 8

/*
 TLCP record version major byte (`0x01`). `version` is a caller parameter on
 every protect/deprotect call; these constants are a convenience.
 */
#define GMCRYPTO_TLCP_RECORD_VERSION_MAJOR 1

/*
 TLCP record version minor byte (`0x01`).
 */
#define GMCRYPTO_TLCP_RECORD_VERSION_MINOR 1

/*
 Opaque handle for a streaming HMAC-SM3 keyed MAC.
 */
typedef struct gmcrypto_hmac_sm3_t gmcrypto_hmac_sm3_t;

/*
 Opaque handle for an SM2 key-exchange INITIATOR (party A; GM/T
 0003.3, v1.2). Born already awaiting the responder's reply —
 [`gmcrypto_sm2_kx_initiator_new`] samples the ephemeral internally
 and writes `R_A` immediately, so no pre-ephemeral state exists in
 C. Pair with exactly one [`gmcrypto_sm2_kx_initiator_confirm`]
 (which consumes + frees) **or** one
 [`gmcrypto_sm2_kx_initiator_free`].
 */
typedef struct gmcrypto_sm2_kx_initiator_t gmcrypto_sm2_kx_initiator_t;

/*
 Opaque handle for an SM2 key-exchange RESPONDER (party B; GM/T
 0003.3, v1.2). Lifecycle: [`gmcrypto_sm2_kx_responder_new`] →
 [`gmcrypto_sm2_kx_responder_respond`] (takes `R_A`, emits
 `R_B` + `S_B`) → [`gmcrypto_sm2_kx_responder_finish`] (takes
 `S_A`, releases `K`, consumes + frees). Pair with exactly one
 `_finish` **or** one [`gmcrypto_sm2_kx_responder_free`].
 */
typedef struct gmcrypto_sm2_kx_responder_t gmcrypto_sm2_kx_responder_t;

/*
 Opaque handle for an SM2 private key.
 */
typedef struct gmcrypto_sm2_privkey_t gmcrypto_sm2_privkey_t;

/*
 Opaque handle for an SM2 public key.
 */
typedef struct gmcrypto_sm2_pubkey_t gmcrypto_sm2_pubkey_t;

/*
 Opaque handle for a streaming SM3 hasher.
 */
typedef struct gmcrypto_sm3_t gmcrypto_sm3_t;

/*
 Opaque handle for a streaming SM4-CBC decryptor (v0.5 W1). Same
 buffer-back-by-one padding-oracle defense as the v0.3 W5 Rust
 streaming surface: the most recent decrypted block is held back
 from emission until [`gmcrypto_sm4_cbc_decryptor_finalize`]
 confirms it is the last block and validates the PKCS#7 padding.
 */
typedef struct gmcrypto_sm4_cbc_decryptor_t gmcrypto_sm4_cbc_decryptor_t;

/*
 Opaque handle for a streaming SM4-CBC encryptor (v0.5 W1).
 Construct with [`gmcrypto_sm4_cbc_encryptor_new`], feed plaintext via
 [`gmcrypto_sm4_cbc_encryptor_update`], emit the trailing PKCS#7-
 padded block(s) via [`gmcrypto_sm4_cbc_encryptor_finalize`].
 */
typedef struct gmcrypto_sm4_cbc_encryptor_t gmcrypto_sm4_cbc_encryptor_t;

/*
 Opaque handle for a streaming (incremental-input, output-BUFFERED)
 SM4-GCM decryptor (v0.10 W2). Commit-on-verify:
 [`gmcrypto_sm4_gcm_decryptor_update`] buffers ciphertext and emits
 **nothing**; [`gmcrypto_sm4_gcm_decryptor_finalize_verify`] releases
 the full plaintext only after a constant-time tag check. Memory is
 `O(message)`. Construct with [`gmcrypto_sm4_gcm_decryptor_new`].
 */
typedef struct gmcrypto_sm4_gcm_decryptor_t gmcrypto_sm4_gcm_decryptor_t;

/*
 Opaque handle for a streaming (incremental-input) SM4-GCM encryptor
 (v0.10 W1). Output-streaming: each
 [`gmcrypto_sm4_gcm_encryptor_update`] emits the ciphertext for its
 chunk; [`gmcrypto_sm4_gcm_encryptor_finalize`] emits the 16-byte tag.
 Construct with [`gmcrypto_sm4_gcm_encryptor_new`]; pair with exactly
 one finalize (which frees the handle) **or** one
 [`gmcrypto_sm4_gcm_encryptor_free`].
 */
typedef struct gmcrypto_sm4_gcm_encryptor_t gmcrypto_sm4_gcm_encryptor_t;

/*
 Opaque handle for an SM4 cipher (key-scheduled).
 */
typedef struct gmcrypto_sm4_t gmcrypto_sm4_t;

/*
 Opaque per-direction SM4-CBC record key carrier (`ZeroizeOnDrop`). Build with
 [`gmcrypto_tlcp_record_keys_cbc_new`]; free + wipe with
 [`gmcrypto_tlcp_record_keys_cbc_free`]. Immutable — protect/deprotect borrow
 it.
 */
typedef struct gmcrypto_tlcp_record_keys_cbc_t gmcrypto_tlcp_record_keys_cbc_t;

/*
 Opaque per-direction SM4-GCM record key carrier (`ZeroizeOnDrop`).
 */
typedef struct gmcrypto_tlcp_record_keys_gcm_t gmcrypto_tlcp_record_keys_gcm_t;

/*
 Opaque X.509 certificate handle (v1.4). Immutable after construction —
 every accessor takes `const *`; free with
 [`gmcrypto_x509_certificate_free`].
 */
typedef struct gmcrypto_x509_certificate_t gmcrypto_x509_certificate_t;

/*
 C ABI function pointer for caller-supplied RNG. Returns `0` on
 success and non-zero on failure. See module-level docs for the
 full contract.
 */
typedef int (*gmcrypto_rng_callback)(void *context, uint8_t *buf, uintptr_t buf_len);

/*
 A certificate validity timestamp — plain calendar fields, mirroring the
 Rust `X509Time` exactly (Zulu-only at parse). **This library has no
 clock**: comparing these to "now" (the actual validity decision) is the
 caller's call.
 */
typedef struct {
  /*
   Full year (the UTCTime 1950/2050 pivot is already applied at parse).
   */
  uint16_t year;
  /*
   Month, 1–12.
   */
  uint8_t month;
  /*
   Day of month, 1–31.
   */
  uint8_t day;
  /*
   Hour, 0–23.
   */
  uint8_t hour;
  /*
   Minute, 0–59.
   */
  uint8_t minute;
  /*
   Second, 0–59.
   */
  uint8_t second;
} gmcrypto_x509_time_t;

/*
 Returns a NUL-terminated string with the `gmcrypto-c` crate version,
 tracking Cargo's `CARGO_PKG_VERSION` at build time (e.g. `"1.0.0"`).
 The returned pointer is to a static `&'static CStr` and must NOT be
 freed by the caller.
 */
 const char *gmcrypto_version(void) ;

/*
 Single-shot SM3 hash. Writes 32 bytes to `out_digest`.

 # Returns
 [`GMCRYPTO_OK`] on success; [`GMCRYPTO_ERR`] on invalid input
 (null `out_digest`, null `msg` with non-zero `msg_len`).
 */
 int gmcrypto_sm3_hash(const uint8_t *msg, uintptr_t msg_len, uint8_t *out_digest) ;

/*
 Construct a fresh streaming SM3 hasher. Returns an opaque handle;
 must be freed via [`gmcrypto_sm3_free`].

 Never returns NULL: construction is infallible apart from heap allocation,
 and allocation failure aborts the process via Rust's global allocator
 (it does not — and cannot, on stable Rust — return NULL here).
 */
 gmcrypto_sm3_t *gmcrypto_sm3_new(void) ;

/*
 Absorb `data` into the streaming SM3 hasher.
 */
 int gmcrypto_sm3_update(gmcrypto_sm3_t *hasher, const uint8_t *data, uintptr_t data_len) ;

/*
 Consume the streaming SM3 hasher and write the digest to
 `out_digest`. The handle is **freed** by this call; do not call
 [`gmcrypto_sm3_free`] on it afterwards.
 */
 int gmcrypto_sm3_finalize(gmcrypto_sm3_t *hasher, uint8_t *out_digest) ;

/*
 Free a streaming SM3 hasher. Passing NULL is a no-op.
 */
 void gmcrypto_sm3_free(gmcrypto_sm3_t *hasher) ;

/*
 Single-shot HMAC-SM3. Writes 32 bytes to `out_tag`.
 */

int gmcrypto_hmac_sm3(const uint8_t *key,
                      uintptr_t key_len,
                      const uint8_t *msg,
                      uintptr_t msg_len,
                      uint8_t *out_tag)
;

/*
 Construct a fresh streaming HMAC-SM3 instance keyed with `key`.
 Returns NULL on invalid input.
 */
 gmcrypto_hmac_sm3_t *gmcrypto_hmac_sm3_new(const uint8_t *key, uintptr_t key_len) ;

/*
 Absorb `data` into the streaming HMAC-SM3 instance.
 */
 int gmcrypto_hmac_sm3_update(gmcrypto_hmac_sm3_t *mac, const uint8_t *data, uintptr_t data_len) ;

/*
 Consume the streaming HMAC-SM3 instance and write the 32-byte tag
 to `out_tag`. The handle is **freed** by this call.
 */
 int gmcrypto_hmac_sm3_finalize(gmcrypto_hmac_sm3_t *mac, uint8_t *out_tag) ;

/*
 Consume the streaming HMAC-SM3 instance and verify the candidate
 tag in constant time. Returns [`GMCRYPTO_OK`] on match;
 [`GMCRYPTO_ERR`] on mismatch. The handle is **freed** by this call.
 */
 int gmcrypto_hmac_sm3_verify(gmcrypto_hmac_sm3_t *mac, const uint8_t *expected_tag) ;

/*
 Free a streaming HMAC-SM3 instance. NULL is a no-op.
 */
 void gmcrypto_hmac_sm3_free(gmcrypto_hmac_sm3_t *mac) ;

/*
 Derive `out_len` bytes via PBKDF2-HMAC-SM3 over `(pwd, salt,
 iterations)`. Writes into the caller-supplied `out` buffer.
 */

int gmcrypto_pbkdf2_hmac_sm3(const uint8_t *pwd,
                             uintptr_t pwd_len,
                             const uint8_t *salt,
                             uintptr_t salt_len,
                             uint32_t iterations,
                             uint8_t *out,
                             uintptr_t out_len)
;

/*
 Construct an SM4 cipher from a 16-byte key. Returns NULL on null
 key.
 */
 gmcrypto_sm4_t *gmcrypto_sm4_new(const uint8_t *key) ;

/*
 Encrypt one 16-byte block in place under the SM4 cipher.

 WARNING: this is the raw SM4 block, not a cipher mode. Calling it in a
 loop over a multi-block buffer is ECB — it leaks plaintext-block equality
 and has no semantic security. To encrypt messages use a mode
 (`gmcrypto_sm4_gcm_*` / `_ccm_*` authenticated; or `_cbc_*` / `_ctr_*` /
 `_xts_*` confidentiality-only with a unique IV/nonce/tweak).
 */
 int gmcrypto_sm4_encrypt_block(const gmcrypto_sm4_t *cipher, uint8_t *block) ;

/*
 Decrypt one 16-byte block in place under the SM4 cipher.

 WARNING: raw SM4 block, not a cipher mode (see
 `gmcrypto_sm4_encrypt_block`). Looping it over a buffer is ECB
 decryption — no semantic security, no authentication. Decrypt real
 messages with a mode.
 */
 int gmcrypto_sm4_decrypt_block(const gmcrypto_sm4_t *cipher, uint8_t *block) ;

/*
 Free an SM4 cipher. NULL is a no-op.
 */
 void gmcrypto_sm4_free(gmcrypto_sm4_t *cipher) ;

/*
 SM4-CBC single-shot encrypt with PKCS#7 padding. IV must be
 caller-supplied and unpredictable (per NIST SP 800-38A
 Appendix C). Output length is always `((pt_len / 16) + 1) * 16`.
 */

int gmcrypto_sm4_cbc_encrypt(const uint8_t *key,
                             const uint8_t *iv,
                             const uint8_t *pt,
                             uintptr_t pt_len,
                             uint8_t *out,
                             uintptr_t out_capacity,
                             uintptr_t *out_actual_len)
;

/*
 SM4-CBC single-shot decrypt. Single-`Failed` return on any
 failure mode (length not multiple of 16, bad padding, key/IV
 mismatch) per the failure-mode invariant.
 */

int gmcrypto_sm4_cbc_decrypt(const uint8_t *key,
                             const uint8_t *iv,
                             const uint8_t *ct,
                             uintptr_t ct_len,
                             uint8_t *out,
                             uintptr_t out_capacity,
                             uintptr_t *out_actual_len)
;

/*
 Construct a streaming SM4-CBC encryptor. `key` is exactly 16
 bytes; `iv` is exactly 16 bytes and MUST be caller-supplied
 unpredictable bytes (NIST SP 800-38A Appendix C). Returns NULL
 on invalid pointer input.
 */

gmcrypto_sm4_cbc_encryptor_t *gmcrypto_sm4_cbc_encryptor_new(const uint8_t *key,
                                                             const uint8_t *iv)
;

/*
 Absorb plaintext into the streaming SM4-CBC encryptor and emit
 zero or more full ciphertext blocks. The caller-allocated `out`
 buffer MUST be at least `pt_len + 16` bytes — that is the upper
 bound on bytes emitted by a single `_update` call (a buffered
 partial block from a prior call can produce one extra block when
 this call's input fills it). On insufficient capacity, the call
 returns [`GMCRYPTO_ERR`] and the encryptor state is left mid-
 stream (the ciphertext bytes that would have been emitted are
 lost). Callers should size the output buffer correctly up-front.
 */

int gmcrypto_sm4_cbc_encryptor_update(gmcrypto_sm4_cbc_encryptor_t *enc,
                                      const uint8_t *pt,
                                      uintptr_t pt_len,
                                      uint8_t *out,
                                      uintptr_t out_capacity,
                                      uintptr_t *out_actual_len)
;

/*
 Apply PKCS#7 padding to the buffered tail and emit the final
 ciphertext block(s). Consumes the encryptor — the handle is
 **freed** by this call; do NOT call
 [`gmcrypto_sm4_cbc_encryptor_free`] on it afterwards.

 Output is always exactly one block (16 bytes).
 */

int gmcrypto_sm4_cbc_encryptor_finalize(gmcrypto_sm4_cbc_encryptor_t *enc,
                                        uint8_t *out,
                                        uintptr_t out_capacity,
                                        uintptr_t *out_actual_len)
;

/*
 Free a streaming SM4-CBC encryptor. Passing NULL is a no-op. Do
 NOT call after [`gmcrypto_sm4_cbc_encryptor_finalize`] — that
 already consumed the handle.
 */
 void gmcrypto_sm4_cbc_encryptor_free(gmcrypto_sm4_cbc_encryptor_t *enc) ;

/*
 Construct a streaming SM4-CBC decryptor. `key` is exactly 16
 bytes; `iv` is exactly 16 bytes and must match the value used
 during encryption. Returns NULL on invalid pointer input.
 */

gmcrypto_sm4_cbc_decryptor_t *gmcrypto_sm4_cbc_decryptor_new(const uint8_t *key,
                                                             const uint8_t *iv)
;

/*
 Absorb ciphertext into the streaming SM4-CBC decryptor and emit
 zero or more full plaintext blocks. The final-candidate block is
 HELD BACK from emission until `_finalize` validates the trailing
 padding (buffer-back-by-one padding-oracle defense). Same buffer-
 size contract as the encryptor's `_update`: caller MUST allocate
 `out_capacity >= ct_len + 16` (strict upper bound on bytes emitted
 in one call). On insufficient capacity returns [`GMCRYPTO_ERR`]
 and the decryptor state is left mid-stream; size the buffer
 up-front.
 */

int gmcrypto_sm4_cbc_decryptor_update(gmcrypto_sm4_cbc_decryptor_t *dec,
                                      const uint8_t *ct,
                                      uintptr_t ct_len,
                                      uint8_t *out,
                                      uintptr_t out_capacity,
                                      uintptr_t *out_actual_len)
;

/*
 Strip PKCS#7 padding from the held-back final block and emit the
 last plaintext bytes. Consumes the decryptor — the handle is
 **freed** by this call; do NOT call
 [`gmcrypto_sm4_cbc_decryptor_free`] on it afterwards.

 Returns [`GMCRYPTO_ERR`] on any failure mode (length not multiple
 of 16, no full blocks seen, or padding-strip rejection) — single
 uninformative failure code per the failure-mode invariant. The
 caller-supplied `out_actual_len` is set to `0` on failure.
 */

int gmcrypto_sm4_cbc_decryptor_finalize(gmcrypto_sm4_cbc_decryptor_t *dec,
                                        uint8_t *out,
                                        uintptr_t out_capacity,
                                        uintptr_t *out_actual_len)
;

/*
 Free a streaming SM4-CBC decryptor. Passing NULL is a no-op. Do
 NOT call after [`gmcrypto_sm4_cbc_decryptor_finalize`] — that
 already consumed the handle.
 */
 void gmcrypto_sm4_cbc_decryptor_free(gmcrypto_sm4_cbc_decryptor_t *dec) ;

/*
 SM4-GCM single-shot encrypt. `ct_out` receives `pt_len` bytes (via
 the capacity/actual-len convention); `tag_out` receives exactly 16
 bytes. Returns [`GMCRYPTO_OK`] / [`GMCRYPTO_ERR`].
 */

int gmcrypto_sm4_gcm_encrypt(const uint8_t *key,
                             const uint8_t *nonce,
                             uintptr_t nonce_len,
                             const uint8_t *aad,
                             uintptr_t aad_len,
                             const uint8_t *pt,
                             uintptr_t pt_len,
                             uint8_t *ct_out,
                             uintptr_t ct_capacity,
                             uintptr_t *ct_actual_len,
                             uint8_t *tag_out)
;

/*
 SM4-GCM single-shot decrypt with a 16-byte tag. `pt_out` receives
 `ct_len` bytes. Returns [`GMCRYPTO_OK`] only if the tag verifies;
 [`GMCRYPTO_ERR`] on any failure (single failure mode).
 */

int gmcrypto_sm4_gcm_decrypt(const uint8_t *key,
                             const uint8_t *nonce,
                             uintptr_t nonce_len,
                             const uint8_t *aad,
                             uintptr_t aad_len,
                             const uint8_t *ct,
                             uintptr_t ct_len,
                             const uint8_t *tag,
                             uint8_t *pt_out,
                             uintptr_t pt_capacity,
                             uintptr_t *pt_actual_len)
;

/*
 SM4-GCM encrypt with a truncated tag. `tag_len` must be in
 `{4, 8, 12, 13, 14, 15, 16}`; `tag_out` receives `tag_len` bytes.
 Invalid `tag_len` → [`GMCRYPTO_ERR`].
 */

int gmcrypto_sm4_gcm_encrypt_with_tag_len(const uint8_t *key,
                                          const uint8_t *nonce,
                                          uintptr_t nonce_len,
                                          const uint8_t *aad,
                                          uintptr_t aad_len,
                                          const uint8_t *pt,
                                          uintptr_t pt_len,
                                          uintptr_t tag_len,
                                          uint8_t *ct_out,
                                          uintptr_t ct_capacity,
                                          uintptr_t *ct_actual_len,
                                          uint8_t *tag_out)
;

/*
 SM4-GCM decrypt with a truncated tag. `tag` is `tag_len` bytes;
 `tag_len` must be in `{4, 8, 12, 13, 14, 15, 16}`. `pt_out`
 receives `ct_len` bytes. [`GMCRYPTO_ERR`] on any failure.
 */

int gmcrypto_sm4_gcm_decrypt_with_tag_len(const uint8_t *key,
                                          const uint8_t *nonce,
                                          uintptr_t nonce_len,
                                          const uint8_t *aad,
                                          uintptr_t aad_len,
                                          const uint8_t *ct,
                                          uintptr_t ct_len,
                                          const uint8_t *tag,
                                          uintptr_t tag_len,
                                          uint8_t *pt_out,
                                          uintptr_t pt_capacity,
                                          uintptr_t *pt_actual_len)
;

/*
 SM4-CCM single-shot encrypt. `tag_len` must be in
 `{4, 6, 8, 10, 12, 14, 16}`; `nonce_len` in `[7, 13]`. `out`
 receives `pt_len + tag_len` bytes (`ciphertext ‖ tag`). Invalid
 parameters → [`GMCRYPTO_ERR`].
 */

int gmcrypto_sm4_ccm_encrypt(const uint8_t *key,
                             const uint8_t *nonce,
                             uintptr_t nonce_len,
                             const uint8_t *aad,
                             uintptr_t aad_len,
                             const uint8_t *pt,
                             uintptr_t pt_len,
                             uintptr_t tag_len,
                             uint8_t *out,
                             uintptr_t out_capacity,
                             uintptr_t *out_actual_len)
;

/*
 SM4-CCM single-shot decrypt. Input `ct` is `ct_len` bytes
 (`ciphertext ‖ tag`); `tag_len` must match the value used at
 encrypt time. `pt_out` receives `ct_len - tag_len` bytes.
 [`GMCRYPTO_ERR`] on any failure (single failure mode).
 */

int gmcrypto_sm4_ccm_decrypt(const uint8_t *key,
                             const uint8_t *nonce,
                             uintptr_t nonce_len,
                             const uint8_t *aad,
                             uintptr_t aad_len,
                             const uint8_t *ct,
                             uintptr_t ct_len,
                             uintptr_t tag_len,
                             uint8_t *pt_out,
                             uintptr_t pt_capacity,
                             uintptr_t *pt_actual_len)
;

/*
 SM4-XTS single-shot encrypt (GB/T 17964-2021, `xts_standard=GB`).
 `key` is exactly [`GMCRYPTO_SM4_XTS_KEY_SIZE`] (32) bytes (`Key1 ‖
 Key2`); `tweak` is exactly [`GMCRYPTO_SM4_BLOCK_SIZE`] (16) raw bytes
 (the data-unit/sector identifier — caller-unique per key). `out`
 receives `data_len` bytes (length-preserving) via the
 capacity/actual-len convention. Returns [`GMCRYPTO_OK`] /
 [`GMCRYPTO_ERR`] (single failure mode: `data_len` outside
 `[16, 16 MiB]`, `Key1 == Key2`, null pointer, or buffer too small —
 in which case `*out_actual_len` is set to the required length).
 **Confidentiality only — SM4-XTS does not authenticate.**
 */

int gmcrypto_sm4_xts_encrypt(const uint8_t *key,
                             const uint8_t *tweak,
                             const uint8_t *data,
                             uintptr_t data_len,
                             uint8_t *out,
                             uintptr_t out_capacity,
                             uintptr_t *out_actual_len)
;

/*
 SM4-XTS single-shot decrypt (GB/T 17964-2021, `xts_standard=GB`).
 Inverse of [`gmcrypto_sm4_xts_encrypt`] with the same argument shape;
 `out` receives `data_len` bytes. Returns [`GMCRYPTO_OK`] /
 [`GMCRYPTO_ERR`] (same single failure mode). XTS is unauthenticated,
 so decrypt cannot detect tampering — it only fails on invalid
 parameters (length / weak key / buffer).
 */

int gmcrypto_sm4_xts_decrypt(const uint8_t *key,
                             const uint8_t *tweak,
                             const uint8_t *data,
                             uintptr_t data_len,
                             uint8_t *out,
                             uintptr_t out_capacity,
                             uintptr_t *out_actual_len)
;

/*
 SM4-XTS in-place multi-sector encrypt (GB/T 17964-2021,
 `xts_standard=GB`). `key` is exactly [`GMCRYPTO_SM4_XTS_KEY_SIZE`] (32)
 bytes (`Key1 ‖ Key2`); `buf` is a contiguous run of `buf_len / sector_size`
 equal-size sectors transformed **in place** (`buf_len` must be a whole
 multiple of `sector_size`). Sector `i` is encrypted under
 tweak = little-endian-128(`start_sector + i`) — the data-unit / LBA
 convention; sector numbers must be unique within the XTS-key namespace
 (caller's contract). `start_sector` is a `uint64_t` (LBA width), so the
 addressable range is `[0, 2^64 − 1]`; for the full u128 sector space use
 the Rust `mode_xts::encrypt_sectors` API. Returns [`GMCRYPTO_OK`] /
 [`GMCRYPTO_ERR`] (single
 failure mode: `sector_size` outside `[16, 16 MiB]` or not a multiple of 16,
 `buf_len` not a whole multiple of `sector_size`, `Key1 == Key2`, or null
 pointer). **`buf` is untouched on [`GMCRYPTO_ERR`].** `buf_len == 0` is a
 vacuous [`GMCRYPTO_OK`] (but the key is still validated, so empty + weak key
 → [`GMCRYPTO_ERR`]). **Confidentiality only — SM4-XTS does not
 authenticate.**
 */

int gmcrypto_sm4_xts_encrypt_sectors(const uint8_t *key,
                                     uintptr_t sector_size,
                                     uint64_t start_sector,
                                     uint8_t *buf,
                                     uintptr_t buf_len)
;

/*
 SM4-XTS in-place multi-sector decrypt (GB/T 17964-2021, `xts_standard=GB`).
 Inverse of [`gmcrypto_sm4_xts_encrypt_sectors`] under the same
 `(key, sector_size, start_sector)`; same in-place contract, single failure
 mode, and `buf`-untouched-on-error guarantee. XTS is unauthenticated, so
 decrypt cannot detect tampering — it only fails on invalid parameters.
 */

int gmcrypto_sm4_xts_decrypt_sectors(const uint8_t *key,
                                     uintptr_t sector_size,
                                     uint64_t start_sector,
                                     uint8_t *buf,
                                     uintptr_t buf_len)
;

/*
 Construct a streaming SM4-GCM encryptor. `key` is exactly 16 bytes;
 `nonce` is `nonce_len` bytes (12 = canonical; other lengths invoke
 the extra GHASH J0-derivation per NIST SP 800-38D §8.2.2); `aad` is
 the full associated data (the message header, supplied up-front).
 Returns NULL on invalid pointer/length input. **Nonce uniqueness is
 the caller's responsibility** — reusing `(key, nonce)` is
 catastrophic for GCM.
 */

gmcrypto_sm4_gcm_encryptor_t *gmcrypto_sm4_gcm_encryptor_new(const uint8_t *key,
                                                             const uint8_t *nonce,
                                                             uintptr_t nonce_len,
                                                             const uint8_t *aad,
                                                             uintptr_t aad_len)
;

/*
 Encrypt `pt_len` bytes of plaintext, emitting the ciphertext for
 this chunk (length == `pt_len`; GCM does not pad or buffer). The
 `out` buffer MUST be at least `pt_len` bytes; on insufficient
 capacity returns [`GMCRYPTO_ERR`] (and the required length is written
 to `*out_actual_len`), and the encryptor state is left mid-stream
 (the chunk's ciphertext is lost — size the buffer correctly).
 Returns [`GMCRYPTO_ERR`] once the cumulative plaintext would exceed
 the GCM ceiling (`2^36 − 32` bytes); the encryptor is poisoned and
 all later calls also return [`GMCRYPTO_ERR`].
 */

int gmcrypto_sm4_gcm_encryptor_update(gmcrypto_sm4_gcm_encryptor_t *enc,
                                      const uint8_t *pt,
                                      uintptr_t pt_len,
                                      uint8_t *out,
                                      uintptr_t out_capacity,
                                      uintptr_t *out_actual_len)
;

/*
 Finish and emit the full 16-byte tag. **Consumes the encryptor —
 the handle is freed by this call** (even on error); do NOT call
 [`gmcrypto_sm4_gcm_encryptor_free`] on it afterwards. `tag_out`
 must be valid for exactly 16 bytes.
 */
 int gmcrypto_sm4_gcm_encryptor_finalize(gmcrypto_sm4_gcm_encryptor_t *enc, uint8_t *tag_out) ;

/*
 Finish and emit a truncated tag of `tag_len` bytes (`MSB_t` per NIST
 SP 800-38D §5.2.1.2). `tag_len` must be in `{4, 8, 12, 13, 14, 15,
 16}` (else [`GMCRYPTO_ERR`]). **Consumes the encryptor — the handle
 is freed by this call** (even on error); do NOT call
 [`gmcrypto_sm4_gcm_encryptor_free`] afterwards.
 */

int gmcrypto_sm4_gcm_encryptor_finalize_with_tag_len(gmcrypto_sm4_gcm_encryptor_t *enc,
                                                     uintptr_t tag_len,
                                                     uint8_t *out,
                                                     uintptr_t out_capacity,
                                                     uintptr_t *out_actual_len)
;

/*
 Free a streaming SM4-GCM encryptor without finalizing (abort path).
 Passing NULL is a no-op. Do NOT call after any `_finalize*` — those
 already consumed the handle.
 */
 void gmcrypto_sm4_gcm_encryptor_free(gmcrypto_sm4_gcm_encryptor_t *enc) ;

/*
 Construct a streaming SM4-GCM decryptor. Same parameter contract as
 [`gmcrypto_sm4_gcm_encryptor_new`]. Returns NULL on invalid input.
 */

gmcrypto_sm4_gcm_decryptor_t *gmcrypto_sm4_gcm_decryptor_new(const uint8_t *key,
                                                             const uint8_t *nonce,
                                                             uintptr_t nonce_len,
                                                             const uint8_t *aad,
                                                             uintptr_t aad_len)
;

/*
 Buffer `ct_len` bytes of ciphertext and fold them into the running
 GHASH. **Emits no plaintext** (commit-on-verify) — there is no
 output parameter. Returns [`GMCRYPTO_ERR`] only on null handle or
 invalid input pointer; a length-ceiling overflow is latched and
 surfaces as [`GMCRYPTO_ERR`] at
 [`gmcrypto_sm4_gcm_decryptor_finalize_verify`].
 */

int gmcrypto_sm4_gcm_decryptor_update(gmcrypto_sm4_gcm_decryptor_t *dec,
                                      const uint8_t *ct,
                                      uintptr_t ct_len)
;

/*
 Verify `tag` (`tag_len` bytes; the length is validated against the
 NIST-permitted set `{4, 8, 12, 13, 14, 15, 16}`) and, on success,
 write the full decrypted plaintext (length == total ciphertext fed)
 to `(out, out_capacity, out_actual_len)`.

 Returns [`GMCRYPTO_ERR`] in two cases, both of which still **consume
 and free the handle** (do NOT call
 [`gmcrypto_sm4_gcm_decryptor_free`] afterwards):

 - **Verification failure** (tag mismatch, invalid `tag_len`, or
   length-ceiling overflow): `*out_actual_len` is `0` and no
   plaintext is written (commit-on-verify; single failure mode).
 - **Tag verified but `out` too small**: `*out_actual_len` is set to
   the required plaintext length and no plaintext is written. The
   handle is consumed, so you cannot retry — size `out` to the total
   ciphertext length up-front (GCM plaintext is the same length).
 */

int gmcrypto_sm4_gcm_decryptor_finalize_verify(gmcrypto_sm4_gcm_decryptor_t *dec,
                                               const uint8_t *tag,
                                               uintptr_t tag_len,
                                               uint8_t *out,
                                               uintptr_t out_capacity,
                                               uintptr_t *out_actual_len)
;

/*
 Free a streaming SM4-GCM decryptor without verifying (abort path).
 NULL is a no-op. Do NOT call after
 [`gmcrypto_sm4_gcm_decryptor_finalize_verify`].
 */
 void gmcrypto_sm4_gcm_decryptor_free(gmcrypto_sm4_gcm_decryptor_t *dec) ;

/*
 Construct an SM2 private key from a 32-byte big-endian scalar.
 Returns NULL on out-of-range scalar (must be in `[1, n-2]`).
 */
 gmcrypto_sm2_privkey_t *gmcrypto_sm2_privkey_new(const uint8_t *d_be) ;

/*
 Construct an SM2 public key from a SEC1 uncompressed-point byte
 string (`04 || X || Y`, 65 bytes). Returns NULL on
 invalid input (off-curve, identity point, non-uncompressed
 prefix).
 */
 gmcrypto_sm2_pubkey_t *gmcrypto_sm2_pubkey_new(const uint8_t *sec1_uncompressed) ;

/*
 Export the SM2 private key as a 32-byte big-endian scalar.

 **Caller MUST zeroize the output buffer** after use. Per Q4.19,
 this entry point exists as `#[doc(hidden)]`-equivalent on the
 Rust side and is NOT SemVer-stable across v0.4.x.
 */
 int gmcrypto_sm2_privkey_to_sec1_be(const gmcrypto_sm2_privkey_t *key, uint8_t *out) ;

/*
 Export the SM2 public key as a SEC1 uncompressed-point byte
 string (`04 || X || Y`, 65 bytes).
 */
 int gmcrypto_sm2_pubkey_to_sec1_uncompressed(const gmcrypto_sm2_pubkey_t *key, uint8_t *out) ;

/*
 Free an SM2 private key. NULL is a no-op. The inner scalar is
 zeroized via `ZeroizeOnDrop` before the heap slot is freed.
 */
 void gmcrypto_sm2_privkey_free(gmcrypto_sm2_privkey_t *key) ;

/*
 Free an SM2 public key. NULL is a no-op.
 */
 void gmcrypto_sm2_pubkey_free(gmcrypto_sm2_pubkey_t *key) ;

/*
 Emit a password-encrypted PKCS#8 PEM blob containing the SM2
 private key. PBES2 / PBKDF2-HMAC-SM3 / SM4-CBC per RFC 8018.
 */

int gmcrypto_sm2_privkey_to_pkcs8(const gmcrypto_sm2_privkey_t *key,
                                  const uint8_t *password,
                                  uintptr_t pwd_len,
                                  uint32_t pbkdf2_iters,
                                  uint8_t *out_pem,
                                  uintptr_t out_capacity,
                                  uintptr_t *out_actual_len)
;

/*
 Load an SM2 private key from a password-encrypted PKCS#8 PEM blob.
 On success, writes the new handle to `*out_key` and returns
 [`GMCRYPTO_OK`]. Caller MUST free via [`gmcrypto_sm2_privkey_free`].
 */

int gmcrypto_sm2_privkey_from_pkcs8(const uint8_t *pem,
                                    uintptr_t pem_len,
                                    const uint8_t *password,
                                    uintptr_t pwd_len,
                                    gmcrypto_sm2_privkey_t **out_key)
;

/*
 Sign `msg` with the SM2 private key using the supplied
 `signer_id` (or [`DEFAULT_SIGNER_ID`] = `"1234567812345678"` if
 `signer_id_len == 0`). Output is DER-encoded
 `SEQUENCE { r, s }`. RNG is sourced from `getrandom::SysRng`.

 May return [`GMCRYPTO_ERR`] if the system RNG fails (in addition to the
 usual null / short-buffer errors); the error is terminal — do not retry
 on the same inputs expecting success.
 */

int gmcrypto_sm2_sign(const gmcrypto_sm2_privkey_t *key,
                      const uint8_t *signer_id,
                      uintptr_t signer_id_len,
                      const uint8_t *msg,
                      uintptr_t msg_len,
                      uint8_t *out_der_sig,
                      uintptr_t out_capacity,
                      uintptr_t *out_actual_len)
;

/*
 Verify a DER-encoded `(r, s)` signature against `msg` using the
 SM2 public key and `signer_id`. Returns [`GMCRYPTO_OK`] on
 valid; [`GMCRYPTO_ERR`] on invalid or any error.
 */

int gmcrypto_sm2_verify(const gmcrypto_sm2_pubkey_t *key,
                        const uint8_t *signer_id,
                        uintptr_t signer_id_len,
                        const uint8_t *msg,
                        uintptr_t msg_len,
                        const uint8_t *der_sig,
                        uintptr_t der_sig_len)
;

/*
 SM2 public-key encrypt. Output is GM/T 0009-2012 DER. RNG from
 `getrandom::SysRng`.

 May return [`GMCRYPTO_ERR`] if the system RNG fails (in addition to the
 usual null / short-buffer errors); the error is terminal.
 */

int gmcrypto_sm2_encrypt(const gmcrypto_sm2_pubkey_t *key,
                         const uint8_t *pt,
                         uintptr_t pt_len,
                         uint8_t *out_der_ct,
                         uintptr_t out_capacity,
                         uintptr_t *out_actual_len)
;

/*
 SM2 private-key decrypt of a GM/T 0009-2012 DER ciphertext.
 */

int gmcrypto_sm2_decrypt(const gmcrypto_sm2_privkey_t *key,
                         const uint8_t *der_ct,
                         uintptr_t der_ct_len,
                         uint8_t *out_pt,
                         uintptr_t out_capacity,
                         uintptr_t *out_actual_len)
;

/*
 SM2 public-key encrypt; output in the modern raw byte-concat
 `C1 || C3 || C2` format. `C1` is the 65-byte SEC1-uncompressed
 point (`0x04 || X || Y`); `C3` is the 32-byte SM3 MAC; `C2` is
 `msg_len` bytes of XOR-ed ciphertext. Output length is exactly
 `65 + 32 + msg_len`.

 RNG is sourced from `getrandom::SysRng` internally (same as
 [`gmcrypto_sm2_encrypt`]). The W3 RNG-callback variant lands as a
 separate workstream.

 Same failure-mode posture as [`gmcrypto_sm2_encrypt`]: single
 [`GMCRYPTO_ERR`] on any failure mode (identity public key, KDF-
 zero retries exhausted).
 */

int gmcrypto_sm2_encrypt_c1c3c2(const gmcrypto_sm2_pubkey_t *key,
                                const uint8_t *pt,
                                uintptr_t pt_len,
                                uint8_t *out_raw_ct,
                                uintptr_t out_capacity,
                                uintptr_t *out_actual_len)
;

/*
 SM2 private-key decrypt of a modern raw byte-concat
 `C1 || C3 || C2` ciphertext. Input length must be at least
 `65 + 32 + 1 = 98` bytes (C1 + C3 + at least one C2 byte).

 Same failure-mode posture as [`gmcrypto_sm2_decrypt`]: single
 [`GMCRYPTO_ERR`] on any failure mode (malformed input, off-curve
 C1, identity C1, MAC mismatch, or KDF-zero detection). Caller
 cannot distinguish wrong-key from corrupt-ciphertext via timing
 or return code.
 */

int gmcrypto_sm2_decrypt_c1c3c2(const gmcrypto_sm2_privkey_t *key,
                                const uint8_t *raw_ct,
                                uintptr_t raw_ct_len,
                                uint8_t *out_pt,
                                uintptr_t out_capacity,
                                uintptr_t *out_actual_len)
;

/*
 SM2 private-key decrypt of a **legacy** raw byte-concat
 `C1 || C2 || C3` ciphertext. Decrypt-only — there is no emit path
 for the legacy ordering, and there will not be one in any v0.5+
 version (per `CLAUDE.md` "Don't" entry).

 The two raw byte-concat orderings (`C1 || C3 || C2` modern vs
 `C1 || C2 || C3` legacy) are NOT auto-detected. The caller MUST
 know which format their wire-data follows. Mis-feeding modern
 ciphertext to this entry point or vice-versa will fail at the MAC
 check (`GMCRYPTO_ERR`); the failure-mode invariant precludes the
 caller from distinguishing wrong-format from wrong-key.

 Same failure-mode posture as [`gmcrypto_sm2_decrypt_c1c3c2`]:
 single [`GMCRYPTO_ERR`] on any failure.
 */

int gmcrypto_sm2_decrypt_c1c2c3_legacy(const gmcrypto_sm2_privkey_t *key,
                                       const uint8_t *raw_ct,
                                       uintptr_t raw_ct_len,
                                       uint8_t *out_pt,
                                       uintptr_t out_capacity,
                                       uintptr_t *out_actual_len)
;

/*
 `_with_rng` variant of [`gmcrypto_sm2_sign`]. Identical contract
 except RNG bytes come from the caller's `rng_callback` rather
 than `getrandom::SysRng`.

 Returns [`GMCRYPTO_OK`] on success; [`GMCRYPTO_ERR`] on any
 failure including:
 - null `key` pointer
 - null `rng_callback` pointer
 - callback returned non-zero on any draw
 - signing produced no valid signature within the retry budget

 Per the failure-mode invariant, the caller cannot distinguish
 callback-error from signing-failure via return code or timing.
 */

int gmcrypto_sm2_sign_with_rng(const gmcrypto_sm2_privkey_t *key,
                               const uint8_t *signer_id,
                               uintptr_t signer_id_len,
                               const uint8_t *msg,
                               uintptr_t msg_len,
                               gmcrypto_rng_callback rng_callback,
                               void *rng_context,
                               uint8_t *out_der_sig,
                               uintptr_t out_capacity,
                               uintptr_t *out_actual_len)
;

/*
 `_with_rng` variant of [`gmcrypto_sm2_encrypt`]. Identical
 contract except RNG bytes come from the caller's `rng_callback`
 rather than `getrandom::SysRng`.

 Output is GM/T 0009-2012 DER (same as `gmcrypto_sm2_encrypt`).
 For raw byte-concat output (`C1 || C3 || C2`), use
 `gmcrypto_sm2_encrypt_c1c3c2` — v0.5 doesn't ship a
 `_c1c3c2_with_rng` combined variant; if needed, callers can
 re-encode the DER output via gmcrypto-core's
 `asn1::ciphertext::decode` + `raw_ciphertext::encode_c1c3c2`.

 Same `GMCRYPTO_ERR`-on-any-failure posture as
 `gmcrypto_sm2_sign_with_rng`.
 */

int gmcrypto_sm2_encrypt_with_rng(const gmcrypto_sm2_pubkey_t *key,
                                  const uint8_t *pt,
                                  uintptr_t pt_len,
                                  gmcrypto_rng_callback rng_callback,
                                  void *rng_context,
                                  uint8_t *out_der_ct,
                                  uintptr_t out_capacity,
                                  uintptr_t *out_actual_len)
;

/*
 Construct a key-exchange INITIATOR (party A) and write its
 ephemeral point `R_A` (SEC1 uncompressed `04 ‖ X ‖ Y`, exactly
 [`GMCRYPTO_SM2_SEC1_UNCOMPRESSED_SIZE`] = 65 bytes) to `out_r_a`.
 The handle is created already awaiting the responder's reply: send
 `out_r_a` to the responder, then call
 [`gmcrypto_sm2_kx_initiator_confirm`] with its `(R_B, S_B)`.

 `local_privkey` is A's static key; `peer_pubkey` is B's static
 public key. `id_a` / `id_b` are the parties' identity strings
 (`len == 0` selects the GM/T default ID `"1234567812345678"`).
 `klen` is the agreed-key length in bytes (non-zero, under the KDF
 ceiling); the SAME `klen` sizes `key_out` at confirm time.
 Ephemeral randomness comes from the OS (`getrandom::SysRng`).

 Returns the handle, or NULL on any failure (null pointer, bad
 `klen`/`id`, RNG failure — indistinguishable by design). Pair with
 exactly one `_confirm` (which frees) **or** one `_free`.

 # Safety

 `local_privkey` / `peer_pubkey` must be valid handles from this
 library; `out_r_a` must be valid for 65 writes; `id_a` / `id_b`
 must be valid for their lengths when non-zero.
 */

gmcrypto_sm2_kx_initiator_t *gmcrypto_sm2_kx_initiator_new(const gmcrypto_sm2_privkey_t *local_privkey,
                                                           const gmcrypto_sm2_pubkey_t *peer_pubkey,
                                                           const uint8_t *id_a,
                                                           uintptr_t id_a_len,
                                                           const uint8_t *id_b,
                                                           uintptr_t id_b_len,
                                                           uintptr_t klen,
                                                           uint8_t *out_r_a)
;

/*
 `_with_rng` variant of [`gmcrypto_sm2_kx_initiator_new`]: identical
 contract except the ephemeral randomness comes from the caller's
 `rng_callback` (the v0.5 `gmcrypto_rng_callback` shape) rather than
 `getrandom::SysRng`. A null or failing callback returns NULL —
 indistinguishable from every other failure by design.

 # Safety

 As [`gmcrypto_sm2_kx_initiator_new`]; additionally `rng_callback`
 must be NULL or a valid function pointer honouring the callback
 contract (fill `buf_len` bytes, return 0 on success).
 */

gmcrypto_sm2_kx_initiator_t *gmcrypto_sm2_kx_initiator_new_with_rng(const gmcrypto_sm2_privkey_t *local_privkey,
                                                                    const gmcrypto_sm2_pubkey_t *peer_pubkey,
                                                                    const uint8_t *id_a,
                                                                    uintptr_t id_a_len,
                                                                    const uint8_t *id_b,
                                                                    uintptr_t id_b_len,
                                                                    uintptr_t klen,
                                                                    gmcrypto_rng_callback rng_callback,
                                                                    void *rng_context,
                                                                    uint8_t *out_r_a)
;

/*
 Receive the responder's reply and finish the initiator side:
 verify `S_B` (constant-time), and on success write the agreed key
 (exactly `klen` bytes, the `klen` given at `_new`) to `key_out`
 and the initiator's confirmation tag `S_A`
 ([`GMCRYPTO_SM2_KX_CONFIRM_SIZE`] = 32 bytes) to `out_s_a` — send
 `S_A` to the responder. `r_b` is the responder's ephemeral point
 (65 bytes); `s_b` its confirmation tag (32 bytes).

 CONSUMES + FREES the handle — even when the arguments are invalid
 or the confirmation fails (the `_finalize*` precedent); do NOT
 call `_free` afterwards. Returns [`GMCRYPTO_OK`] only when `S_B`
 verified and the key was written; every failure (invalid `R_B`,
 tag mismatch, null pointer) is the single [`GMCRYPTO_ERR`].
 **The caller owns wiping `key_out`.**

 # Safety

 `initiator` must be a live handle from a `_new` (not yet consumed
 or freed); `r_b` valid for 65 reads, `s_b` for 32 reads, `key_out`
 for `klen` writes, `out_s_a` for 32 writes.
 */

int gmcrypto_sm2_kx_initiator_confirm(gmcrypto_sm2_kx_initiator_t *initiator,
                                      const uint8_t *r_b,
                                      const uint8_t *s_b,
                                      uint8_t *key_out,
                                      uint8_t *out_s_a)
;

/*
 Free an UNCONSUMED initiator handle (abandonment path — e.g. the
 responder never replied). Safe on NULL. Do NOT call after
 `_confirm` (which already consumed + freed the handle).

 # Safety

 `initiator` must be NULL or a live handle from a `_new`.
 */
 void gmcrypto_sm2_kx_initiator_free(gmcrypto_sm2_kx_initiator_t *initiator) ;

/*
 Construct a key-exchange RESPONDER (party B). `local_privkey` is
 B's static key; `peer_pubkey` is A's static public key; ids and
 `klen` follow the [`gmcrypto_sm2_kx_initiator_new`] conventions
 (and must match the initiator's, or the confirmation tags will
 not verify). The handle then waits for the initiator's `R_A` —
 call [`gmcrypto_sm2_kx_responder_respond`].

 Returns the handle, or NULL on any failure. Pair with exactly one
 [`gmcrypto_sm2_kx_responder_finish`] (which frees) **or** one
 [`gmcrypto_sm2_kx_responder_free`].

 # Safety

 `local_privkey` / `peer_pubkey` must be valid handles from this
 library; `id_a` / `id_b` must be valid for their lengths when
 non-zero.
 */

gmcrypto_sm2_kx_responder_t *gmcrypto_sm2_kx_responder_new(const gmcrypto_sm2_privkey_t *local_privkey,
                                                           const gmcrypto_sm2_pubkey_t *peer_pubkey,
                                                           const uint8_t *id_a,
                                                           uintptr_t id_a_len,
                                                           const uint8_t *id_b,
                                                           uintptr_t id_b_len,
                                                           uintptr_t klen)
;

/*
 Receive the initiator's `R_A` (65 bytes) and produce the
 responder's reply: writes `R_B` (65 bytes) to `out_r_b` and the
 responder's confirmation tag `S_B` (32 bytes) to `out_s_b` — send
 both to the initiator, then call
 [`gmcrypto_sm2_kx_responder_finish`] with its `S_A`. Ephemeral
 randomness comes from the OS (`getrandom::SysRng`).

 The handle stays alive (it now holds the agreed key, wiped on
 drop, pending the initiator's confirmation). Calling `_respond`
 twice returns [`GMCRYPTO_ERR`] without disturbing the in-flight
 state. A FAILED respond (invalid `R_A`, RNG failure) spends the
 handle — every further call fails and the caller frees it.

 # Safety

 `responder` must be a live handle from `_new`; `r_a` valid for 65
 reads, `out_r_b` for 65 writes, `out_s_b` for 32 writes.
 */

int gmcrypto_sm2_kx_responder_respond(gmcrypto_sm2_kx_responder_t *responder,
                                      const uint8_t *r_a,
                                      uint8_t *out_r_b,
                                      uint8_t *out_s_b)
;

/*
 `_with_rng` variant of [`gmcrypto_sm2_kx_responder_respond`]:
 identical contract except the ephemeral randomness comes from the
 caller's `rng_callback` rather than `getrandom::SysRng`.

 # Safety

 As [`gmcrypto_sm2_kx_responder_respond`]; additionally
 `rng_callback` must be NULL or a valid function pointer honouring
 the callback contract.
 */

int gmcrypto_sm2_kx_responder_respond_with_rng(gmcrypto_sm2_kx_responder_t *responder,
                                               const uint8_t *r_a,
                                               gmcrypto_rng_callback rng_callback,
                                               void *rng_context,
                                               uint8_t *out_r_b,
                                               uint8_t *out_s_b)
;

/*
 Verify the initiator's confirmation tag `S_A` (32 bytes,
 constant-time) and on success write the agreed key (exactly
 `klen` bytes, the `klen` given at `_new`) to `key_out`.

 CONSUMES + FREES the handle — even when the arguments are invalid
 or the tag mismatches (the held key is wiped on drop in every
 case); do NOT call `_free` afterwards. Returns [`GMCRYPTO_OK`]
 only when `S_A` verified and the key was written; calling
 `_finish` before a successful `_respond` is the same single
 [`GMCRYPTO_ERR`]. **The caller owns wiping `key_out`.**

 # Safety

 `responder` must be a live handle from `_new` (not yet consumed
 or freed); `s_a` valid for 32 reads, `key_out` for `klen` writes.
 */

int gmcrypto_sm2_kx_responder_finish(gmcrypto_sm2_kx_responder_t *responder,
                                     const uint8_t *s_a,
                                     uint8_t *key_out)
;

/*
 Free an UNCONSUMED responder handle (abandonment path — e.g. the
 initiator never confirmed, or a `_respond` failure spent the
 handle). Safe on NULL. Do NOT call after `_finish` (which already
 consumed + freed the handle). Any held key material is wiped.

 # Safety

 `responder` must be NULL or a live handle from `_new`.
 */
 void gmcrypto_sm2_kx_responder_free(gmcrypto_sm2_kx_responder_t *responder) ;

/*
 Parse a DER X.509-with-SM2 **v3 leaf** certificate (GM/T 0015 profile:
 `sm2-sign-with-sm3` signature algorithm, SM2 SPKI). Returns NULL on ANY
 failure (null/empty input, malformed DER, wrong profile) —
 indistinguishable by design. **Parsing makes NO trust decisions** (no
 chain / time / extension / revocation logic — see `gmcrypto-core`'s
 `x509` module docs).

 # Safety

 `der` must be valid for `der_len` reads (or `der_len == 0`).
 */

gmcrypto_x509_certificate_t *gmcrypto_x509_certificate_from_der(const uint8_t *der,
                                                                uintptr_t der_len)
;

/*
 Free a certificate handle. NULL is a no-op.

 # Safety

 `cert` must be a handle from this library, not yet freed.
 */
 void gmcrypto_x509_certificate_free(gmcrypto_x509_certificate_t *cert) ;

/*
 The exact `TBSCertificate` TLV bytes as they appeared on the wire (the
 bytes the signature covers) — NOT re-encoded, NOT trust-validated.
 Copy-out convention: too-small buffer → [`GMCRYPTO_ERR`] + required
 length in `*out_actual_len`.

 # Safety

 `cert` must be a valid handle; `out` valid for `out_capacity` writes;
 `out_actual_len` valid for one write.
 */

int gmcrypto_x509_certificate_tbs_raw(const gmcrypto_x509_certificate_t *cert,
                                      uint8_t *out,
                                      uintptr_t out_capacity,
                                      uintptr_t *out_actual_len)
;

/*
 The serial number as unsigned big-endian value bytes (the DER
 disambiguating pad is stripped), 1..=20 bytes; negative serials were
 rejected at parse. Copy-out convention as
 [`gmcrypto_x509_certificate_tbs_raw`].

 # Safety

 As [`gmcrypto_x509_certificate_tbs_raw`].
 */

int gmcrypto_x509_certificate_serial_raw(const gmcrypto_x509_certificate_t *cert,
                                         uint8_t *out,
                                         uintptr_t out_capacity,
                                         uintptr_t *out_actual_len)
;

/*
 The issuer `Name` as its full raw DER TLV — no interpretation; match
 issuers by byte equality. Copy-out convention as
 [`gmcrypto_x509_certificate_tbs_raw`].

 # Safety

 As [`gmcrypto_x509_certificate_tbs_raw`].
 */

int gmcrypto_x509_certificate_issuer_raw(const gmcrypto_x509_certificate_t *cert,
                                         uint8_t *out,
                                         uintptr_t out_capacity,
                                         uintptr_t *out_actual_len)
;

/*
 The subject `Name` as its full raw DER TLV — no interpretation.
 Copy-out convention as [`gmcrypto_x509_certificate_tbs_raw`].

 # Safety

 As [`gmcrypto_x509_certificate_tbs_raw`].
 */

int gmcrypto_x509_certificate_subject_raw(const gmcrypto_x509_certificate_t *cert,
                                          uint8_t *out,
                                          uintptr_t out_capacity,
                                          uintptr_t *out_actual_len)
;

/*
 The `Extensions` SEQUENCE TLV if present — shape-checked at parse but
 NEVER interpreted (`critical` flags included); a caller building trust
 logic on top inherits RFC 5280 §4.2's reject-unrecognized-critical
 obligation. **`*out_actual_len == 0` means the optional extensions
 block is ABSENT** (a present block is never empty), with
 [`GMCRYPTO_OK`]. Copy-out convention otherwise as
 [`gmcrypto_x509_certificate_tbs_raw`].

 # Safety

 As [`gmcrypto_x509_certificate_tbs_raw`].
 */

int gmcrypto_x509_certificate_extensions_raw(const gmcrypto_x509_certificate_t *cert,
                                             uint8_t *out,
                                             uintptr_t out_capacity,
                                             uintptr_t *out_actual_len)
;

/*
 Verify the certificate's SM2-with-SM3 signature over the exact wire
 `tbsCertificate` bytes against the issuer's public key
 (`issuer_pubkey` is a KEY handle, not an issuer certificate), using the
 GM / RFC 8998 default signer ID `"1234567812345678"`. Returns
 [`GMCRYPTO_OK`] only on a verifying signature; [`GMCRYPTO_ERR`] on
 invalid or any error (indistinguishable by design).

 **This is NOT certificate validation** — no chain / time / extension /
 revocation logic; success means exactly "this issuer key signed these
 tbs bytes".

 # Safety

 `cert` / `issuer_pubkey` must be valid handles from this library.
 */

int gmcrypto_x509_certificate_verify_signature(const gmcrypto_x509_certificate_t *cert,
                                               const gmcrypto_sm2_pubkey_t *issuer_pubkey)
;

/*
 As [`gmcrypto_x509_certificate_verify_signature`] with a caller-supplied
 SM2 signer ID; `id_len == 0` selects the default ID (the v1.2 KX
 convention — an empty ID is unrepresentable through this ABI).

 # Safety

 `cert` / `issuer_pubkey` must be valid handles; `id` must be valid for
 `id_len` reads when `id_len > 0`.
 */

int gmcrypto_x509_certificate_verify_signature_with_id(const gmcrypto_x509_certificate_t *cert,
                                                       const gmcrypto_sm2_pubkey_t *issuer_pubkey,
                                                       const uint8_t *id,
                                                       uintptr_t id_len)
;

/*
 Write the certificate's `notBefore` into `*out_time`. Exposure only —
 NO validity decision is made (see [`gmcrypto_x509_time_t`]).

 # Safety

 `cert` must be a valid handle; `out_time` valid for one write.
 */

int gmcrypto_x509_certificate_not_before(const gmcrypto_x509_certificate_t *cert,
                                         gmcrypto_x509_time_t *out_time)
;

/*
 Write the certificate's `notAfter` into `*out_time`. Exposure only —
 NO validity decision is made (see [`gmcrypto_x509_time_t`]).

 # Safety

 `cert` must be a valid handle; `out_time` valid for one write.
 */

int gmcrypto_x509_certificate_not_after(const gmcrypto_x509_certificate_t *cert,
                                        gmcrypto_x509_time_t *out_time)
;

/*
 Write `1` to `*out_is_self_issued` if the certificate's subject and
 issuer `Name`s are byte-identical (the RFC 5280 self-ISSUED notion),
 else `0`; returns [`GMCRYPTO_OK`] for a successful evaluation,
 [`GMCRYPTO_ERR`] on null/bad arguments ("not self-issued" is NOT a
 failure). NOT "self-signed": use
 [`gmcrypto_x509_certificate_verify_signature`] against the cert's own
 subject key for a self-signature check.

 # Safety

 `cert` must be a valid handle or NULL; `out_is_self_issued` must be
 valid for one write or NULL.
 */

int gmcrypto_x509_certificate_is_self_issued(const gmcrypto_x509_certificate_t *cert,
                                             int *out_is_self_issued)
;

/*
 The subject's SM2 public key as a NEWLY allocated pubkey handle — the
 caller owns it and frees it via [`gmcrypto_sm2_pubkey_free`]. Composes
 with `gmcrypto_sm2_verify` / `gmcrypto_sm2_encrypt` / the KX
 constructors — and with
 [`gmcrypto_x509_certificate_verify_signature`] for manual leaf-vs-CA
 chaining. NULL only on NULL input (the key was validated on-curve at
 parse).

 # Safety

 `cert` must be a valid handle or NULL.
 */

gmcrypto_sm2_pubkey_t *gmcrypto_x509_certificate_subject_public_key(const gmcrypto_x509_certificate_t *cert)
;

/*
 Derive the 48-byte TLCP master secret from a 48-byte `pre_master` and the
 two 32-byte randoms. Infallible in core — returns [`GMCRYPTO_ERR`] only on a
 NULL pointer. **The caller owns wiping `pre_master` and `out`.**
 */

int gmcrypto_tlcp_derive_master_secret(const uint8_t *pre_master,
                                       const uint8_t *client_random,
                                       const uint8_t *server_random,
                                       uint8_t *out)
;

/*
 Expand the key block: `PRF(master_secret, "key expansion",
 server_random ‖ client_random)`. Writes exactly `out_len` bytes (the caller
 carves per suite — CBC 128, GCM 40). `out_len == 0` is vacuously OK. **The
 caller owns wiping `out`.**
 */

int gmcrypto_tlcp_derive_key_block(const uint8_t *master_secret,
                                   const uint8_t *client_random,
                                   const uint8_t *server_random,
                                   uint8_t *out,
                                   uintptr_t out_len)
;

/*
 Compute the 12-byte Finished `verify_data` for `role` (`0` = Client,
 `1` = Server). `transcript_hash` is the caller's SM3 over the handshake
 messages (stateless). **The caller owns wiping `out`.**
 */

int gmcrypto_tlcp_finished_verify_data(const uint8_t *master_secret,
                                       int role,
                                       const uint8_t *transcript_hash,
                                       uint8_t *out)
;

/*
 Complete the SM2 key exchange on the INITIATOR side WITHOUT key confirmation
 (the TLCP Finished message plays the S_A/S_B role). CONSUMES + FREES the
 `gmcrypto_sm2_kx_initiator_t` handle on every path; takes only the peer
 `R_B` (65 bytes, SEC1 `04 ‖ X ‖ Y`) and writes the agreed key (the `klen`
 given at `_new`) to `key_out`. An invalid `R_B` is the single
 [`GMCRYPTO_ERR`]. **The caller owns wiping `key_out`.** Do NOT `_free`
 afterwards.
 */

int gmcrypto_sm2_kx_initiator_derive_unconfirmed(gmcrypto_sm2_kx_initiator_t *initiator,
                                                 const uint8_t *r_b,
                                                 uint8_t *key_out)
;

/*
 Complete the SM2 key exchange on the RESPONDER side WITHOUT key confirmation
 (single call — no S_A to verify). CONSUMES + FREES the handle; takes the
 initiator's `R_A` (65 bytes), writes `R_B` (65 bytes) to `out_r_b` and the
 agreed key (`klen` bytes) to `key_out`. Ephemeral randomness comes from the
 OS. **The caller owns wiping `key_out`.** Do NOT `_free` afterwards.
 */

int gmcrypto_sm2_kx_responder_respond_unconfirmed(gmcrypto_sm2_kx_responder_t *responder,
                                                  const uint8_t *r_a,
                                                  uint8_t *out_r_b,
                                                  uint8_t *key_out)
;

/*
 `_with_rng` variant of [`gmcrypto_sm2_kx_responder_respond_unconfirmed`]:
 the ephemeral randomness comes from `rng_callback` rather than the OS. A
 NULL callback returns [`GMCRYPTO_ERR`] WITHOUT consuming the handle (free it
 yourself), matching the confirmed `_with_rng` flow.
 */

int gmcrypto_sm2_kx_responder_respond_unconfirmed_with_rng(gmcrypto_sm2_kx_responder_t *responder,
                                                           const uint8_t *r_a,
                                                           gmcrypto_rng_callback rng_callback,
                                                           void *rng_context,
                                                           uint8_t *out_r_b,
                                                           uint8_t *key_out)
;

/*
 Carve the SM4-CBC record keys for `role` (`0` = Client, `1` = Server) from a
 128-byte (`GMCRYPTO_TLCP_CBC_KEY_BLOCK_LEN`) key block. Returns NULL on a bad
 role / NULL block. Free with [`gmcrypto_tlcp_record_keys_cbc_free`].
 */

gmcrypto_tlcp_record_keys_cbc_t *gmcrypto_tlcp_record_keys_cbc_new(int role,
                                                                   const uint8_t *key_block)
;

/*
 Free (and wipe) an SM4-CBC record key carrier. Safe on NULL.
 */
 void gmcrypto_tlcp_record_keys_cbc_free(gmcrypto_tlcp_record_keys_cbc_t *keys) ;

/*
 Carve the SM4-GCM record keys for `role` from a 40-byte
 (`GMCRYPTO_TLCP_GCM_KEY_BLOCK_LEN`) key block. Returns NULL on a bad role /
 NULL block. Free with [`gmcrypto_tlcp_record_keys_gcm_free`].
 */

gmcrypto_tlcp_record_keys_gcm_t *gmcrypto_tlcp_record_keys_gcm_new(int role,
                                                                   const uint8_t *key_block)
;

/*
 Free (and wipe) an SM4-GCM record key carrier. Safe on NULL.
 */
 void gmcrypto_tlcp_record_keys_gcm_free(gmcrypto_tlcp_record_keys_gcm_t *keys) ;

/*
 Protect (MAC-then-encrypt) a plaintext record under SM4-CBC with HMAC-SM3,
 a fresh OS-sampled explicit IV. `version` is 2 bytes; output to the
 `(out, out_capacity, out_actual_len)` copy-out buffer. Single
 [`GMCRYPTO_ERR`]. **`(key, seq)` uniqueness is the caller's contract.**
 */

int gmcrypto_tlcp_protect_cbc(const gmcrypto_tlcp_record_keys_cbc_t *keys,
                              uint64_t seq,
                              uint8_t content_type,
                              const uint8_t *version,
                              const uint8_t *plaintext,
                              uintptr_t pt_len,
                              uint8_t *out,
                              uintptr_t out_capacity,
                              uintptr_t *out_actual_len)
;

/*
 `_with_rng` variant of [`gmcrypto_tlcp_protect_cbc`]: the explicit IV comes
 from `rng_callback` (REQUIRED for record-KAT reproduction) rather than the
 OS. A NULL callback returns [`GMCRYPTO_ERR`].
 */

int gmcrypto_tlcp_protect_cbc_with_rng(const gmcrypto_tlcp_record_keys_cbc_t *keys,
                                       uint64_t seq,
                                       uint8_t content_type,
                                       const uint8_t *version,
                                       const uint8_t *plaintext,
                                       uintptr_t pt_len,
                                       gmcrypto_rng_callback rng_callback,
                                       void *rng_context,
                                       uint8_t *out,
                                       uintptr_t out_capacity,
                                       uintptr_t *out_actual_len)
;

/*
 Deprotect an SM4-CBC record (`explicit_IV(16) ‖ CBC_ct`) — the Lucky13
 constant-time operation lives in core; this shim adds NO logic. The
 recovered plaintext goes to the copy-out buffer ONLY on success; on ANY
 failure (bad pad, bad MAC, bad length — indistinguishable) it returns a
 single [`GMCRYPTO_ERR`] and touches NO output pointer. There is deliberately
 **no** length-in parameter (the post-strip length is secret).
 */

int gmcrypto_tlcp_deprotect_cbc(const gmcrypto_tlcp_record_keys_cbc_t *keys,
                                uint64_t seq,
                                uint8_t content_type,
                                const uint8_t *version,
                                const uint8_t *record,
                                uintptr_t record_len,
                                uint8_t *out,
                                uintptr_t out_capacity,
                                uintptr_t *out_actual_len)
;

/*
 Protect a plaintext record under SM4-GCM (RFC 5288: seq-derived nonce, TLS
 AAD). Output to the copy-out buffer; single [`GMCRYPTO_ERR`].
 **`(key, seq)` uniqueness is the caller's contract.**
 */

int gmcrypto_tlcp_protect_gcm(const gmcrypto_tlcp_record_keys_gcm_t *keys,
                              uint64_t seq,
                              uint8_t content_type,
                              const uint8_t *version,
                              const uint8_t *plaintext,
                              uintptr_t pt_len,
                              uint8_t *out,
                              uintptr_t out_capacity,
                              uintptr_t *out_actual_len)
;

/*
 Deprotect an SM4-GCM record (`explicit_nonce(8) ‖ ct ‖ tag(16)`,
 commit-on-verify). Plaintext to the copy-out buffer ONLY if the tag
 verifies; otherwise a single [`GMCRYPTO_ERR`] (short record / over-ceiling /
 bad tag are indistinguishable). No length-in parameter.
 */

int gmcrypto_tlcp_deprotect_gcm(const gmcrypto_tlcp_record_keys_gcm_t *keys,
                                uint64_t seq,
                                uint8_t content_type,
                                const uint8_t *version,
                                const uint8_t *record,
                                uintptr_t record_len,
                                uint8_t *out,
                                uintptr_t out_capacity,
                                uintptr_t *out_actual_len)
;

/*
 Verify a single linear, leaf-first certificate chain links to a
 caller-trusted anchor. `chain` / `anchors` are arrays of cert handles;
 `at_time` (NULL = skip the validity window) is the comparison time; the
 `bool` verdict is written to `*out_verified` (1 = verifies, 0 = does not,
 e.g. over-depth). Returns [`GMCRYPTO_OK`] for a successful evaluation,
 [`GMCRYPTO_ERR`] only on NULL `out_verified` or a malformed handle array.

 **⚠ This is structural-trust verification, NOT endpoint authentication.** A
 `1` means the chain links to a trusted CA — never "this is the peer I
 dialed" (identity binding is the caller's, permanently).
 */

int gmcrypto_x509_verify_chain(const gmcrypto_x509_certificate_t *const *chain,
                               uintptr_t chain_len,
                               const gmcrypto_x509_certificate_t *const *anchors,
                               uintptr_t anchors_len,
                               const gmcrypto_x509_time_t *at_time,
                               int *out_verified)
;

/*
 Verify a TLCP [signature, encryption] certificate pair (each a leaf-first
 chain) against the caller's `anchors`. Verdict to `*out_verified`. Returns
 [`GMCRYPTO_ERR`] only on NULL `out_verified` or a malformed handle array.

 **⚠ NOT endpoint authentication.** A `1` means each chain links to a trusted
 anchor, each leaf is usable for its TLCP role, neither leaf is a CA, and the
 two leaves share one identity (subject + the same issuing chain). It does
 **NOT** mean "this is the server I dialed" — *whose* identity the pair
 carries is the caller's decision, permanently.
 */

int gmcrypto_tlcp_verify_pair(const gmcrypto_x509_certificate_t *const *sign_chain,
                              uintptr_t sign_chain_len,
                              const gmcrypto_x509_certificate_t *const *enc_chain,
                              uintptr_t enc_chain_len,
                              const gmcrypto_x509_certificate_t *const *anchors,
                              uintptr_t anchors_len,
                              const gmcrypto_x509_time_t *at_time,
                              int *out_verified)
;

/*
 Read the `keyUsage` extension. Writes `1`/`0` to `*out_present` (absent OR
 malformed → `0`) and the raw bitmask to `*out_bits` (bit 0 =
 `digitalSignature`). Returns [`GMCRYPTO_ERR`] only on NULL.
 */

int gmcrypto_x509_certificate_key_usage(const gmcrypto_x509_certificate_t *cert,
                                        int *out_present,
                                        uint16_t *out_bits)
;

/*
 Read the `basicConstraints` extension. Writes `1`/`0` to `*out_present`
 (absent/malformed → `0`), the `cA` flag to `*out_is_ca`, and the
 `pathLenConstraint` to `*out_path_len` guarded by `*out_has_path_len`
 (parsed, **not** enforced — informational). Returns [`GMCRYPTO_ERR`] only on
 NULL.
 */

int gmcrypto_x509_certificate_basic_constraints(const gmcrypto_x509_certificate_t *cert,
                                                int *out_present,
                                                int *out_is_ca,
                                                int *out_has_path_len,
                                                uint32_t *out_path_len)
;

#endif  /* GMCRYPTO_H_ */