-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Expand file tree
/
Copy pathml_dsa.zig
More file actions
3598 lines (2987 loc) · 119 KB
/
Copy pathml_dsa.zig
File metadata and controls
3598 lines (2987 loc) · 119 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Module-Lattice-Based Digital Signature Algorithm (ML-DSA) as specified in NIST FIPS 204.
//!
//! ML-DSA is a post-quantum secure digital signature scheme based on the hardness
//! of the Module Learning With Errors (MLWE) and Module Short Integer Solution (MSIS)
//! problems over module lattices.
//!
//! We provide three parameter sets:
//!
//! - ML-DSA-44: NIST security category 2 (128-bit security)
//! - ML-DSA-65: NIST security category 3 (192-bit security)
//! - ML-DSA-87: NIST security category 5 (256-bit security)
const std = @import("std");
const builtin = @import("builtin");
const testing = std.testing;
const assert = std.debug.assert;
const crypto = std.crypto;
const errors = std.crypto.errors;
const math = std.math;
const mem = std.mem;
const sha3 = crypto.hash.sha3;
const ContextTooLongError = errors.ContextTooLongError;
const EncodingError = errors.EncodingError;
const SignatureVerificationError = errors.SignatureVerificationError;
/// ML-DSA-44 (Module-Lattice-Based Digital Signature Algorithm, 44 parameter set)
/// as specified in NIST FIPS 204.
///
/// This is a post-quantum signature scheme providing NIST security category 2,
/// which is roughly equivalent to the security of SHA-256 or AES-128.
///
/// Key sizes:
///
/// - Public key: 1312 bytes
/// - Secret key: 2560 bytes
/// - Signature: 2420 bytes
///
/// Example usage:
///
/// ```zig
/// const kp = MLDSA44.KeyPair.generate();
/// const msg = "Hello, post-quantum world!";
/// const sig = try kp.sign(msg, null);
/// try sig.verify(msg, kp.public_key);
/// ```
pub const MLDSA44 = MLDSAImpl(.{
.name = "ML-DSA-44",
.k = 4,
.l = 4,
.eta = 2,
.omega = 80,
.tau = 39,
.gamma1_bits = 17,
.gamma2 = 95232, // (Q-1)/88
.tr_size = 64,
.ctilde_size = 32,
});
/// ML-DSA-65 (Module-Lattice-Based Digital Signature Algorithm, 65 parameter set)
/// as specified in NIST FIPS 204.
///
/// This is a post-quantum signature scheme providing NIST security category 3,
/// which is roughly equivalent to the security of SHA-384 or AES-192.
///
/// Key sizes:
///
/// - Public key: 1952 bytes
/// - Secret key: 4032 bytes
/// - Signature: 3309 bytes
///
/// This parameter set offers higher security than ML-DSA-44 at the cost of
/// larger keys and signatures.
pub const MLDSA65 = MLDSAImpl(.{
.name = "ML-DSA-65",
.k = 6,
.l = 5,
.eta = 4,
.omega = 55,
.tau = 49,
.gamma1_bits = 19,
.gamma2 = 261888, // (Q-1)/32
.tr_size = 64,
.ctilde_size = 48,
});
/// ML-DSA-87 (Module-Lattice-Based Digital Signature Algorithm, 87 parameter set)
/// as specified in NIST FIPS 204.
///
/// This is a post-quantum signature scheme providing NIST security category 5,
/// which is roughly equivalent to the security of SHA-512 or AES-256.
///
/// Key sizes:
///
/// - Public key: 2592 bytes
/// - Secret key: 4896 bytes
/// - Signature: 4627 bytes
///
/// This parameter set offers the highest security level among the three ML-DSA
/// variants, suitable for applications requiring maximum security assurance.
pub const MLDSA87 = MLDSAImpl(.{
.name = "ML-DSA-87",
.k = 8,
.l = 7,
.eta = 2,
.omega = 75,
.tau = 60,
.gamma1_bits = 19,
.gamma2 = 261888, // (Q-1)/32
.tr_size = 64,
.ctilde_size = 64,
});
const N: usize = 256; // Degree of polynomials
const Q: u32 = 8380417; // Modulus: 2^23 - 2^13 + 1
const Q_BITS: u32 = 23;
const D: u32 = 13; // Dropped bits in power2Round
// Montgomery constant R = 2^32 mod q
const R: u64 = 1 << 32;
// Q^(-1) mod 2^32 = -(q^-1) mod 2^32
const Q_INV: u32 = 4236238847;
// (256)^(-1) * R^2 mod q, used in inverse NTT
const R_OVER_256: u32 = 41978;
// Primitive 512th root of unity
const ZETA: u32 = 1753;
const Params = struct {
name: []const u8,
// Matrix dimensions
k: u8, // Height of matrix A
l: u8, // Width of matrix A
// Sampling parameter
eta: u8, // Bound for secret coefficients
// Hint parameters
omega: u16, // Maximum number of hint bits
// Challenge parameter
tau: u16, // Weight of challenge polynomial
// Rounding parameters
gamma1_bits: u8, // Bits for gamma1
gamma2: u32, // Parameter for decompose
// Sizes
tr_size: usize, // Size of tr hash
ctilde_size: usize, // Size of challenge hash
};
const Poly = struct {
cs: [N]u32,
const zero: Poly = .{ .cs = .{0} ** N };
// Add two polynomials (no normalization)
fn add(a: Poly, b: Poly) Poly {
var ret: Poly = undefined;
for (0..N) |i| {
ret.cs[i] = a.cs[i] + b.cs[i];
}
return ret;
}
// Subtract two polynomials (assumes b coefficients < 2q)
fn sub(a: Poly, b: Poly) Poly {
var ret: Poly = undefined;
for (0..N) |i| {
ret.cs[i] = a.cs[i] +% (@as(u32, 2 * Q) -% b.cs[i]);
}
return ret;
}
// Reduce each coefficient to < 2q
fn reduceLe2Q(p: Poly) Poly {
var ret = p;
for (0..N) |i| {
ret.cs[i] = le2Q(ret.cs[i]);
}
return ret;
}
// Normalize coefficients to [0, q)
fn normalize(p: Poly) Poly {
var ret = p;
for (0..N) |i| {
ret.cs[i] = modQ(ret.cs[i]);
}
return ret;
}
// Normalize assuming coefficients already < 2q
fn normalizeAssumingLe2Q(p: Poly) Poly {
var ret = p;
for (0..N) |i| {
ret.cs[i] = le2qModQ(ret.cs[i]);
}
return ret;
}
// Pointwise multiplication in NTT domain (Montgomery form)
fn mulHat(a: Poly, b: Poly) Poly {
var ret: Poly = undefined;
for (0..N) |i| {
ret.cs[i] = montReduceLe2Q(@as(u64, a.cs[i]) * @as(u64, b.cs[i]));
}
return ret;
}
// Forward NTT
fn ntt(p: Poly) Poly {
var ret = p;
ret.nttInPlace();
return ret;
}
// In-place forward NTT
fn nttInPlace(p: *Poly) void {
var k: usize = 0;
var l: usize = N / 2;
while (l > 0) : (l >>= 1) {
var offset: usize = 0;
while (offset < N - l) : (offset += 2 * l) {
k += 1;
const zeta: u64 = zetas[k];
for (offset..offset + l) |j| {
const t = montReduceLe2Q(zeta * @as(u64, p.cs[j + l]));
p.cs[j + l] = p.cs[j] +% (2 * Q -% t);
p.cs[j] +%= t;
}
}
}
}
// Inverse NTT
fn invNTT(p: Poly) Poly {
var ret = p;
ret.invNTTInPlace();
return ret;
}
// In-place inverse NTT
fn invNTTInPlace(p: *Poly) void {
var k: usize = 0;
var l: usize = 1;
while (l < N) : (l <<= 1) {
var offset: usize = 0;
while (offset < N - l) : (offset += 2 * l) {
const zeta: u64 = inv_zetas[k];
k += 1;
for (offset..offset + l) |j| {
const t = p.cs[j];
p.cs[j] = t +% p.cs[j + l];
p.cs[j + l] = montReduceLe2Q(zeta * @as(u64, t +% 256 * Q -% p.cs[j + l]));
}
}
}
for (0..N) |j| {
p.cs[j] = montReduceLe2Q(@as(u64, R_OVER_256) * @as(u64, p.cs[j]));
}
}
/// Apply Power2Round to all coefficients
/// Returns both t0 and t1 polynomials
fn power2RoundPoly(p: Poly) struct { t0: Poly, t1: Poly } {
var t0 = Poly.zero;
var t1 = Poly.zero;
for (0..N) |i| {
const result = power2Round(p.cs[i]);
t0.cs[i] = result.a0_plus_q;
t1.cs[i] = result.a1;
}
return .{ .t0 = t0, .t1 = t1 };
}
// Check if infinity norm exceeds bound
fn exceeds(p: Poly, bound: u32) bool {
var result: u32 = 0;
for (0..N) |i| {
const x = @as(i32, @intCast((Q - 1) / 2)) - @as(i32, @intCast(p.cs[i]));
const abs_x = x ^ (x >> 31);
const norm = @as(i32, @intCast((Q - 1) / 2)) - abs_x;
const exceeds_bit = @intFromBool(@as(u32, @intCast(norm)) >= bound);
result |= exceeds_bit;
}
return result != 0;
}
};
fn PolyVec(comptime len: u8) type {
return struct {
ps: [len]Poly,
const Self = @This();
const zero: Self = .{ .ps = .{Poly.zero} ** len };
/// Apply a unary operation to each polynomial in the vector
fn map(v: Self, comptime op: fn (Poly) Poly) Self {
var ret: Self = undefined;
inline for (0..len) |i| {
ret.ps[i] = op(v.ps[i]);
}
return ret;
}
/// Apply a binary operation pairwise to two vectors
fn mapBinary(a: Self, b: Self, comptime op: fn (Poly, Poly) Poly) Self {
var ret: Self = undefined;
inline for (0..len) |i| {
ret.ps[i] = op(a.ps[i], b.ps[i]);
}
return ret;
}
/// Apply a binary operation between a vector and a scalar polynomial
fn mapBinaryPoly(v: Self, scalar: Poly, comptime op: fn (Poly, Poly) Poly) Self {
var ret: Self = undefined;
inline for (0..len) |i| {
ret.ps[i] = op(v.ps[i], scalar);
}
return ret;
}
fn add(a: Self, b: Self) Self {
return mapBinary(a, b, Poly.add);
}
fn sub(a: Self, b: Self) Self {
return mapBinary(a, b, Poly.sub);
}
fn ntt(v: Self) Self {
return map(v, Poly.ntt);
}
fn invNTT(v: Self) Self {
return map(v, Poly.invNTT);
}
fn normalize(v: Self) Self {
return map(v, Poly.normalize);
}
fn reduceLe2Q(v: Self) Self {
return map(v, Poly.reduceLe2Q);
}
fn normalizeAssumingLe2Q(v: Self) Self {
return map(v, Poly.normalizeAssumingLe2Q);
}
// Check if any polynomial in the vector exceeds the bound
fn exceeds(v: Self, bound: u32) bool {
var result = false;
for (0..len) |i| {
result = result or v.ps[i].exceeds(bound);
}
return result;
}
/// Apply Power2Round to each polynomial in the vector
/// Returns both t0 and t1 vectors
fn power2Round(v: Self, t0_out: *Self) Self {
var t1: Self = undefined;
for (0..len) |i| {
const result = v.ps[i].power2RoundPoly();
t0_out.ps[i] = result.t0;
t1.ps[i] = result.t1;
}
return t1;
}
/// Generic packing function for vectors
fn packWith(
v: Self,
buf: []u8,
comptime poly_size: usize,
comptime pack_fn: fn (Poly, []u8) void,
) void {
inline for (0..len) |i| {
const offset = i * poly_size;
pack_fn(v.ps[i], buf[offset..][0..poly_size]);
}
}
/// Generic unpacking function for vectors
fn unpackWith(
comptime poly_size: usize,
comptime unpack_fn: fn ([]const u8) Poly,
buf: []const u8,
) Self {
var result: Self = undefined;
inline for (0..len) |i| {
const offset = i * poly_size;
result.ps[i] = unpack_fn(buf[offset..][0..poly_size]);
}
return result;
}
/// Pack T1 vector to bytes
fn packT1(v: Self, buf: []u8) void {
const poly_size = (N * (Q_BITS - D)) / 8;
packWith(v, buf, poly_size, polyPackT1);
}
/// Unpack T1 vector from bytes
fn unpackT1(bytes: []const u8) Self {
const poly_size = (N * (Q_BITS - D)) / 8;
return unpackWith(poly_size, polyUnpackT1, bytes);
}
/// Pack T0 vector to bytes
fn packT0(v: Self, buf: []u8) void {
const poly_size = (N * D) / 8;
packWith(v, buf, poly_size, polyPackT0);
}
/// Unpack T0 vector from bytes
fn unpackT0(buf: []const u8) Self {
const poly_size = (N * D) / 8;
return unpackWith(poly_size, polyUnpackT0, buf);
}
/// Pack vector with coefficients in [-eta, eta]
fn packLeqEta(v: Self, comptime eta: u8, buf: []u8) void {
const poly_size = if (eta == 2) 96 else 128;
const pack_fn = struct {
fn pack(p: Poly, b: []u8) void {
polyPackLeqEta(p, eta, b);
}
}.pack;
packWith(v, buf, poly_size, pack_fn);
}
/// Unpack vector with coefficients in [-eta, eta]
fn unpackLeqEta(comptime eta: u8, buf: []const u8) Self {
const poly_size = if (eta == 2) 96 else 128;
const unpack_fn = struct {
fn unpack(b: []const u8) Poly {
return polyUnpackLeqEta(eta, b);
}
}.unpack;
return unpackWith(poly_size, unpack_fn, buf);
}
/// Pack vector of polynomials with coefficients < gamma1
fn packLeGamma1(v: Self, comptime gamma1_bits: u8, buf: []u8) void {
const poly_size = ((gamma1_bits + 1) * N) / 8;
const pack_fn = struct {
fn pack(p: Poly, b: []u8) void {
polyPackLeGamma1(p, gamma1_bits, b);
}
}.pack;
packWith(v, buf, poly_size, pack_fn);
}
/// Unpack vector of polynomials with coefficients < gamma1
fn unpackLeGamma1(comptime gamma1_bits: u8, buf: []const u8) Self {
const poly_size = ((gamma1_bits + 1) * N) / 8;
const unpack_fn = struct {
fn unpack(b: []const u8) Poly {
return polyUnpackLeGamma1(gamma1_bits, b);
}
}.unpack;
return unpackWith(poly_size, unpack_fn, buf);
}
/// Pack high bits w1 for signature verification
fn packW1(v: Self, comptime gamma1_bits: u8, buf: []u8) void {
const poly_size = (N * (Q_BITS - gamma1_bits)) / 8;
const pack_fn = struct {
fn pack(p: Poly, b: []u8) void {
polyPackW1(p, gamma1_bits, b);
}
}.pack;
packWith(v, buf, poly_size, pack_fn);
}
/// Decompose each polynomial in the vector into high and low bits
fn decomposeVec(v: Self, comptime gamma2: u32, w0_out: *Self) Self {
var w1: Self = undefined;
for (0..len) |i| {
for (0..N) |j| {
const r = decompose(v.ps[i].cs[j], gamma2);
w0_out.ps[i].cs[j] = r.a0_plus_q;
w1.ps[i].cs[j] = r.a1;
}
}
return w1;
}
/// Create hints for vector, returns hint population count
fn makeHintVec(w0mcs2pct0: Self, w1: Self, comptime gamma2: u32) struct { hint: Self, pop: u32 } {
var hint: Self = undefined;
var pop: u32 = 0;
for (0..len) |i| {
const result = polyMakeHint(w0mcs2pct0.ps[i], w1.ps[i], gamma2);
hint.ps[i] = result.hint;
pop += result.count;
}
return .{ .hint = hint, .pop = pop };
}
/// Apply hints to recover high bits
fn useHint(v: Self, hint: Self, comptime gamma2: u32) Self {
var result: Self = undefined;
for (0..len) |i| {
result.ps[i] = polyUseHint(v.ps[i], hint.ps[i], gamma2);
}
return result;
}
/// Multiply vector by 2^D (left shift)
fn mulBy2toD(v: Self) Self {
var result: Self = undefined;
for (0..len) |i| {
for (0..N) |j| {
result.ps[i].cs[j] = v.ps[i].cs[j] << D;
}
}
return result;
}
/// Sample vector with coefficients uniformly in (-gamma1, gamma1]
/// Wraps expandMask (FIPS 204: ExpandMask)
fn deriveUniformLeGamma1(comptime gamma1_bits: u8, seed: *const [64]u8, nonce: u16) Self {
var result: Self = undefined;
for (0..len) |i| {
result.ps[i] = expandMask(gamma1_bits, seed, nonce + @as(u16, @intCast(i)));
}
return result;
}
/// Pack hints into bytes
/// Format: for each polynomial, find positions where hint[i]=1, encode those positions
fn packHint(v: Self, comptime omega: u16, buf: []u8) bool {
var idx: usize = 0;
var count: u32 = 0;
for (0..len) |i| {
for (0..N) |j| {
if (v.ps[i].cs[j] != 0) {
count += 1;
}
}
}
if (count > omega) {
return false;
}
// Hint encoding format per FIPS 204:
// First omega bytes: positions of set bits across all polynomials
// Last len bytes: boundary indices showing where each polynomial's hints end
for (0..len) |i| {
for (0..N) |j| {
if (v.ps[i].cs[j] != 0) {
buf[idx] = @intCast(j);
idx += 1;
}
}
buf[omega + i] = @intCast(idx);
}
while (idx < omega) : (idx += 1) {
buf[idx] = 0;
}
return true;
}
/// Unpack hints from bytes
fn unpackHint(comptime omega: u16, buf: []const u8) ?Self {
var result: Self = .{ .ps = .{Poly.zero} ** len };
var prev_sop: u8 = 0; // previous switch-over-point
for (0..len) |i| {
const sop = buf[omega + i]; // switch-over-point
if (sop < prev_sop or sop > omega) {
return null; // ensures switch-over-points are increasing
}
var j = prev_sop;
while (j < sop) : (j += 1) {
// Validation: indices must be strictly increasing within each polynomial
if (j > prev_sop and buf[j] <= buf[j - 1]) {
return null;
}
const pos = buf[j];
if (pos >= N) {
return null;
}
result.ps[i].cs[pos] = 1;
}
prev_sop = sop;
}
var j = prev_sop;
while (j < omega) : (j += 1) {
if (buf[j] != 0) {
return null;
}
}
return result;
}
};
}
// Matrix of k x l polynomials
fn Mat(comptime k: u8, comptime l: u8) type {
return struct {
rows: [k]PolyVec(l),
const Self = @This();
const VecL = PolyVec(l);
const VecK = PolyVec(k);
/// Expand matrix A from seed rho using SHAKE-128
/// This is the ExpandA function from FIPS 204
fn derive(rho: *const [32]u8) Self {
var m: Self = undefined;
for (0..k) |i| {
if (i + 1 < k) {
@prefetch(&m.rows[i + 1], .{ .rw = .write, .locality = 2 });
}
for (0..l) |j| {
// Nonce is i*256 + j
const nonce: u16 = (@as(u16, @intCast(i)) << 8) | @as(u16, @intCast(j));
m.rows[i].ps[j] = polyDeriveUniform(rho, nonce);
}
}
return m;
}
/// Multiply matrix by vector in NTT domain and return result in regular domain.
/// Takes a vector in NTT form and returns the product in regular form.
fn mulVec(self: Self, v_hat: VecL) VecK {
var result = VecK.zero;
for (0..k) |i| {
result.ps[i] = dotHat(l, self.rows[i], v_hat);
result.ps[i] = result.ps[i].reduceLe2Q();
result.ps[i] = result.ps[i].invNTT();
}
return result;
}
/// Multiply matrix by vector in NTT domain and return result in NTT domain.
/// Takes a vector in NTT form and returns the product in NTT form.
fn mulVecHat(self: Self, v_hat: VecL) VecK {
var result: VecK = undefined;
for (0..k) |i| {
result.ps[i] = dotHat(l, self.rows[i], v_hat);
}
return result;
}
};
}
// Dot product in NTT domain
fn dotHat(comptime len: u8, a: PolyVec(len), b: PolyVec(len)) Poly {
var ret = Poly.zero;
for (0..len) |i| {
const prod = a.ps[i].mulHat(b.ps[i]);
ret = ret.add(prod);
}
return ret;
}
// Modular arithmetic operations
// Reduce x to [0, 2q) using the fact that 2^23 = 2^13 - 1 (mod q)
fn le2Q(x: u32) u32 {
// Write x = x1 * 2^23 + x2 with x2 < 2^23 and x1 < 2^9
// Then x = x2 + x1 * 2^13 - x1 (mod q)
// and x2 + x1 * 2^13 - x1 <= 2^23 + 2^13 < 2q
const x1 = x >> 23;
const x2 = x & 0x7FFFFF; // 2^23 - 1
return x2 +% (x1 << 13) -% x1;
}
// Reduce x to [0, q)
fn modQ(x: u32) u32 {
return le2qModQ(le2Q(x));
}
// Given x < 2q, reduce to [0, q)
fn le2qModQ(x: u32) u32 {
const r = x -% Q;
const mask = signMask(u32, r);
return r +% (mask & Q);
}
// Montgomery reduction: for x < q*2^32, return y < 2q where y ≡ x*R^(-1) (mod q)
// where R = 2^32. This is used for efficient modular multiplication in NTT operations.
fn montReduceLe2Q(x: u64) u32 {
const m = (x *% Q_INV) & 0xffffffff;
return @truncate((x +% m * @as(u64, Q)) >> 32);
}
// Precomputed zetas for NTT (Montgomery form)
// zetas[i] = zeta^brv(i) * R mod q
const zetas = computeZetas();
fn computeZetas() [N]u32 {
@setEvalBranchQuota(100000);
var ret: [N]u32 = undefined;
for (0..N) |i| {
const brv_i = @bitReverse(@as(u8, @intCast(i)));
const power = modularPow(u32, ZETA, brv_i, Q);
ret[i] = toMont(power);
}
return ret;
}
// Precomputed inverse zetas for inverse NTT
const inv_zetas = computeInvZetas();
fn computeInvZetas() [N]u32 {
@setEvalBranchQuota(100000);
var ret: [N]u32 = undefined;
const inv_zeta = modularInverse(u32, ZETA, Q);
for (0..N) |i| {
const idx = 255 - i;
const brv_idx = @bitReverse(@as(u8, @intCast(idx)));
// Exponent is -(brv_idx - 256) = 256 - brv_idx
const exp: u32 = @as(u32, 256) - brv_idx;
// Compute inv_zeta^exp
const power = modularPow(u32, inv_zeta, exp, Q);
// Convert to Montgomery form
ret[i] = toMont(power);
}
return ret;
}
// Convert to Montgomery form: x -> x * R mod q
fn toMont(x: u32) u32 {
// R = 2^32, R mod q can be computed as:
// 2^32 mod q = 2^32 mod (2^23 - 2^13 + 1)
// Using the identity 2^23 = 2^13 - 1 (mod q), we can reduce 2^32
// But it's easier to just do: return montReduce(x * R^2 mod q)
// where R^2 mod q is precomputed
// Computing R^2 mod q:
// R = 2^32, so R^2 = 2^64
// We can compute this by noting that R mod q first:
// 2^32 = 2^32 mod q
// But let's use a simpler approach: multiply x by R in the Montgomery domain
// Actually, the simplest is: x * R mod q = montReduceLe2Q(x * R^2 mod q)
// Precompute R^2 mod q at comptime
const r_mod_q = comptime blk: {
// 2^32 mod q - compute by successive squaring
var r: u64 = 1;
for (0..32) |_| {
r = (r * 2) % Q;
}
break :blk @as(u32, @intCast(r));
};
const r2_mod_q = comptime blk: {
const r = @as(u64, r_mod_q);
break :blk @as(u32, @intCast((r * r) % Q));
};
return montReduceLe2Q(@as(u64, x) * @as(u64, r2_mod_q));
}
/// Splits 0 ≤ a < Q into a0 and a1 with a = a1*2^D + a0
/// and -2^(D-1) < a0 ≤ 2^(D-1). Returns a0 + Q and a1.
/// FIPS 204: Power2Round (Algorithm 19)
fn power2Round(a: u32) struct { a0_plus_q: u32, a1: u32 } {
// We effectively compute a0 = a mod± 2^D
// and a1 = (a - a0) / 2^D
var a0 = a & ((1 << D) - 1); // a mod 2^D
// a0 is one of 0, 1, ..., 2^(D-1)-1, 2^(D-1), 2^(D-1)+1, ..., 2^D-1
a0 -%= (1 << (D - 1)) + 1;
// now a0 is -2^(D-1)-1, -2^(D-1), ..., -2, -1, 0, ..., 2^(D-1)-2
// Next, add 2^D to those a0 that are negative (seen as i32)
a0 +%= @as(u32, @bitCast(@as(i32, @bitCast(a0)) >> 31)) & (1 << D);
// now a0 is 2^(D-1)-1, 2^(D-1), ..., 2^D-2, 2^D-1, 0, ..., 2^(D-1)-2
a0 -%= (1 << (D - 1)) - 1;
// now a0 is 0, 1, 2, ..., 2^(D-1)-1, 2^(D-1), -2^(D-1)+1, ..., -1
const a0_plus_q = Q +% a0;
const a1 = (a -% a0) >> D;
return .{ .a0_plus_q = a0_plus_q, .a1 = a1 };
}
/// Splits 0 ≤ a < q into a0 and a1 with a = a1*alpha + a0 with -alpha/2 < a0 ≤ alpha/2,
/// except when we would have a1 = (q-1)/alpha in which case a1=0 is taken
/// and -alpha/2 ≤ a0 < 0. Returns a0 + q. Note 0 ≤ a1 < (q-1)/alpha.
/// Recall alpha = 2*gamma2.
fn decompose(a: u32, comptime gamma2: u32) struct { a0_plus_q: u32, a1: u32 } {
const alpha = 2 * gamma2;
// a1 = ⌈a / 128⌉
var a1 = (a + 127) >> 7;
if (alpha == 523776) {
// For ML-DSA-87: gamma2 = 261888, alpha = 523776
// 1025/2^22 is close enough to 1/4092 so that a1 becomes a/alpha rounded down
a1 = ((a1 * 1025 + (1 << 21)) >> 22);
// For the corner-case a1 = (q-1)/alpha = 16, we have to set a1=0
a1 &= 15;
} else if (alpha == 190464) {
// For ML-DSA-65: gamma2 = 95232, alpha = 190464
// 11275/2^24 is close enough to 1/1488 so that a1 becomes a/alpha rounded down
a1 = ((a1 * 11275) + (1 << 23)) >> 24;
// For the corner-case a1 = (q-1)/alpha = 44, we have to set a1=0
a1 ^= @as(u32, @bitCast(@as(i32, @bitCast(43 -% a1)) >> 31)) & a1;
} else {
@compileError("unsupported gamma2/alpha value");
}
var a0_plus_q = a -% a1 * alpha;
// In the corner-case, when we set a1=0, we will incorrectly
// have a0 > (q-1)/2 and we'll need to subtract q. As we
// return a0 + q, that comes down to adding q if a0 < (q-1)/2.
a0_plus_q +%= @as(u32, @bitCast(@as(i32, @bitCast(a0_plus_q -% (Q - 1) / 2)) >> 31)) & Q;
return .{ .a0_plus_q = a0_plus_q, .a1 = a1 };
}
/// Creates a hint bit to help recover high bits after a small perturbation.
/// Given:
/// - z0: the modified low bits (r0 - f mod Q) where f is small
/// - r1: the original high bits
/// Returns 1 if a hint is needed, 0 otherwise.
///
/// This implements makeHint from FIPS 204. The hint helps recover r1 from
/// r' = r - f without knowing f explicitly.
fn makeHint(z0: u32, r1: u32, comptime gamma2: u32) u32 {
// If -alpha/2 < r0 - f <= alpha/2, then r1*alpha + r0 - f is a valid
// decomposition of r' with the restrictions of decompose() and so r'1 = r1.
// So the hint should be 0. This is covered by the first two inequalities.
// There is one other case: if r0 - f = -alpha/2, then r1*alpha + r0 - f is
// also a valid decomposition if r1 = 0. In the other cases a one is carried
// and the hint should be 1.
const cond1 = @intFromBool(z0 <= gamma2);
const cond2 = @intFromBool(z0 > Q - gamma2);
const eq_gamma2 = @intFromBool(z0 == Q - gamma2);
const r1_is_zero = @intFromBool(r1 == 0);
const cond3 = eq_gamma2 & r1_is_zero;
return 1 - (cond1 | cond2 | cond3);
}
/// Uses a hint to reconstruct high bits from a perturbed value.
/// Given:
/// - rp: the perturbed value (r' = r - f)
/// - hint: the hint bit from makeHint
/// Returns the reconstructed high bits r1.
///
/// This implements useHint from FIPS 204.
fn useHint(rp: u32, hint: u32, comptime gamma2: u32) u32 {
const decomp = decompose(rp, gamma2);
const rp0_plus_q = decomp.a0_plus_q;
var rp1 = decomp.a1;
if (hint == 0) {
return rp1;
}
// Depending on gamma2, handle the adjustment differently
if (gamma2 == 261888) {
// ML-DSA-65 and ML-DSA-87: max r1 is 15
if (rp0_plus_q > Q) {
rp1 = (rp1 + 1) & 15;
} else {
rp1 = (rp1 -% 1) & 15;
}
} else if (gamma2 == 95232) {
// ML-DSA-44: max r1 is 43
if (rp0_plus_q > Q) {
if (rp1 == 43) {
rp1 = 0;
} else {
rp1 += 1;
}
} else {
if (rp1 == 0) {
rp1 = 43;
} else {
rp1 -= 1;
}
}
} else {
@compileError("unsupported gamma2 value");
}
return rp1;
}
/// Creates a hint polynomial for the difference between perturbed and original high bits.
/// Returns the number of hint bits set to 1 (the population count).
///
/// This is used during signature generation to create hints that help verification
/// recover the high bits without access to the secret.
fn polyMakeHint(p0: Poly, p1: Poly, comptime gamma2: u32) struct { hint: Poly, count: u32 } {
var hint = Poly.zero;
var count: u32 = 0;
for (0..N) |i| {
const h = makeHint(p0.cs[i], p1.cs[i], gamma2);
hint.cs[i] = h;
count += h;
}
return .{ .hint = hint, .count = count };
}
/// Applies hints to reconstruct high bits from a perturbed polynomial.
///
/// This is used during signature verification to recover the high bits
/// using the hints provided in the signature.
fn polyUseHint(q: Poly, hint: Poly, comptime gamma2: u32) Poly {
var result = Poly.zero;
for (0..N) |i| {
result.cs[i] = useHint(q.cs[i], hint.cs[i], gamma2);
}
return result;
}
/// Pack polynomial with coefficients in [Q-eta, Q+eta] into bytes.
/// For eta=2: packs coefficients into 3 bits each (96 bytes total)
/// For eta=4: packs coefficients into 4 bits each (128 bytes total)
/// Assumes coefficients are not normalized, but in [q-η, q+η].
fn polyPackLeqEta(p: Poly, comptime eta: u8, buf: []u8) void {
comptime {
if (eta != 2 and eta != 4) {
@compileError("eta must be 2 or 4");
}
}
if (eta == 2) {
// 3 bits per coefficient: pack 8 coefficients into 3 bytes
var j: usize = 0;
var i: usize = 0;
while (i < buf.len) : (i += 3) {
const c0 = Q + eta - p.cs[j];
const c1 = Q + eta - p.cs[j + 1];
const c2 = Q + eta - p.cs[j + 2];
const c3 = Q + eta - p.cs[j + 3];
const c4 = Q + eta - p.cs[j + 4];
const c5 = Q + eta - p.cs[j + 5];
const c6 = Q + eta - p.cs[j + 6];
const c7 = Q + eta - p.cs[j + 7];
buf[i] = @truncate(c0 | (c1 << 3) | (c2 << 6));
buf[i + 1] = @truncate((c2 >> 2) | (c3 << 1) | (c4 << 4) | (c5 << 7));
buf[i + 2] = @truncate((c5 >> 1) | (c6 << 2) | (c7 << 5));
j += 8;
}
} else { // eta == 4
// 4 bits per coefficient: pack 2 coefficients into 1 byte
var j: usize = 0;
for (0..buf.len) |i| {
const c0 = Q + eta - p.cs[j];
const c1 = Q + eta - p.cs[j + 1];
buf[i] = @truncate(c0 | (c1 << 4));
j += 2;
}
}
}
/// Unpack polynomial with coefficients in [Q-eta, Q+eta] from bytes.
/// Output coefficients will not be normalized, but in [q-η, q+η].
fn polyUnpackLeqEta(comptime eta: u8, buf: []const u8) Poly {
comptime {