lib-q-sig 0.0.4

Post-quantum Digital Signatures for lib-Q
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
//! SLH-DSA (SPHINCS+) implementation for lib-Q
//!
//! This module provides integration between the lib-q-slh-dsa crate and the lib-q
//! provider pattern, implementing proper security validation and algorithm routing.
//!
//! ## Architecture
//!
//! This implementation follows the lib-q pattern for maximum flexibility:
//! - **Low-level API**: Functions accept randomness externally (no_std compatible)
//! - **High-level API**: Functions generate randomness when std is available
//! - **WASM Support**: JavaScript-compatible bindings for web environments
//! - **External randomness**: Required for key generation and signing operations
//!
//! ## Usage Examples
//!
//! ### With std (automatic randomness generation)
//! ```rust
//! # #[cfg(feature = "slh-dsa-std")]
//! # {
//! use lib_q_core::{
//!     Algorithm,
//!     Signature,
//! };
//! use lib_q_sig::slh_dsa::SlhDsa;
//!
//! let slh_dsa = SlhDsa::new();
//! let keypair = slh_dsa
//!     .generate_keypair_for_algorithm(
//!         Algorithm::SlhDsaShake256128fRobust,
//!         None,
//!     )
//!     .unwrap();
//! let signature = slh_dsa
//!     .sign_for_algorithm(
//!         Algorithm::SlhDsaShake256128fRobust,
//!         keypair.secret_key(),
//!         b"Hello, SLH-DSA!",
//!         None,
//!     )
//!     .unwrap();
//! let is_valid = slh_dsa
//!     .verify_for_algorithm(
//!         Algorithm::SlhDsaShake256128fRobust,
//!         keypair.public_key(),
//!         b"Hello, SLH-DSA!",
//!         &signature,
//!     )
//!     .unwrap();
//! assert!(is_valid);
//! # }
//! ```
//!
//! ### Without std (external randomness)
//! ```rust
//! # #[cfg(feature = "slh-dsa")]
//! # {
//! use lib_q_core::{Algorithm, Signature};
//! use lib_q_sig::slh_dsa::SlhDsa;
//!
//! let slh_dsa = SlhDsa::new();
//!
//! // Provide randomness externally
//! let key_randomness = [0u8; 48]; // Get from hardware RNG (48 bytes for Shake256128f)
//! let signing_randomness = [0u8; 16]; // Get from hardware RNG (size depends on parameter set)
//!
//! let keypair = slh_dsa.generate_keypair_with_randomness(
//!     Algorithm::SlhDsaShake256128fRobust,
//!     &key_randomness
//! ).unwrap();
//! let signature = slh_dsa.sign_with_randomness(
//!     Algorithm::SlhDsaShake256128fRobust,
//!     keypair.secret_key(),
//!     b"Hello, SLH-DSA!",
//!     &signing_randomness
//! ).unwrap();
//! let is_valid = slh_dsa.verify_for_algorithm(
//!     Algorithm::SlhDsaShake256128fRobust,
//!     keypair.public_key(),
//!     b"Hello, SLH-DSA!",
//!     &signature
//! ).unwrap();
//! assert!(is_valid);
//! # }
//! ```
//!
//! ### WASM (JavaScript) environment
//! ```javascript
//! import { SlhDsa, WasmSlhDsaKeyPair } from './pkg/lib_q_sig.js';
//!
//! const slhDsa = new SlhDsa();
//!
//! // Generate keypair
//! const keyRandomness = new Uint8Array(32);
//! const keypair = slhDsa.generate_keypair_wasm("SlhDsaShake256128fRobust", keyRandomness);
//!
//! // Sign message
//! const message = new TextEncoder().encode("Hello, WASM SLH-DSA!");
//! const signingRandomness = new Uint8Array(16);
//! const signature = slhDsa.sign_wasm(
//!     "SlhDsaShake256128fRobust",
//!     keypair.secret_key,
//!     message,
//!     signingRandomness
//! );
//!
//! // Verify signature
//! const isValid = slhDsa.verify_wasm(
//!     "SlhDsaShake256128fRobust",
//!     keypair.public_key,
//!     message,
//!     signature
//! );
//! console.log("Signature valid:", isValid);
//! ```
//!
//! ## Supported Parameter Sets
//!
//! - **SHA256-128f-Robust**: Level 1 security (128-bit)
//! - **SHA256-192f-Robust**: Level 3 security (192-bit)
//! - **SHA256-256f-Robust**: Level 5 security (256-bit)
//! - **SHAKE256-128f-Robust**: Level 1 security (128-bit)
//! - **SHAKE256-192f-Robust**: Level 3 security (192-bit)
//! - **SHAKE256-256f-Robust**: Level 5 security (256-bit)
//!
//! ## Feature Flags
//!
//! - `slh-dsa`: Basic SLH-DSA support (no_std compatible)
//! - `slh-dsa-std`: SLH-DSA with automatic randomness generation
//! - `slh-dsa-wasm`: SLH-DSA with WASM bindings
//! - `wasm`: General WASM support

#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(feature = "alloc")]
use alloc::{
    string::ToString,
    vec::Vec,
};

// Import ToString for lib-q-core compatibility (lib-q-core always has alloc enabled)
#[cfg(not(feature = "alloc"))]
extern crate alloc;
#[cfg(not(feature = "alloc"))]
use alloc::string::ToString;

#[cfg(feature = "wasm")]
use js_sys::Uint8Array;
use lib_q_core::api::Algorithm;
use lib_q_core::error::{
    Error,
    Result,
};
use lib_q_core::traits::{
    SigKeypair,
    SigPublicKey,
    SigSecretKey,
    Signature,
};
#[cfg(feature = "slh-dsa")]
use lib_q_slh_dsa::{
    ParameterSet,
    Sha2_128f,
    Sha2_192f,
    Sha2_256f,
    Shake128f,
    Shake192f,
    Shake256f,
    lib_q_integration::SlhDsaSignature,
};
#[cfg(feature = "slh-dsa-std")]
use rand_core::Rng;
// WASM support
#[cfg(feature = "wasm")]
use wasm_bindgen::prelude::*;

/// SLH-DSA signature implementation wrapper
///
/// This struct provides the lib-Q Signature trait implementation for SLH-DSA,
/// routing operations to the appropriate parameter set based on the algorithm.
#[derive(Debug, PartialEq, Eq)]
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub struct SlhDsa;

impl SlhDsa {
    /// Create a new SLH-DSA instance
    pub fn new() -> Self {
        Self
    }

    /// Generate a keypair with external randomness (no_std compatible)
    ///
    /// This is the low-level API that accepts randomness externally,
    /// making it suitable for no_std environments where randomness
    /// must be provided by the caller (e.g., from hardware RNG).
    ///
    /// # Arguments
    /// * `algorithm` - The SLH-DSA algorithm variant
    /// * `randomness` - Cryptographically secure random bytes for key generation
    ///
    /// # Returns
    /// * `Result<SigKeypair>` - The generated keypair or an error
    ///
    /// # Example
    /// ```rust
    /// # #[cfg(feature = "slh-dsa")]
    /// # {
    /// use lib_q_core::Algorithm;
    /// use lib_q_sig::slh_dsa::SlhDsa;
    ///
    /// let slh_dsa = SlhDsa::new();
    /// let randomness = [0u8; 48]; // Get from hardware RNG (48 bytes for Shake256128f)
    /// let keypair = slh_dsa
    ///     .generate_keypair_with_randomness(
    ///         Algorithm::SlhDsaShake256128fRobust,
    ///         &randomness,
    ///     )
    ///     .unwrap();
    /// # }
    /// ```
    #[cfg(feature = "alloc")]
    pub fn generate_keypair_with_randomness(
        &self,
        algorithm: Algorithm,
        randomness: &[u8],
    ) -> Result<SigKeypair> {
        self.generate_keypair_for_algorithm(algorithm, Some(randomness))
    }

    /// Sign a message with external randomness (no_std compatible)
    ///
    /// This is the low-level API that accepts randomness externally,
    /// making it suitable for no_std environments where randomness
    /// must be provided by the caller (e.g., from hardware RNG).
    ///
    /// # Arguments
    /// * `algorithm` - The SLH-DSA algorithm variant
    /// * `secret_key` - The secret key for signing
    /// * `message` - The message to sign
    /// * `randomness` - Cryptographically secure random bytes for signing
    ///
    /// # Returns
    /// * `Result<Vec<u8>>` - The signature or an error
    ///
    /// # Example
    /// ```rust
    /// # #[cfg(feature = "slh-dsa")]
    /// # {
    /// use lib_q_core::Algorithm;
    /// use lib_q_sig::slh_dsa::SlhDsa;
    ///
    /// let slh_dsa = SlhDsa::new();
    /// let key_randomness = [0u8; 48]; // Get from hardware RNG (48 bytes for Shake256128f)
    /// let signing_randomness = [0u8; 16]; // Get from hardware RNG (size depends on parameter set)
    ///
    /// // Generate a keypair first
    /// let keypair = slh_dsa.generate_keypair_with_randomness(
    ///     Algorithm::SlhDsaShake256128fRobust,
    ///     &key_randomness
    /// ).unwrap();
    ///
    /// let signature = slh_dsa.sign_with_randomness(
    ///     Algorithm::SlhDsaShake256128fRobust,
    ///     keypair.secret_key(),
    ///     b"Hello, SLH-DSA!",
    ///     &signing_randomness
    /// ).unwrap();
    /// # }
    /// ```
    #[cfg(feature = "alloc")]
    pub fn sign_with_randomness(
        &self,
        algorithm: Algorithm,
        secret_key: &SigSecretKey,
        message: &[u8],
        randomness: &[u8],
    ) -> Result<Vec<u8>> {
        self.sign_for_algorithm(algorithm, secret_key, message, Some(randomness))
    }
}

impl Default for SlhDsa {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(feature = "alloc")]
impl Signature for SlhDsa {
    fn generate_keypair(&self) -> Result<SigKeypair> {
        // Default to SHAKE256-128f for key generation
        self.generate_keypair_for_algorithm(Algorithm::SlhDsaShake256128fRobust, None)
    }

    fn sign(&self, secret_key: &SigSecretKey, message: &[u8]) -> Result<Vec<u8>> {
        // Default to SHAKE256-128f for signing
        self.sign_for_algorithm(
            Algorithm::SlhDsaShake256128fRobust,
            secret_key,
            message,
            None,
        )
    }

    fn verify(&self, public_key: &SigPublicKey, message: &[u8], signature: &[u8]) -> Result<bool> {
        // Default to SHAKE256-128f for verification
        self.verify_for_algorithm(
            Algorithm::SlhDsaShake256128fRobust,
            public_key,
            message,
            signature,
        )
    }
}

impl SlhDsa {
    /// Generate a keypair for a specific SLH-DSA algorithm
    #[cfg(feature = "alloc")]
    pub fn generate_keypair_for_algorithm(
        &self,
        algorithm: Algorithm,
        randomness: Option<&[u8]>,
    ) -> Result<SigKeypair> {
        #[cfg(feature = "slh-dsa")]
        {
            // Validate algorithm is SLH-DSA
            if !matches!(
                algorithm,
                Algorithm::SlhDsaSha256128fRobust |
                    Algorithm::SlhDsaSha256192fRobust |
                    Algorithm::SlhDsaSha256256fRobust |
                    Algorithm::SlhDsaShake256128fRobust |
                    Algorithm::SlhDsaShake256192fRobust |
                    Algorithm::SlhDsaShake256256fRobust
            ) {
                return Err(Error::InvalidAlgorithm {
                    algorithm: "Algorithm is not an SLH-DSA algorithm",
                });
            }

            // Generate keypair based on algorithm
            let (public_key, secret_key) = match algorithm {
                Algorithm::SlhDsaSha256128fRobust => {
                    self.generate_keypair_impl::<Sha2_128f>(randomness)?
                }
                Algorithm::SlhDsaSha256192fRobust => {
                    self.generate_keypair_impl::<Sha2_192f>(randomness)?
                }
                Algorithm::SlhDsaSha256256fRobust => {
                    self.generate_keypair_impl::<Sha2_256f>(randomness)?
                }
                Algorithm::SlhDsaShake256128fRobust => {
                    self.generate_keypair_impl::<Shake128f>(randomness)?
                }
                Algorithm::SlhDsaShake256192fRobust => {
                    self.generate_keypair_impl::<Shake192f>(randomness)?
                }
                Algorithm::SlhDsaShake256256fRobust => {
                    self.generate_keypair_impl::<Shake256f>(randomness)?
                }
                _ => unreachable!(), // Already validated above
            };

            Ok(SigKeypair::new(public_key, secret_key))
        }
        #[cfg(not(feature = "slh-dsa"))]
        {
            Err(Error::NotImplemented {
                feature: "SLH-DSA implementation requires the 'slh-dsa' feature flag",
            })
        }
    }

    /// Sign a message for a specific SLH-DSA algorithm
    #[cfg(feature = "alloc")]
    pub fn sign_for_algorithm(
        &self,
        algorithm: Algorithm,
        secret_key: &SigSecretKey,
        message: &[u8],
        randomness: Option<&[u8]>,
    ) -> Result<Vec<u8>> {
        #[cfg(feature = "slh-dsa")]
        {
            // Validate algorithm is SLH-DSA
            if !matches!(
                algorithm,
                Algorithm::SlhDsaSha256128fRobust |
                    Algorithm::SlhDsaSha256192fRobust |
                    Algorithm::SlhDsaSha256256fRobust |
                    Algorithm::SlhDsaShake256128fRobust |
                    Algorithm::SlhDsaShake256192fRobust |
                    Algorithm::SlhDsaShake256256fRobust
            ) {
                return Err(Error::InvalidAlgorithm {
                    algorithm: "Algorithm is not an SLH-DSA algorithm",
                });
            }

            // Sign based on algorithm
            match algorithm {
                Algorithm::SlhDsaSha256128fRobust => {
                    self.sign_impl::<Sha2_128f>(secret_key, message, randomness)
                }
                Algorithm::SlhDsaSha256192fRobust => {
                    self.sign_impl::<Sha2_192f>(secret_key, message, randomness)
                }
                Algorithm::SlhDsaSha256256fRobust => {
                    self.sign_impl::<Sha2_256f>(secret_key, message, randomness)
                }
                Algorithm::SlhDsaShake256128fRobust => {
                    self.sign_impl::<Shake128f>(secret_key, message, randomness)
                }
                Algorithm::SlhDsaShake256192fRobust => {
                    self.sign_impl::<Shake192f>(secret_key, message, randomness)
                }
                Algorithm::SlhDsaShake256256fRobust => {
                    self.sign_impl::<Shake256f>(secret_key, message, randomness)
                }
                _ => unreachable!(), // Already validated above
            }
        }
        #[cfg(not(feature = "slh-dsa"))]
        {
            Err(Error::NotImplemented {
                feature: "SLH-DSA implementation requires the 'slh-dsa' feature flag",
            })
        }
    }

    /// Verify a signature for a specific SLH-DSA algorithm
    pub fn verify_for_algorithm(
        &self,
        algorithm: Algorithm,
        public_key: &SigPublicKey,
        message: &[u8],
        signature: &[u8],
    ) -> Result<bool> {
        #[cfg(feature = "slh-dsa")]
        {
            // Validate algorithm is SLH-DSA
            if !matches!(
                algorithm,
                Algorithm::SlhDsaSha256128fRobust |
                    Algorithm::SlhDsaSha256192fRobust |
                    Algorithm::SlhDsaSha256256fRobust |
                    Algorithm::SlhDsaShake256128fRobust |
                    Algorithm::SlhDsaShake256192fRobust |
                    Algorithm::SlhDsaShake256256fRobust
            ) {
                return Err(Error::InvalidAlgorithm {
                    algorithm: "Algorithm is not an SLH-DSA algorithm",
                });
            }

            // Verify based on algorithm
            match algorithm {
                Algorithm::SlhDsaSha256128fRobust => {
                    self.verify_impl::<Sha2_128f>(public_key, message, signature)
                }
                Algorithm::SlhDsaSha256192fRobust => {
                    self.verify_impl::<Sha2_192f>(public_key, message, signature)
                }
                Algorithm::SlhDsaSha256256fRobust => {
                    self.verify_impl::<Sha2_256f>(public_key, message, signature)
                }
                Algorithm::SlhDsaShake256128fRobust => {
                    self.verify_impl::<Shake128f>(public_key, message, signature)
                }
                Algorithm::SlhDsaShake256192fRobust => {
                    self.verify_impl::<Shake192f>(public_key, message, signature)
                }
                Algorithm::SlhDsaShake256256fRobust => {
                    self.verify_impl::<Shake256f>(public_key, message, signature)
                }
                _ => unreachable!(), // Already validated above
            }
        }
        #[cfg(not(feature = "slh-dsa"))]
        {
            Err(Error::NotImplemented {
                feature: "SLH-DSA implementation requires the 'slh-dsa' feature flag",
            })
        }
    }

    #[cfg(all(feature = "slh-dsa", feature = "alloc"))]
    fn generate_keypair_impl<P: ParameterSet + 'static>(
        &self,
        randomness: Option<&[u8]>,
    ) -> Result<(Vec<u8>, Vec<u8>)> {
        let slh_dsa = SlhDsaSignature::<P>::new();

        if let Some(rand) = randomness {
            // Use provided randomness
            let keypair = slh_dsa.generate_keypair_with_randomness(rand)?;
            Ok((
                keypair.public_key.as_bytes().to_vec(),
                keypair.secret_key.as_bytes().to_vec(),
            ))
        } else {
            // Use system RNG (requires std feature)
            #[cfg(feature = "slh-dsa-std")]
            {
                use lib_q_random::new_secure_rng;
                let mut rng = new_secure_rng().map_err(|_| Error::RandomGenerationFailed {
                    operation: "Failed to create secure RNG".to_string(),
                })?;

                // Generate randomness for key generation
                // SLH-DSA requires 3 * N bytes of randomness for key generation
                // We'll use a conservative size that works for all parameter sets
                let mut key_randomness = vec![0u8; 96]; // 32 * 3, works for all parameter sets
                rng.fill_bytes(&mut key_randomness);

                let keypair = slh_dsa.generate_keypair_with_randomness(&key_randomness)?;
                Ok((
                    keypair.public_key.as_bytes().to_vec(),
                    keypair.secret_key.as_bytes().to_vec(),
                ))
            }
            #[cfg(not(feature = "slh-dsa-std"))]
            {
                Err(Error::RandomGenerationFailed {
                    operation: "No randomness source available in no_std environment. Use generate_keypair_with_randomness() instead.".to_string(),
                })
            }
        }
    }

    #[cfg(all(feature = "slh-dsa", feature = "alloc"))]
    fn sign_impl<P: ParameterSet + 'static>(
        &self,
        secret_key: &SigSecretKey,
        message: &[u8],
        randomness: Option<&[u8]>,
    ) -> Result<Vec<u8>> {
        let slh_dsa = SlhDsaSignature::<P>::new();

        if let Some(rand) = randomness {
            // Use provided randomness
            slh_dsa.sign_with_randomness(secret_key, message, rand)
        } else {
            // Use system RNG (requires std feature)
            #[cfg(feature = "slh-dsa-std")]
            {
                use lib_q_random::new_secure_rng;
                let mut rng = new_secure_rng().map_err(|_| Error::RandomGenerationFailed {
                    operation: "Failed to create secure RNG".to_string(),
                })?;

                // Generate randomness for signing
                // SLH-DSA requires N bytes of randomness for signing
                // We'll use a conservative size that works for all parameter sets
                let mut signing_randomness = vec![0u8; 32]; // 32 bytes, works for all parameter sets
                rng.fill_bytes(&mut signing_randomness);

                slh_dsa.sign_with_randomness(secret_key, message, &signing_randomness)
            }
            #[cfg(not(feature = "slh-dsa-std"))]
            {
                Err(Error::RandomGenerationFailed {
                    operation: "No randomness source available in no_std environment. Use sign_with_randomness() instead.".to_string(),
                })
            }
        }
    }

    #[cfg(all(feature = "slh-dsa", feature = "alloc"))]
    fn verify_impl<P: ParameterSet + 'static>(
        &self,
        public_key: &SigPublicKey,
        message: &[u8],
        signature: &[u8],
    ) -> Result<bool> {
        let slh_dsa = SlhDsaSignature::<P>::new();
        slh_dsa.verify(public_key, message, signature)
    }

    #[cfg(all(feature = "slh-dsa", not(feature = "alloc")))]
    fn verify_impl<P: ParameterSet + 'static>(
        &self,
        _public_key: &SigPublicKey,
        _message: &[u8],
        _signature: &[u8],
    ) -> Result<bool> {
        Err(Error::NotImplemented {
            feature: "SLH-DSA verification requires alloc feature for no_std compatibility"
                .to_string(),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_slh_dsa_creation() {
        let slh_dsa = SlhDsa::new();
        assert_eq!(slh_dsa, SlhDsa);
    }

    #[cfg(feature = "slh-dsa")]
    #[test]
    fn test_algorithm_validation() {
        let slh_dsa = SlhDsa::new();

        // Test valid SLH-DSA algorithms
        let valid_algorithms = [
            Algorithm::SlhDsaSha256128fRobust,
            Algorithm::SlhDsaSha256192fRobust,
            Algorithm::SlhDsaSha256256fRobust,
            Algorithm::SlhDsaShake256128fRobust,
            Algorithm::SlhDsaShake256192fRobust,
            Algorithm::SlhDsaShake256256fRobust,
        ];

        for algorithm in valid_algorithms {
            let result = slh_dsa.generate_keypair_for_algorithm(algorithm, None);
            // Should either succeed or fail with RandomGenerationFailed (no_std)
            assert!(result.is_ok() || matches!(result, Err(Error::RandomGenerationFailed { .. })));
        }

        // Test invalid algorithm
        let result = slh_dsa.generate_keypair_for_algorithm(Algorithm::MlDsa65, None);
        assert!(matches!(result, Err(Error::InvalidAlgorithm { .. })));
    }

    #[cfg(feature = "slh-dsa")]
    #[test]
    fn test_explicit_randomness_round_trip() {
        let slh_dsa = SlhDsa::new();
        let algorithm = Algorithm::SlhDsaShake256128fRobust;
        let message = b"slh-dsa explicit randomness test";
        // Shake256-128f requires 3*N bytes for keygen and N bytes for signing (N=16).
        let key_randomness = [11u8; 48];
        let signing_randomness = [23u8; 16];

        let keypair = slh_dsa
            .generate_keypair_with_randomness(algorithm, &key_randomness)
            .expect("key generation with explicit randomness should succeed");
        let signature = slh_dsa
            .sign_with_randomness(
                algorithm,
                keypair.secret_key(),
                message,
                &signing_randomness,
            )
            .expect("signing with explicit randomness should succeed");
        let is_valid = slh_dsa
            .verify_for_algorithm(algorithm, keypair.public_key(), message, &signature)
            .expect("verification should succeed");
        assert!(is_valid, "signature should verify for original message");
    }

    #[cfg(feature = "slh-dsa")]
    #[test]
    fn test_sign_and_verify_reject_non_slh_algorithm() {
        let slh_dsa = SlhDsa::new();
        let key_randomness = [5u8; 48];
        let signing_randomness = [9u8; 16];
        let keypair = slh_dsa
            .generate_keypair_with_randomness(Algorithm::SlhDsaShake256128fRobust, &key_randomness)
            .expect("explicit key generation should succeed");

        let sign_result = slh_dsa.sign_for_algorithm(
            Algorithm::MlDsa65,
            keypair.secret_key(),
            b"message",
            Some(&signing_randomness),
        );
        assert!(matches!(sign_result, Err(Error::InvalidAlgorithm { .. })));

        let verify_result = slh_dsa.verify_for_algorithm(
            Algorithm::MlDsa65,
            keypair.public_key(),
            b"message",
            b"signature",
        );
        assert!(matches!(verify_result, Err(Error::InvalidAlgorithm { .. })));
    }

    #[cfg(all(feature = "slh-dsa", feature = "slh-dsa-std"))]
    #[test]
    fn test_implicit_randomness_round_trip_with_std_rng() {
        let slh_dsa = SlhDsa::new();
        let algorithm = Algorithm::SlhDsaShake256128fRobust;
        let message = b"slh-dsa implicit randomness test";

        let keypair = slh_dsa
            .generate_keypair_for_algorithm(algorithm, None)
            .expect("key generation should use std RNG when slh-dsa-std is enabled");
        let signature = slh_dsa
            .sign_for_algorithm(algorithm, keypair.secret_key(), message, None)
            .expect("signing should use std RNG when slh-dsa-std is enabled");
        let is_valid = slh_dsa
            .verify_for_algorithm(algorithm, keypair.public_key(), message, &signature)
            .expect("verification should succeed");
        assert!(is_valid, "signature should verify for original message");
    }

    #[cfg(all(feature = "slh-dsa", not(feature = "slh-dsa-std")))]
    #[test]
    fn test_implicit_randomness_requires_std_feature() {
        let slh_dsa = SlhDsa::new();
        let algorithm = Algorithm::SlhDsaShake256128fRobust;

        let keypair_err = slh_dsa.generate_keypair_for_algorithm(algorithm, None);
        assert!(
            matches!(keypair_err, Err(Error::RandomGenerationFailed { .. })),
            "without slh-dsa-std, implicit keygen randomness should fail"
        );

        // A valid key is still needed to exercise the implicit-signing error path.
        let key_randomness = [7u8; 48];
        let keypair = slh_dsa
            .generate_keypair_with_randomness(algorithm, &key_randomness)
            .expect("explicit key generation should succeed");
        let sign_err = slh_dsa.sign_for_algorithm(algorithm, keypair.secret_key(), b"msg", None);
        assert!(
            matches!(sign_err, Err(Error::RandomGenerationFailed { .. })),
            "without slh-dsa-std, implicit signing randomness should fail"
        );
    }

    #[cfg(not(feature = "slh-dsa"))]
    #[test]
    fn test_feature_flag_required() {
        let slh_dsa = SlhDsa::new();
        let result =
            slh_dsa.generate_keypair_for_algorithm(Algorithm::SlhDsaShake256128fRobust, None);
        assert!(matches!(result, Err(Error::NotImplemented { .. })));
    }
}

// WASM bindings for SLH-DSA
#[cfg(feature = "wasm")]
#[wasm_bindgen]
impl SlhDsa {
    /// Generate a keypair for WASM (JavaScript) environment
    ///
    /// # Arguments
    /// * `algorithm` - The algorithm name as a string
    /// * `randomness` - Optional randomness as Uint8Array
    ///
    /// # Returns
    /// * `Result<WasmSlhDsaKeyPair, JsValue>` - The keypair or error
    #[wasm_bindgen]
    pub fn generate_keypair_wasm(
        &self,
        algorithm: &str,
        randomness: Option<Uint8Array>,
    ) -> core::result::Result<WasmSlhDsaKeyPair, JsValue> {
        let algorithm = match algorithm {
            "SlhDsaSha256128fRobust" => Algorithm::SlhDsaSha256128fRobust,
            "SlhDsaSha256192fRobust" => Algorithm::SlhDsaSha256192fRobust,
            "SlhDsaSha256256fRobust" => Algorithm::SlhDsaSha256256fRobust,
            "SlhDsaShake256128fRobust" => Algorithm::SlhDsaShake256128fRobust,
            "SlhDsaShake256192fRobust" => Algorithm::SlhDsaShake256192fRobust,
            "SlhDsaShake256256fRobust" => Algorithm::SlhDsaShake256256fRobust,
            _ => return Err(JsValue::from_str("Invalid algorithm")),
        };

        let randomness_vec = randomness.map(|rand| rand.to_vec());
        let randomness_slice = randomness_vec.as_deref();

        let keypair = match self.generate_keypair_for_algorithm(algorithm, randomness_slice) {
            Ok(kp) => kp,
            Err(e) => return Err(JsValue::from_str(&e.to_string())),
        };

        Ok(WasmSlhDsaKeyPair::new(
            Uint8Array::from(keypair.public_key().as_bytes()),
            Uint8Array::from(keypair.secret_key().as_bytes()),
        ))
    }

    /// Sign a message in WASM (JavaScript) environment
    ///
    /// # Arguments
    /// * `algorithm` - The algorithm name as a string
    /// * `secret_key` - The secret key as Uint8Array
    /// * `message` - The message to sign as Uint8Array
    /// * `randomness` - Optional randomness as Uint8Array
    ///
    /// # Returns
    /// * `Result<Uint8Array, JsValue>` - The signature or error
    #[wasm_bindgen]
    pub fn sign_wasm(
        &self,
        algorithm: &str,
        secret_key: Uint8Array,
        message: Uint8Array,
        randomness: Option<Uint8Array>,
    ) -> core::result::Result<Uint8Array, JsValue> {
        let algorithm = match algorithm {
            "SlhDsaSha256128fRobust" => Algorithm::SlhDsaSha256128fRobust,
            "SlhDsaSha256192fRobust" => Algorithm::SlhDsaSha256192fRobust,
            "SlhDsaSha256256fRobust" => Algorithm::SlhDsaSha256256fRobust,
            "SlhDsaShake256128fRobust" => Algorithm::SlhDsaShake256128fRobust,
            "SlhDsaShake256192fRobust" => Algorithm::SlhDsaShake256192fRobust,
            "SlhDsaShake256256fRobust" => Algorithm::SlhDsaShake256256fRobust,
            _ => return Err(JsValue::from_str("Invalid algorithm")),
        };

        let secret_key = SigSecretKey::new(secret_key.to_vec());
        let message = message.to_vec();
        let randomness_vec = randomness.map(|rand| rand.to_vec());
        let randomness_slice = randomness_vec.as_deref();

        let signature =
            match self.sign_for_algorithm(algorithm, &secret_key, &message, randomness_slice) {
                Ok(sig) => sig,
                Err(e) => return Err(JsValue::from_str(&e.to_string())),
            };

        Ok(Uint8Array::from(signature.as_slice()))
    }

    /// Verify a signature in WASM (JavaScript) environment
    ///
    /// # Arguments
    /// * `algorithm` - The algorithm name as a string
    /// * `public_key` - The public key as Uint8Array
    /// * `message` - The message as Uint8Array
    /// * `signature` - The signature to verify as Uint8Array
    ///
    /// # Returns
    /// * `Result<bool, JsValue>` - Verification result or error
    #[wasm_bindgen]
    pub fn verify_wasm(
        &self,
        algorithm: &str,
        public_key: Uint8Array,
        message: Uint8Array,
        signature: Uint8Array,
    ) -> core::result::Result<bool, JsValue> {
        let algorithm = match algorithm {
            "SlhDsaSha256128fRobust" => Algorithm::SlhDsaSha256128fRobust,
            "SlhDsaSha256192fRobust" => Algorithm::SlhDsaSha256192fRobust,
            "SlhDsaSha256256fRobust" => Algorithm::SlhDsaSha256256fRobust,
            "SlhDsaShake256128fRobust" => Algorithm::SlhDsaShake256128fRobust,
            "SlhDsaShake256192fRobust" => Algorithm::SlhDsaShake256192fRobust,
            "SlhDsaShake256256fRobust" => Algorithm::SlhDsaShake256256fRobust,
            _ => return Err(JsValue::from_str("Invalid algorithm")),
        };

        let public_key = SigPublicKey::new(public_key.to_vec());
        let message = message.to_vec();
        let signature = signature.to_vec();

        let is_valid = match self.verify_for_algorithm(algorithm, &public_key, &message, &signature)
        {
            Ok(valid) => valid,
            Err(e) => return Err(JsValue::from_str(&e.to_string())),
        };

        Ok(is_valid)
    }
}

/// WASM-compatible SLH-DSA key pair
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub struct WasmSlhDsaKeyPair {
    public_key: Uint8Array,
    secret_key: Uint8Array,
}

#[cfg(feature = "wasm")]
#[wasm_bindgen]
impl WasmSlhDsaKeyPair {
    #[wasm_bindgen(constructor)]
    pub fn new(public_key: Uint8Array, secret_key: Uint8Array) -> WasmSlhDsaKeyPair {
        WasmSlhDsaKeyPair {
            public_key,
            secret_key,
        }
    }

    #[wasm_bindgen(getter)]
    pub fn public_key(&self) -> Uint8Array {
        self.public_key.clone()
    }

    #[wasm_bindgen(getter)]
    pub fn secret_key(&self) -> Uint8Array {
        self.secret_key.clone()
    }
}