1use crate::kernel_args as args;
8
9pub(crate) const Q: i32 = 8_380_417;
10const QINV: i32 = 58_728_449; const ZETA: i64 = 1753; const MONT: i64 = 4_193_792;
14const N: usize = 256;
15
16#[inline]
18pub(crate) fn montgomery_reduce(a: i64) -> i32 {
19 let t = (a as i32).wrapping_mul(QINV) as i64;
20 ((a - t * Q as i64) >> 32) as i32
21}
22
23pub(crate) const ZETAS: [i32; 256] = zeta_table();
25
26const fn zeta_table() -> [i32; 256] {
27 let mut pow = [1i64; 256];
28 let mut i = 1;
29 while i < 256 {
30 pow[i] = pow[i - 1] * ZETA % Q as i64;
31 i += 1;
32 }
33 let mut z = [0i32; 256];
34 let mut i = 0;
35 while i < 256 {
36 let mut v = pow[(i as u8).reverse_bits() as usize] * MONT % Q as i64;
37 if v > Q as i64 / 2 {
38 v -= Q as i64;
39 }
40 z[i] = v as i32;
41 i += 1;
42 }
43 z
44}
45
46pub(crate) fn ntt(a: &mut [i32; N]) {
51 let zetas = &ZETAS;
52 let mut k = 0usize;
53 let mut len = 128usize;
54 while len > 0 {
55 let mut start = 0usize;
56 while start < N {
57 k += 1;
58 let zeta = zetas[k] as i64;
59 for j in start..start + len {
60 let t = montgomery_reduce(zeta * a[j + len] as i64);
61 a[j + len] = a[j] - t;
62 a[j] = a[j] + t;
63 }
64 start += 2 * len;
65 }
66 len >>= 1;
67 }
68}
69
70const INVNTT_F: i64 = 41_978; pub(crate) fn invntt_tomont(a: &mut [i32; N]) {
76 let zetas = &ZETAS;
77 let mut k = 256usize;
78 let mut len = 1usize;
79 while len < N {
80 let mut start = 0usize;
81 while start < N {
82 k -= 1;
83 let zeta = -(zetas[k] as i64);
84 for j in start..start + len {
85 let t = a[j];
86 a[j] = t + a[j + len];
87 a[j + len] = t - a[j + len];
88 a[j + len] = montgomery_reduce(zeta * a[j + len] as i64);
89 }
90 start += 2 * len;
91 }
92 len <<= 1;
93 }
94 for x in a.iter_mut() {
95 *x = montgomery_reduce(INVNTT_F * *x as i64);
96 }
97}
98
99#[inline]
102pub(crate) fn reduce32(a: i32) -> i32 {
103 let t = (a + (1 << 22)) >> 23;
104 a - t * Q
105}
106
107pub(crate) fn to_normal_domain(acc: &mut [i32; N]) {
111 for x in acc.iter_mut() {
112 *x = reduce32(*x);
113 }
114 invntt_tomont(acc);
115}
116
117pub(crate) fn pointwise_montgomery(a: &[i32; N], b: &[i32; N]) -> [i32; N] {
119 std::array::from_fn(|i| montgomery_reduce(a[i] as i64 * b[i] as i64))
123}
124
125#[inline]
127pub(crate) fn freeze(a: i32) -> i32 {
128 caddq(reduce32(a))
129}
130
131#[inline]
133pub(crate) fn caddq(a: i32) -> i32 {
134 a + ((a >> 31) & Q)
135}
136
137pub(crate) const D: i32 = 13; pub(crate) const GAMMA1: i32 = 1 << 19; pub(crate) const GAMMA2: i32 = (Q - 1) / 32; pub(crate) fn power2round(r: i32) -> (i32, i32) {
146 let r = freeze(r);
147 let r1 = (r + (1 << (D - 1)) - 1) >> D;
148 let r0 = r - (r1 << D);
149 (r1, r0)
150}
151
152pub(crate) fn decompose(r: i32) -> (i32, i32) {
155 let r = freeze(r);
156 let mut a1 = (r + 127) >> 7;
157 a1 = (a1 * 1025 + (1 << 21)) >> 22;
158 a1 &= 15;
159 let mut a0 = r - a1 * 2 * GAMMA2;
160 a0 -= (((Q - 1) / 2 - a0) >> 31) & Q;
161 (a1, a0)
162}
163
164pub(crate) fn highbits(r: i32) -> i32 {
166 decompose(r).0
167}
168pub(crate) fn lowbits(r: i32) -> i32 {
169 decompose(r).1
170}
171
172pub(crate) fn make_hint(z: i32, r: i32) -> u8 {
174 (highbits(r) != highbits(r + z)) as u8
175}
176
177pub(crate) fn use_hint(h: u8, r: i32) -> i32 {
179 const M: i32 = 16; let (r1, r0) = decompose(r);
181 if h == 0 {
182 r1
183 } else if r0 > 0 {
184 (r1 + 1) % M
185 } else {
186 (r1 - 1 + M) % M
187 }
188}
189
190pub(crate) const MK: usize = 6; pub(crate) const ML: usize = 5; pub(crate) const ETA: i32 = 4;
194pub(crate) const TAU: usize = 49;
195
196type Poly = [i32; N];
197
198fn rej_ntt_poly(seed: &[u8]) -> Poly {
203 let mut st = crate::keccak::shake_absorb(seed, 168);
204 let mut buf = [0u8; 168];
205 crate::keccak::shake_squeeze_block(&st, &mut buf, 168);
206 let mut pos = 0;
207 let mut a = [0i32; N];
208 let mut ctr = 0;
209 while ctr < N {
210 if pos + 3 > 168 {
211 crate::keccak::keccak_permute(&mut st);
212 crate::keccak::shake_squeeze_block(&st, &mut buf, 168);
213 pos = 0;
214 }
215 let d = (buf[pos] as u32)
216 | ((buf[pos + 1] as u32) << 8)
217 | (((buf[pos + 2] as u32) & 0x7f) << 16);
218 pos += 3;
219 if d < Q as u32 {
220 a[ctr] = d as i32;
221 ctr += 1;
222 }
223 }
224 a
225}
226
227fn rej_bounded_poly(seed: &[u8]) -> Poly {
230 let mut st = crate::keccak::shake_absorb(seed, 136);
231 let mut buf = [0u8; 136];
232 crate::keccak::shake_squeeze_block(&st, &mut buf, 136);
233 let mut pos = 0;
234 let mut a = [0i32; N];
235 let mut ctr = 0;
236 while ctr < N {
237 if pos >= 136 {
238 crate::keccak::keccak_permute(&mut st);
239 crate::keccak::shake_squeeze_block(&st, &mut buf, 136);
240 pos = 0;
241 }
242 let b = buf[pos];
243 pos += 1;
244 let t0 = (b & 15) as i32;
245 let t1 = (b >> 4) as i32;
246 if t0 < 9 {
247 a[ctr] = ETA - t0;
248 ctr += 1;
249 }
250 if t1 < 9 && ctr < N {
251 a[ctr] = ETA - t1;
252 ctr += 1;
253 }
254 }
255 a
256}
257
258pub(crate) fn expand_a(rho: &[u8]) -> Vec<Vec<Poly>> {
264 #[cfg(target_arch = "x86_64")]
265 {
266 if std::is_x86_feature_detected!("avx2") {
267 const ENTRIES: usize = MK * ML;
268 let coords = &ENTRY_COORDS;
269 let mut flat = vec![[0i32; N]; ENTRIES];
270 let mut e = 0;
271 while e + 4 <= ENTRIES {
272 let blocks: [[u8; 168]; 4] = std::array::from_fn(|l| {
273 let (r, c) = coords[e + l];
274 mldsa_expand_xof_block(rho, c as u8, r as u8)
275 });
276 let mut accs: [Vec<i32>; 4] = std::array::from_fn(|_| Vec::with_capacity(256));
277 let mut st = unsafe { crate::keccak::shake128_x4_absorb_once(&blocks) };
278 loop {
279 let outb = unsafe { crate::keccak::shake128_x4_squeeze_block(&st) };
280 let mut done = true;
281 for (l, acc) in accs.iter_mut().enumerate() {
282 if acc.len() < N {
283 mldsa_reject_ntt_block(&outb[l], acc);
284 }
285 if acc.len() < N {
286 done = false;
287 }
288 }
289 if done {
290 break;
291 }
292 unsafe { crate::keccak::keccak_f1600_x4(&mut st) };
293 }
294 for (l, acc) in accs.iter().enumerate() {
295 let (r, c) = coords[e + l];
296 flat[r * ML + c].copy_from_slice(&acc[..N]);
297 }
298 e += 4;
299 }
300 while e < ENTRIES {
301 let (r, c) = coords[e];
302 let mut seed = rho[..32].to_vec();
303 seed.push(c as u8);
304 seed.push(r as u8);
305 flat[r * ML + c] = rej_ntt_poly(&seed);
306 e += 1;
307 }
308 return (0..MK)
309 .map(|r| (0..ML).map(|c| flat[r * ML + c]).collect())
310 .collect();
311 }
312 }
313 expand_a_scalar(rho)
314}
315
316#[cfg_attr(not(target_arch = "x86_64"), allow(dead_code))]
318pub(crate) const ENTRY_COORDS: [(usize, usize); MK * ML] = entry_coords();
319
320const fn entry_coords() -> [(usize, usize); MK * ML] {
321 let mut coords = [(0, 0); MK * ML];
322 let mut e = 0;
323 while e < MK * ML {
324 coords[e] = (e / ML, e % ML);
325 e += 1;
326 }
327 coords
328}
329
330fn expand_a_scalar(rho: &[u8]) -> Vec<Vec<Poly>> {
331 (0..MK)
332 .map(|r| {
333 (0..ML)
334 .map(|s| {
335 let mut seed = rho.to_vec();
336 seed.push(s as u8);
337 seed.push(r as u8);
338 rej_ntt_poly(&seed)
339 })
340 .collect()
341 })
342 .collect()
343}
344
345#[cfg(target_arch = "x86_64")]
348#[inline]
349fn mldsa_expand_xof_block(rho: &[u8], s: u8, r: u8) -> [u8; 168] {
350 let mut blk = [0u8; 168];
351 blk[..32].copy_from_slice(&rho[..32]);
352 blk[32] = s;
353 blk[33] = r;
354 blk[34] = 0x1f;
355 blk[167] |= 0x80;
356 blk
357}
358
359#[cfg(target_arch = "x86_64")]
362#[inline]
363fn mldsa_reject_ntt_block(buf: &[u8; 168], out: &mut Vec<i32>) {
364 let q = Q as u32;
365 let mut k = 0;
366 while k + 3 <= 168 && out.len() < N {
367 let d = (buf[k] as u32) | ((buf[k + 1] as u32) << 8) | (((buf[k + 2] as u32) & 0x7f) << 16);
368 k += 3;
369 if d < q {
370 out.push(d as i32);
371 }
372 }
373}
374
375fn pack_t1(t1: &Poly) -> Vec<u8> {
379 let mut r = vec![0u8; N / 4 * 5];
380 for i in 0..N / 4 {
381 let a = [t1[4 * i], t1[4 * i + 1], t1[4 * i + 2], t1[4 * i + 3]];
382 r[5 * i] = a[0] as u8;
383 r[5 * i + 1] = ((a[0] >> 8) | (a[1] << 2)) as u8;
384 r[5 * i + 2] = ((a[1] >> 6) | (a[2] << 4)) as u8;
385 r[5 * i + 3] = ((a[2] >> 4) | (a[3] << 6)) as u8;
386 r[5 * i + 4] = (a[3] >> 2) as u8;
387 }
388 r
389}
390
391fn pack_eta(p: &Poly) -> Vec<u8> {
393 let mut r = vec![0u8; N / 2];
394 for i in 0..N / 2 {
395 let t0 = (ETA - p[2 * i]) as u8;
396 let t1 = (ETA - p[2 * i + 1]) as u8;
397 r[i] = t0 | (t1 << 4);
398 }
399 r
400}
401
402fn pack_t0(p: &Poly) -> Vec<u8> {
404 let mut r = vec![0u8; N / 8 * 13];
405 for i in 0..N / 8 {
406 let mut t = [0u32; 8];
407 for j in 0..8 {
408 t[j] = ((1 << (D - 1)) - p[8 * i + j]) as u32;
409 }
410 let o = 13 * i;
411 r[o] = t[0] as u8;
412 r[o + 1] = ((t[0] >> 8) | (t[1] << 5)) as u8;
413 r[o + 2] = (t[1] >> 3) as u8;
414 r[o + 3] = ((t[1] >> 11) | (t[2] << 2)) as u8;
415 r[o + 4] = ((t[2] >> 6) | (t[3] << 7)) as u8;
416 r[o + 5] = (t[3] >> 1) as u8;
417 r[o + 6] = ((t[3] >> 9) | (t[4] << 4)) as u8;
418 r[o + 7] = (t[4] >> 4) as u8;
419 r[o + 8] = ((t[4] >> 12) | (t[5] << 1)) as u8;
420 r[o + 9] = ((t[5] >> 7) | (t[6] << 6)) as u8;
421 r[o + 10] = (t[6] >> 2) as u8;
422 r[o + 11] = ((t[6] >> 10) | (t[7] << 3)) as u8;
423 r[o + 12] = (t[7] >> 5) as u8;
424 }
425 r
426}
427
428pub const PK_BYTES: usize = 32 + MK * 320;
432pub const SK_BYTES: usize = 32 + 32 + 64 + ML * 128 + MK * 128 + MK * 416;
434
435pub fn keygen(seed: &[u8; 32]) -> (Vec<u8>, Vec<u8>) {
437 let mut h_in = seed.to_vec();
438 h_in.push(MK as u8);
439 h_in.push(ML as u8);
440 let hash = crate::keccak::shake256_bytes(&h_in, 128);
441 let rho = &hash[0..32];
442 let rho_prime = &hash[32..96];
443 let k_key = &hash[96..128];
444
445 let a_hat = expand_a(rho);
446 let s1: Vec<Poly> = (0..ML)
447 .map(|i| {
448 let mut seed = rho_prime.to_vec();
449 seed.extend_from_slice(&(i as u16).to_le_bytes());
450 rej_bounded_poly(&seed)
451 })
452 .collect();
453 let s2: Vec<Poly> = (0..MK)
454 .map(|i| {
455 let mut seed = rho_prime.to_vec();
456 seed.extend_from_slice(&((ML + i) as u16).to_le_bytes());
457 rej_bounded_poly(&seed)
458 })
459 .collect();
460
461 let s1_hat: Vec<Poly> = s1
462 .iter()
463 .map(|p| {
464 let mut q = *p;
465 ntt(&mut q);
466 q
467 })
468 .collect();
469 let mut t1 = vec![[0i32; N]; MK];
470 let mut t0 = vec![[0i32; N]; MK];
471 for i in 0..MK {
472 let mut acc = [0i32; N];
473 for j in 0..ML {
474 let prod = pointwise_montgomery(&a_hat[i][j], &s1_hat[j]);
475 for c in 0..N {
476 acc[c] += prod[c];
477 }
478 }
479 to_normal_domain(&mut acc);
480 for c in 0..N {
481 let t = freeze(acc[c] + s2[i][c]);
482 let (r1, r0) = power2round(t);
483 t1[i][c] = r1;
484 t0[i][c] = r0;
485 }
486 }
487
488 let mut pk = rho.to_vec();
489 for poly in &t1 {
490 pk.extend(pack_t1(poly));
491 }
492 let tr = crate::keccak::shake256_bytes(&pk, 64);
493
494 let mut sk = rho.to_vec();
495 sk.extend_from_slice(k_key);
496 sk.extend_from_slice(&tr);
497 for poly in &s1 {
498 sk.extend(pack_eta(poly));
499 }
500 for poly in &s2 {
501 sk.extend(pack_eta(poly));
502 }
503 for poly in &t0 {
504 sk.extend(pack_t0(poly));
505 }
506 (pk, sk)
507}
508
509pub(crate) const BETA: i32 = (TAU as i32) * ETA; pub(crate) const OMEGA: usize = 55;
512const CTILDE: usize = 48; pub const SIG_BYTES: usize = CTILDE + ML * 640 + OMEGA + MK;
515
516#[inline]
519pub(crate) fn to_signed(a: i32) -> i32 {
520 let r = freeze(a);
521 r - (((Q / 2 - r) >> 31) & Q)
522}
523fn inf_norm(p: &Poly) -> i32 {
524 p.iter().map(|&c| to_signed(c).abs()).max().unwrap()
525}
526
527#[inline]
528fn nttp(p: &Poly) -> Poly {
529 let mut q = *p;
530 ntt(&mut q);
531 q
532}
533
534fn unpack_eta(b: &[u8]) -> Poly {
537 std::array::from_fn(|i| {
538 let byte = b[i / 2];
539 let nib = if i % 2 == 0 { byte & 15 } else { byte >> 4 };
540 ETA - nib as i32
541 })
542}
543
544fn unpack_t0(b: &[u8]) -> Poly {
545 let mut r = [0i32; N];
546 for i in 0..N / 8 {
547 let a: Vec<u32> = b[13 * i..13 * i + 13].iter().map(|&x| x as u32).collect();
548 let mut t = [0u32; 8];
549 t[0] = a[0] | (a[1] << 8);
550 t[1] = (a[1] >> 5) | (a[2] << 3) | (a[3] << 11);
551 t[2] = (a[3] >> 2) | (a[4] << 6);
552 t[3] = (a[4] >> 7) | (a[5] << 1) | (a[6] << 9);
553 t[4] = (a[6] >> 4) | (a[7] << 4) | (a[8] << 12);
554 t[5] = (a[8] >> 1) | (a[9] << 7);
555 t[6] = (a[9] >> 6) | (a[10] << 2) | (a[11] << 10);
556 t[7] = (a[11] >> 3) | (a[12] << 5);
557 for j in 0..8 {
558 r[8 * i + j] = (1 << (D - 1)) - (t[j] & 0x1fff) as i32;
559 }
560 }
561 r
562}
563
564fn unpack_t1(b: &[u8]) -> Poly {
565 let mut r = [0i32; N];
566 for i in 0..N / 4 {
567 let a: Vec<u32> = b[5 * i..5 * i + 5].iter().map(|&x| x as u32).collect();
568 r[4 * i] = ((a[0] | (a[1] << 8)) & 0x3ff) as i32;
569 r[4 * i + 1] = (((a[1] >> 2) | (a[2] << 6)) & 0x3ff) as i32;
570 r[4 * i + 2] = (((a[2] >> 4) | (a[3] << 4)) & 0x3ff) as i32;
571 r[4 * i + 3] = (((a[3] >> 6) | (a[4] << 2)) & 0x3ff) as i32;
572 }
573 r
574}
575
576fn unpack_z(b: &[u8]) -> Poly {
577 let mut r = [0i32; N];
578 for i in 0..N / 2 {
579 let a: Vec<u32> = b[5 * i..5 * i + 5].iter().map(|&x| x as u32).collect();
580 let z0 = (a[0] | (a[1] << 8) | (a[2] << 16)) & 0xfffff;
581 let z1 = ((a[2] >> 4) | (a[3] << 4) | (a[4] << 12)) & 0xfffff;
582 r[2 * i] = GAMMA1 - z0 as i32;
583 r[2 * i + 1] = GAMMA1 - z1 as i32;
584 }
585 r
586}
587
588fn unpack_hint(b: &[u8]) -> Option<Vec<Poly>> {
589 let mut h = vec![[0i32; N]; MK];
590 let mut k = 0usize;
591 for i in 0..MK {
592 let cnt = b[OMEGA + i] as usize;
593 if cnt < k || cnt > OMEGA {
594 return None;
595 }
596 for j in k..cnt {
597 if j > k && b[j] <= b[j - 1] {
598 return None; }
600 h[i][b[j] as usize] = 1;
601 }
602 k = cnt;
603 }
604 if b[k..OMEGA].iter().any(|&x| x != 0) {
605 return None; }
607 Some(h)
608}
609
610fn pack_z(p: &Poly) -> Vec<u8> {
613 let mut r = vec![0u8; N / 2 * 5];
614 for i in 0..N / 2 {
615 let t0 = (GAMMA1 - to_signed(p[2 * i])) as u32;
616 let t1 = (GAMMA1 - to_signed(p[2 * i + 1])) as u32;
617 r[5 * i] = t0 as u8;
618 r[5 * i + 1] = (t0 >> 8) as u8;
619 r[5 * i + 2] = ((t0 >> 16) | (t1 << 4)) as u8;
620 r[5 * i + 3] = (t1 >> 4) as u8;
621 r[5 * i + 4] = (t1 >> 12) as u8;
622 }
623 r
624}
625
626fn pack_w1(p: &Poly) -> Vec<u8> {
627 (0..N / 2)
628 .map(|i| (p[2 * i] | (p[2 * i + 1] << 4)) as u8)
629 .collect()
630}
631
632fn pack_hint(h: &[Poly]) -> Vec<u8> {
633 let mut r = vec![0u8; OMEGA + MK];
634 let mut k = 0usize;
635 for (i, poly) in h.iter().enumerate() {
636 for (j, &v) in poly.iter().enumerate() {
637 if v != 0 {
638 r[k] = j as u8;
639 k += 1;
640 }
641 }
642 r[OMEGA + i] = k as u8;
643 }
644 r
645}
646
647fn expand_mask(rho: &[u8], kappa: u16) -> Poly {
650 let mut seed = rho.to_vec();
651 seed.extend_from_slice(&kappa.to_le_bytes());
652 let buf = crate::keccak::shake256_bytes(&seed, N / 2 * 5);
653 let mut a = [0i32; N];
654 for i in 0..N / 2 {
655 let o = 5 * i;
656 let z0 = (buf[o] as u32) | ((buf[o + 1] as u32) << 8) | (((buf[o + 2] as u32) & 0xf) << 16);
657 let z1 =
658 ((buf[o + 2] as u32) >> 4) | ((buf[o + 3] as u32) << 4) | ((buf[o + 4] as u32) << 12);
659 a[2 * i] = GAMMA1 - z0 as i32;
660 a[2 * i + 1] = GAMMA1 - z1 as i32;
661 }
662 a
663}
664
665fn sample_in_ball(seed: &[u8]) -> Poly {
666 let mut st = crate::keccak::shake_absorb(seed, 136);
667 let mut buf = [0u8; 136];
668 crate::keccak::shake_squeeze_block(&st, &mut buf, 136);
669 let signs = u64::from_le_bytes(buf[0..8].try_into().unwrap());
670 let mut pos = 8;
671 let mut c = [0i32; N];
672 let mut sign_idx = 0;
673 for i in (N - TAU)..N {
674 let j = loop {
675 if pos >= 136 {
676 crate::keccak::keccak_permute(&mut st);
677 crate::keccak::shake_squeeze_block(&st, &mut buf, 136);
678 pos = 0;
679 }
680 let candidate = buf[pos] as usize;
681 pos += 1;
682 if candidate <= i {
683 break candidate;
684 }
685 };
686 c[i] = c[j];
687 c[j] = 1 - 2 * (((signs >> sign_idx) & 1) as i32);
688 sign_idx += 1;
689 }
690 c
691}
692
693fn message_representative(m: &[u8], ctx: &[u8]) -> Option<Vec<u8>> {
696 let len = u8::try_from(ctx.len()).ok()?;
697 let mut mp = Vec::with_capacity(2 + ctx.len() + m.len());
698 mp.push(0);
699 mp.push(len);
700 mp.extend_from_slice(ctx);
701 mp.extend_from_slice(m);
702 Some(mp)
703}
704
705fn compute_mu(tr: &[u8], mp: &[u8]) -> Vec<u8> {
707 let mut mu_in = tr.to_vec();
708 mu_in.extend_from_slice(mp);
709 crate::keccak::shake256_bytes(&mu_in, 64)
710}
711
712#[derive(Debug, Clone, Copy, PartialEq, Eq)]
716pub enum SignError {
717 ContextTooLong { len: usize },
719 SecretKeyLength { len: usize },
721 SecretKeyOutOfRange,
723}
724
725impl std::fmt::Display for SignError {
726 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
727 match self {
728 SignError::ContextTooLong { len } => {
729 write!(f, "the context is {len} bytes; FIPS 204 allows at most 255")
730 }
731 SignError::SecretKeyLength { len } => write!(
732 f,
733 "the secret key is {len} bytes; an ML-DSA-65 secret key is {SK_BYTES}"
734 ),
735 SignError::SecretKeyOutOfRange => write!(
736 f,
737 "the secret key holds an s1 or s2 coefficient outside [-{ETA}, {ETA}]"
738 ),
739 }
740 }
741}
742
743impl std::error::Error for SignError {}
744
745struct SecretKey<'a> {
748 rho: &'a [u8],
749 k_key: &'a [u8],
750 tr: &'a [u8],
751 s1: Vec<Poly>,
752 s2: Vec<Poly>,
753 t0: Vec<Poly>,
754}
755
756impl<'a> SecretKey<'a> {
757 fn decode(sk: &'a [u8]) -> Result<Self, SignError> {
758 if sk.len() != SK_BYTES {
759 return Err(SignError::SecretKeyLength { len: sk.len() });
760 }
761 let s1_at = 128;
762 let s2_at = s1_at + ML * 128;
763 let t0_at = s2_at + MK * 128;
764 let eta = |at: usize, count: usize| -> Vec<Poly> {
765 (0..count)
766 .map(|i| unpack_eta(&sk[at + 128 * i..at + 128 * (i + 1)]))
767 .collect()
768 };
769 if !eta_nibbles_in_range(&sk[s1_at..t0_at]) {
770 return Err(SignError::SecretKeyOutOfRange);
771 }
772 Ok(SecretKey {
773 rho: &sk[0..32],
774 k_key: &sk[32..64],
775 tr: &sk[64..128],
776 s1: eta(s1_at, ML),
777 s2: eta(s2_at, MK),
778 t0: (0..MK)
779 .map(|i| unpack_t0(&sk[t0_at + 416 * i..t0_at + 416 * (i + 1)]))
780 .collect(),
781 })
782 }
783}
784
785fn eta_nibbles_in_range(packed: &[u8]) -> bool {
788 let mut over = 0u8;
789 for &b in packed {
790 over |= ((b & 15) > 2 * ETA as u8) as u8;
791 over |= ((b >> 4) > 2 * ETA as u8) as u8;
792 }
793 over == 0
794}
795
796pub fn sign(sk: &[u8], m: &[u8], ctx: &[u8]) -> Result<Vec<u8>, SignError> {
798 sign_randomized(sk, m, ctx, &[0u8; 32])
799}
800
801pub fn sign_randomized(
805 sk: &[u8],
806 m: &[u8],
807 ctx: &[u8],
808 rnd: &[u8; 32],
809) -> Result<Vec<u8>, SignError> {
810 let mp = message_representative(m, ctx).ok_or(SignError::ContextTooLong { len: ctx.len() })?;
811 let key = SecretKey::decode(sk)?;
812 Ok(sign_internal(&key, &mp, rnd))
813}
814
815fn sign_internal(key: &SecretKey<'_>, mp: &[u8], rnd: &[u8; 32]) -> Vec<u8> {
818 let a_hat = expand_a(key.rho);
819 let s1_hat: Vec<Poly> = key.s1.iter().map(nttp).collect();
820 let s2_hat: Vec<Poly> = key.s2.iter().map(nttp).collect();
821 let t0_hat: Vec<Poly> = key.t0.iter().map(nttp).collect();
822
823 let mu = compute_mu(key.tr, mp);
824 let mut rp_in = key.k_key.to_vec();
825 rp_in.extend_from_slice(rnd);
826 rp_in.extend_from_slice(&mu);
827 let rho_pp = crate::keccak::shake256_bytes(&rp_in, 64);
828
829 let mut kappa = 0u16;
830 loop {
831 let y: Vec<Poly> = (0..ML)
832 .map(|i| expand_mask(&rho_pp, kappa + i as u16))
833 .collect();
834 let y_hat: Vec<Poly> = y.iter().map(nttp).collect();
835 let mut w = vec![[0i32; N]; MK];
836 for i in 0..MK {
837 let mut acc = [0i32; N];
838 for j in 0..ML {
839 let prod = pointwise_montgomery(&a_hat[i][j], &y_hat[j]);
840 for c in 0..N {
841 acc[c] += prod[c];
842 }
843 }
844 to_normal_domain(&mut acc);
845 w[i] = acc;
846 }
847 let w1: Vec<Poly> = w
848 .iter()
849 .map(|p| std::array::from_fn(|c| highbits(p[c])))
850 .collect();
851
852 let mut ct_in = mu.clone();
853 for p in &w1 {
854 ct_in.extend(pack_w1(p));
855 }
856 let c_tilde = crate::keccak::shake256_bytes(&ct_in, CTILDE);
857 let c_hat = nttp(&sample_in_ball(&c_tilde));
858
859 let cs1: Vec<Poly> = s1_hat
860 .iter()
861 .map(|sh| {
862 let mut a = pointwise_montgomery(&c_hat, sh);
863 invntt_tomont(&mut a);
864 a
865 })
866 .collect();
867 let cs2: Vec<Poly> = s2_hat
868 .iter()
869 .map(|sh| {
870 let mut a = pointwise_montgomery(&c_hat, sh);
871 invntt_tomont(&mut a);
872 a
873 })
874 .collect();
875
876 let z: Vec<Poly> = (0..ML)
877 .map(|j| std::array::from_fn(|c| y[j][c] + cs1[j][c]))
878 .collect();
879 let r0: Vec<Poly> = (0..MK)
880 .map(|i| std::array::from_fn(|c| lowbits(freeze(w[i][c] - cs2[i][c]))))
881 .collect();
882
883 if z.iter().any(|p| inf_norm(p) >= GAMMA1 - BETA)
884 || r0.iter().any(|p| inf_norm(p) >= GAMMA2 - BETA)
885 {
886 kappa += ML as u16;
887 continue;
888 }
889
890 let ct0: Vec<Poly> = t0_hat
891 .iter()
892 .map(|th| {
893 let mut a = pointwise_montgomery(&c_hat, th);
894 invntt_tomont(&mut a);
895 a
896 })
897 .collect();
898 let mut h = vec![[0i32; N]; MK];
899 let mut weight = 0i32;
900 for i in 0..MK {
901 for c in 0..N {
902 let r = w[i][c] - cs2[i][c] + ct0[i][c];
903 let bit = make_hint(-ct0[i][c], r) as i32;
904 h[i][c] = bit;
905 weight += bit;
906 }
907 }
908 if ct0.iter().any(|p| inf_norm(p) >= GAMMA2) || weight > OMEGA as i32 {
909 kappa += ML as u16;
910 continue;
911 }
912
913 let mut sig = c_tilde.clone();
914 for p in &z {
915 sig.extend(pack_z(p));
916 }
917 sig.extend(pack_hint(&h));
918 return sig;
919 }
920}
921
922pub fn verify(pk: &[u8], m: &[u8], ctx: &[u8], sig: &[u8]) -> bool {
924 let Some(mp) = message_representative(m, ctx) else {
925 return false;
926 };
927 if sig.len() != SIG_BYTES || pk.len() != PK_BYTES {
928 return false;
929 }
930 let rho = &pk[0..32];
931 let t1: Vec<Poly> = (0..MK)
932 .map(|i| unpack_t1(&pk[32 + i * 320..32 + (i + 1) * 320]))
933 .collect();
934
935 let c_tilde = &sig[0..CTILDE];
936 let mut off = CTILDE;
937 let z: Vec<Poly> = (0..ML)
938 .map(|_| {
939 let p = unpack_z(&sig[off..off + 640]);
940 off += 640;
941 p
942 })
943 .collect();
944 let h = match unpack_hint(&sig[off..off + OMEGA + MK]) {
945 Some(h) => h,
946 None => return false,
947 };
948 if z.iter().any(|p| inf_norm(p) >= GAMMA1 - BETA) {
949 return false;
950 }
951
952 let a_hat = expand_a(rho);
953 let tr = crate::keccak::shake256_bytes(pk, 64);
954 let mu = compute_mu(&tr, &mp);
955 let c_hat = nttp(&sample_in_ball(c_tilde));
956 let z_hat: Vec<Poly> = z.iter().map(nttp).collect();
957
958 let mut w1 = vec![[0i32; N]; MK];
959 for i in 0..MK {
960 let mut acc = [0i32; N];
961 for j in 0..ML {
962 let prod = pointwise_montgomery(&a_hat[i][j], &z_hat[j]);
963 for c in 0..N {
964 acc[c] += prod[c];
965 }
966 }
967 let t1d_hat = nttp(&std::array::from_fn(|c| t1[i][c] << D));
968 let ct1 = pointwise_montgomery(&c_hat, &t1d_hat);
969 for c in 0..N {
970 acc[c] -= ct1[c];
971 }
972 to_normal_domain(&mut acc);
973 for c in 0..N {
974 w1[i][c] = use_hint(h[i][c] as u8, acc[c]);
975 }
976 }
977
978 let mut ct_in = mu;
979 for p in &w1 {
980 ct_in.extend(pack_w1(p));
981 }
982 c_tilde == crate::keccak::shake256_bytes(&ct_in, CTILDE).as_slice()
983}
984
985pub fn bench_verify_breakdown(pk: &[u8], sig: &[u8]) {
987 use std::time::Instant;
988 let rho = &pk[0..32];
989 let c_tilde = &sig[0..CTILDE];
990 let iters = 2000u32;
991 macro_rules! t {
992 ($l:expr, $b:expr) => {{
993 for _ in 0..50 {
994 std::hint::black_box($b);
995 }
996 let s = Instant::now();
997 for _ in 0..iters {
998 std::hint::black_box($b);
999 }
1000 eprintln!(
1001 " {:<22} {:>9.1} ns/op",
1002 $l,
1003 s.elapsed().as_nanos() as f64 / iters as f64
1004 );
1005 }};
1006 }
1007 eprintln!("--- ML-DSA verify component breakdown ---");
1008 t!("expand_a (30 poly)", expand_a(rho));
1009 t!("sample_in_ball", sample_in_ball(c_tilde));
1010 let c = sample_in_ball(c_tilde);
1011 t!("nttp (1 poly)", nttp(&c));
1012 t!("shake256(pk,64)", crate::keccak::shake256_bytes(pk, 64));
1013}
1014
1015pub fn mldsa_keypair_seq(seed: &[i64]) -> Result<logicaffeine_data::LogosSeq<i64>, String> {
1019 let (pk, sk) = keygen(&args::byte_array::<32>("seed", seed)?);
1020 let mut out = pk;
1021 out.extend(sk);
1022 Ok(args::seq_of_bytes(&out))
1023}
1024pub fn mldsa_sign_seq(
1026 sk: &[i64],
1027 msg: &[i64],
1028 ctx: &[i64],
1029) -> Result<logicaffeine_data::LogosSeq<i64>, String> {
1030 let sk = args::bytes("secret key", sk)?;
1031 let msg = args::bytes("message", msg)?;
1032 let ctx = args::bytes("context", ctx)?;
1033 sign(&sk, &msg, &ctx)
1034 .map(|sig| args::seq_of_bytes(&sig))
1035 .map_err(|e| e.to_string())
1036}
1037pub fn mldsa_verify_seq(pk: &[i64], msg: &[i64], ctx: &[i64], sig: &[i64]) -> Result<i64, String> {
1040 let as_bytes = |s: &[i64]| args::bytes("", s).ok();
1041 Ok(
1042 match (as_bytes(pk), as_bytes(msg), as_bytes(ctx), as_bytes(sig)) {
1043 (Some(pk), Some(msg), Some(ctx), Some(sig)) => verify(&pk, &msg, &ctx, &sig) as i64,
1044 _ => 0,
1045 },
1046 )
1047}
1048
1049#[cfg(test)]
1050#[path = "../../logicaffeine_tests/unit/logicaffeine_system/mldsa/tests.rs"]
1051mod tests;