pqcrypto_mldsa/
mldsa44.rs

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
//! ml-dsa-44
//!
//! These bindings use the clean version from [PQClean][pqc]
//!
//! # Example
//! ```
//! // if using pqcrypto-mldsa
//! use pqcrypto_mldsa::mldsa44::*;
//! // or if using the pqcrypto crate:
//! // use pqcrypto::sign::mldsa44::*;
//! let message = vec![0, 1, 2, 3, 4, 5];
//! let (pk, sk) = keypair();
//! let sm = sign(&message, &sk);
//! let verifiedmsg = open(&sm, &pk).unwrap();
//! assert!(verifiedmsg == message);
//! ```
//!
//! [pqc]: https://github.com/pqclean/pqclean/

// This file is generated.

#[cfg(feature = "serialization")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "serialization")]
use serde_big_array::BigArray;

use crate::ffi;
use alloc::vec::Vec;
use pqcrypto_traits::sign as primitive;
use pqcrypto_traits::{Error, Result};

use paste::paste;

macro_rules! simple_struct {
    ($type: ident, $size: expr) => {
        #[derive(Clone, Copy)]
        #[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
        pub struct $type(
            #[cfg_attr(feature = "serialization", serde(with = "BigArray"))] [u8; $size],
        );

        impl $type {
            /// Generates an uninitialized object
            ///
            /// Used to pass to ``ffi`` interfaces.
            ///
            /// Internal use only!
            fn new() -> Self {
                $type([0u8; $size])
            }
        }

        impl primitive::$type for $type {
            /// Get this object as a byte slice
            #[inline]
            fn as_bytes(&self) -> &[u8] {
                &self.0
            }

            /// Construct this object from a byte slice
            fn from_bytes(bytes: &[u8]) -> Result<Self> {
                if bytes.len() != $size {
                    Err(Error::BadLength {
                        name: stringify!($type),
                        actual: bytes.len(),
                        expected: $size,
                    })
                } else {
                    let mut array = [0u8; $size];
                    array.copy_from_slice(bytes);
                    Ok($type(array))
                }
            }
        }

        impl PartialEq for $type {
            /// By no means constant time comparison
            fn eq(&self, other: &Self) -> bool {
                self.0
                    .iter()
                    .zip(other.0.iter())
                    .try_for_each(|(a, b)| if a == b { Ok(()) } else { Err(()) })
                    .is_ok()
            }
        }
    };
}

simple_struct!(PublicKey, ffi::PQCLEAN_MLDSA44_CLEAN_CRYPTO_PUBLICKEYBYTES);
simple_struct!(SecretKey, ffi::PQCLEAN_MLDSA44_CLEAN_CRYPTO_SECRETKEYBYTES);

#[derive(Clone, Copy)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct DetachedSignature(
    #[cfg_attr(feature = "serialization", serde(with = "BigArray"))]
    [u8; ffi::PQCLEAN_MLDSA44_CLEAN_CRYPTO_BYTES],
    usize,
);

// for internal use
impl DetachedSignature {
    fn new() -> Self {
        DetachedSignature([0u8; ffi::PQCLEAN_MLDSA44_CLEAN_CRYPTO_BYTES], 0)
    }
}

impl primitive::DetachedSignature for DetachedSignature {
    /// Get this object as a byte slice
    #[inline]
    fn as_bytes(&self) -> &[u8] {
        &self.0[..self.1]
    }

    #[inline]
    fn from_bytes(bytes: &[u8]) -> Result<Self> {
        let actual = bytes.len();
        let expected = ffi::PQCLEAN_MLDSA44_CLEAN_CRYPTO_BYTES;
        if actual > expected {
            return Err(Error::BadLength {
                name: "DetachedSignature",
                actual,
                expected,
            });
        }
        let mut array = [0u8; ffi::PQCLEAN_MLDSA44_CLEAN_CRYPTO_BYTES];
        array[..bytes.len()].copy_from_slice(bytes);
        Ok(DetachedSignature(array, actual))
    }
}

#[derive(Clone)]
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
pub struct SignedMessage(Vec<u8>);
impl primitive::SignedMessage for SignedMessage {
    /// Get this object as a byte slice
    #[inline]
    fn as_bytes(&self) -> &[u8] {
        self.0.as_slice()
    }

    /// Construct this object from a byte slice
    #[inline]
    fn from_bytes(bytes: &[u8]) -> Result<Self> {
        Ok(SignedMessage(bytes.to_vec()))
    }
}

impl SignedMessage {
    pub fn len(&self) -> usize {
        self.0.len()
    }
}

/// Get the number of bytes for a public key
pub const fn public_key_bytes() -> usize {
    ffi::PQCLEAN_MLDSA44_CLEAN_CRYPTO_PUBLICKEYBYTES
}

/// Get the number of bytes for a secret key
pub const fn secret_key_bytes() -> usize {
    ffi::PQCLEAN_MLDSA44_CLEAN_CRYPTO_SECRETKEYBYTES
}

/// Get the number of bytes that a signature occupies
pub const fn signature_bytes() -> usize {
    ffi::PQCLEAN_MLDSA44_CLEAN_CRYPTO_BYTES
}

macro_rules! gen_keypair {
    ($variant:ident) => {{
        let mut pk = PublicKey::new();
        let mut sk = SecretKey::new();
        assert_eq!(
            unsafe { ffi::$variant(pk.0.as_mut_ptr(), sk.0.as_mut_ptr()) },
            0
        );
        (pk, sk)
    }};
}

/// Generate a ml-dsa-44 keypair
pub fn keypair() -> (PublicKey, SecretKey) {
    #[cfg(all(enable_x86_avx2, feature = "avx2"))]
    {
        if std::is_x86_feature_detected!("avx2") {
            return gen_keypair!(PQCLEAN_MLDSA44_AVX2_crypto_sign_keypair);
        }
    }
    #[cfg(all(enable_aarch64_neon, feature = "neon"))]
    {
        // always use AArch64 code, when target is detected as all AArch64 targets have NEON
        // support, and std::is_aarch64_feature_detected!("neon") works only with Rust nightly at
        // the moment
        if true {
            return gen_keypair!(PQCLEAN_MLDSA44_AARCH64_crypto_sign_keypair);
        }
    }
    gen_keypair!(PQCLEAN_MLDSA44_CLEAN_crypto_sign_keypair)
}

macro_rules! gen_signature {
    ($variant:ident, $msg:ident, $sk:ident) => {{
        let max_len = $msg.len() + signature_bytes();
        let mut signed_msg = Vec::with_capacity(max_len);
        let mut smlen: usize = 0;
        unsafe {
            paste! {
                ffi::[<$variant _ctx>](
                signed_msg.as_mut_ptr(),
                &mut smlen as *mut usize,
                $msg.as_ptr(),
                $msg.len(),
                core::ptr::null(), 0,
                $sk.0.as_ptr(),
            );
            }
            debug_assert!(smlen <= max_len, "exceeded vector capacity");
            signed_msg.set_len(smlen);
        }
        SignedMessage(signed_msg)
    }};
}

macro_rules! gen_signature_ctx {
    ($variant:ident, $msg:ident, $ctx:ident, $sk:ident) => {{
        let max_len = $msg.len() + signature_bytes();
        let mut signed_msg = Vec::with_capacity(max_len);
        let mut smlen: usize = 0;
        unsafe {
            ffi::$variant(
                signed_msg.as_mut_ptr(),
                &mut smlen as *mut usize,
                $msg.as_ptr(),
                $msg.len(),
                $ctx.as_ptr(),
                $ctx.len(),
                $sk.0.as_ptr(),
            );
            debug_assert!(smlen <= max_len, "exceeded vector capacity");
            signed_msg.set_len(smlen);
        }
        SignedMessage(signed_msg)
    }};
}

/// Sign the message and return the signed message.
pub fn sign(msg: &[u8], sk: &SecretKey) -> SignedMessage {
    #[cfg(all(enable_x86_avx2, feature = "avx2"))]
    {
        if std::is_x86_feature_detected!("avx2") {
            return gen_signature!(PQCLEAN_MLDSA44_AVX2_crypto_sign, msg, sk);
        }
    }
    #[cfg(all(enable_aarch64_neon, feature = "neon"))]
    {
        if true {
            return gen_signature!(PQCLEAN_MLDSA44_AARCH64_crypto_sign, msg, sk);
        }
    }
    gen_signature!(PQCLEAN_MLDSA44_CLEAN_crypto_sign, msg, sk)
}

/// Sign the message for the provided context and return the signed message.
pub fn sign_ctx(msg: &[u8], ctx: &[u8], sk: &SecretKey) -> SignedMessage {
    #[cfg(all(enable_x86_avx2, feature = "avx2"))]
    {
        if std::is_x86_feature_detected!("avx2") {
            return gen_signature_ctx!(PQCLEAN_MLDSA44_AVX2_crypto_sign_ctx, msg, ctx, sk);
        }
    }
    #[cfg(all(enable_aarch64_neon, feature = "neon"))]
    {
        if true {
            return gen_signature_ctx!(PQCLEAN_MLDSA44_AARCH64_crypto_sign_ctx, msg, ctx, sk);
        }
    }
    gen_signature_ctx!(PQCLEAN_MLDSA44_CLEAN_crypto_sign_ctx, msg, ctx, sk)
}

macro_rules! open_signed {
    ($variant:ident, $sm:ident, $pk:ident) => {{
        let mut m: Vec<u8> = Vec::with_capacity($sm.len());
        let mut mlen: usize = 0;
        match unsafe {
            paste! { ffi:: [<$variant _ctx>] (
                m.as_mut_ptr(),
                &mut mlen as *mut usize,
                $sm.0.as_ptr(),
                $sm.len(),
                core::ptr::null() as *const u8, 0,
                $pk.0.as_ptr(),
            )}
        } {
            0 => {
                unsafe { m.set_len(mlen) };
                Ok(m)
            }
            -1 => Err(primitive::VerificationError::InvalidSignature),
            _ => Err(primitive::VerificationError::UnknownVerificationError),
        }
    }};
}

macro_rules! open_signed_ctx {
    ($variant:ident, $sm:ident, $ctx: ident, $pk:ident) => {{
        let mut m: Vec<u8> = Vec::with_capacity($sm.len());
        let mut mlen: usize = 0;
        match unsafe {
            ffi::$variant(
                m.as_mut_ptr(),
                &mut mlen as *mut usize,
                $sm.0.as_ptr(),
                $sm.len(),
                $ctx.as_ptr(),
                $ctx.len(),
                $pk.0.as_ptr(),
            )
        } {
            0 => {
                unsafe { m.set_len(mlen) };
                Ok(m)
            }
            -1 => Err(primitive::VerificationError::InvalidSignature),
            _ => Err(primitive::VerificationError::UnknownVerificationError),
        }
    }};
}

/// Open the signed message and if verification succeeds return the message
pub fn open(
    sm: &SignedMessage,
    pk: &PublicKey,
) -> core::result::Result<Vec<u8>, primitive::VerificationError> {
    #[cfg(all(enable_x86_avx2, feature = "avx2"))]
    {
        if std::is_x86_feature_detected!("avx2") {
            return open_signed!(PQCLEAN_MLDSA44_AVX2_crypto_sign_open, sm, pk);
        }
    }
    #[cfg(all(enable_aarch64_neon, feature = "neon"))]
    {
        if true {
            return open_signed!(PQCLEAN_MLDSA44_AARCH64_crypto_sign_open, sm, pk);
        }
    }
    open_signed!(PQCLEAN_MLDSA44_CLEAN_crypto_sign_open, sm, pk)
}

/// Open the signed message and if verification succeeds return the message
pub fn open_ctx(
    sm: &SignedMessage,
    ctx: &[u8],
    pk: &PublicKey,
) -> core::result::Result<Vec<u8>, primitive::VerificationError> {
    #[cfg(all(enable_x86_avx2, feature = "avx2"))]
    {
        if std::is_x86_feature_detected!("avx2") {
            return open_signed_ctx!(PQCLEAN_MLDSA44_AVX2_crypto_sign_open_ctx, sm, ctx, pk);
        }
    }
    #[cfg(all(enable_aarch64_neon, feature = "neon"))]
    {
        if true {
            return open_signed_ctx!(PQCLEAN_MLDSA44_AARCH64_crypto_sign_open_ctx, sm, ctx, pk);
        }
    }
    open_signed_ctx!(PQCLEAN_MLDSA44_CLEAN_crypto_sign_open_ctx, sm, ctx, pk)
}

macro_rules! detached_signature {
    ($variant:ident, $msg:ident, $sk:ident) => {{
        let mut sig = DetachedSignature::new();
        unsafe {
            paste! {
                ffi:: [<$variant _ctx >](
                    sig.0.as_mut_ptr(),
                    &mut sig.1 as *mut usize,
                    $msg.as_ptr(),
                    $msg.len(),
                    core::ptr::null(), 0,
                    $sk.0.as_ptr(),
                );
            }
        }
        sig
    }};
}

macro_rules! detached_signature_ctx {
    ($variant:ident, $msg:ident, $ctx:ident, $sk:ident) => {{
        let mut sig = DetachedSignature::new();
        unsafe {
            ffi::$variant(
                sig.0.as_mut_ptr(),
                &mut sig.1 as *mut usize,
                $msg.as_ptr(),
                $msg.len(),
                $ctx.as_ptr(),
                $ctx.len(),
                $sk.0.as_ptr(),
            );
        }
        sig
    }};
}

/// Create a detached signature on the message
pub fn detached_sign(msg: &[u8], sk: &SecretKey) -> DetachedSignature {
    #[cfg(all(enable_x86_avx2, feature = "avx2"))]
    {
        if std::is_x86_feature_detected!("avx2") {
            return detached_signature!(PQCLEAN_MLDSA44_AVX2_crypto_sign_signature, msg, sk);
        }
    }
    #[cfg(all(enable_aarch64_neon, feature = "neon"))]
    {
        if true {
            return detached_signature!(PQCLEAN_MLDSA44_AARCH64_crypto_sign_signature, msg, sk);
        }
    }
    detached_signature!(PQCLEAN_MLDSA44_CLEAN_crypto_sign_signature, msg, sk)
}

/// Create a detached signature on the message
pub fn detached_sign_ctx(msg: &[u8], ctx: &[u8], sk: &SecretKey) -> DetachedSignature {
    #[cfg(all(enable_x86_avx2, feature = "avx2"))]
    {
        if std::is_x86_feature_detected!("avx2") {
            return detached_signature_ctx!(
                PQCLEAN_MLDSA44_AVX2_crypto_sign_signature_ctx,
                msg,
                ctx,
                sk
            );
        }
    }
    #[cfg(all(enable_aarch64_neon, feature = "neon"))]
    {
        if true {
            return detached_signature_ctx!(
                PQCLEAN_MLDSA44_AARCH64_crypto_sign_signature_ctx,
                msg,
                ctx,
                sk
            );
        }
    }
    detached_signature_ctx!(
        PQCLEAN_MLDSA44_CLEAN_crypto_sign_signature_ctx,
        msg,
        ctx,
        sk
    )
}

macro_rules! verify_detached_sig {
    ($variant:ident, $sig:ident, $msg:ident, $pk:ident) => {{
        let res = unsafe {
            paste! {
                ffi:: [<$variant _ctx >](
                    $sig.0.as_ptr(),
                    $sig.1,
                    $msg.as_ptr(),
                    $msg.len(),
                    core::ptr::null(), 0,
                    $pk.0.as_ptr(),
                )
            }
        };
        match res {
            0 => Ok(()),
            -1 => Err(primitive::VerificationError::InvalidSignature),
            _ => Err(primitive::VerificationError::UnknownVerificationError),
        }
    }};
}

macro_rules! verify_detached_sig_ctx {
    ($variant:ident, $sig:ident, $msg:ident, $ctx:ident, $pk:ident) => {{
        let res = unsafe {
            ffi::$variant(
                $sig.0.as_ptr(),
                $sig.1,
                $msg.as_ptr(),
                $msg.len(),
                $ctx.as_ptr(),
                $ctx.len(),
                $pk.0.as_ptr(),
            )
        };
        match res {
            0 => Ok(()),
            -1 => Err(primitive::VerificationError::InvalidSignature),
            _ => Err(primitive::VerificationError::UnknownVerificationError),
        }
    }};
}

/// Verify the detached signature
pub fn verify_detached_signature(
    sig: &DetachedSignature,
    msg: &[u8],
    pk: &PublicKey,
) -> core::result::Result<(), primitive::VerificationError> {
    #[cfg(all(enable_x86_avx2, feature = "avx2"))]
    {
        if std::is_x86_feature_detected!("avx2") {
            return verify_detached_sig!(PQCLEAN_MLDSA44_AVX2_crypto_sign_verify, sig, msg, pk);
        }
    }
    #[cfg(all(enable_aarch64_neon, feature = "neon"))]
    {
        if true {
            return verify_detached_sig!(PQCLEAN_MLDSA44_AARCH64_crypto_sign_verify, sig, msg, pk);
        }
    }
    verify_detached_sig!(PQCLEAN_MLDSA44_CLEAN_crypto_sign_verify, sig, msg, pk)
}

/// Verify the detached signature
pub fn verify_detached_signature_ctx(
    sig: &DetachedSignature,
    msg: &[u8],
    ctx: &[u8],
    pk: &PublicKey,
) -> core::result::Result<(), primitive::VerificationError> {
    #[cfg(all(enable_x86_avx2, feature = "avx2"))]
    {
        if std::is_x86_feature_detected!("avx2") {
            return verify_detached_sig_ctx!(
                PQCLEAN_MLDSA44_AVX2_crypto_sign_verify_ctx,
                sig,
                msg,
                ctx,
                pk
            );
        }
    }
    #[cfg(all(enable_aarch64_neon, feature = "neon"))]
    {
        if true {
            return verify_detached_sig_ctx!(
                PQCLEAN_MLDSA44_AARCH64_crypto_sign_verify_ctx,
                sig,
                msg,
                ctx,
                pk
            );
        }
    }
    verify_detached_sig_ctx!(
        PQCLEAN_MLDSA44_CLEAN_crypto_sign_verify_ctx,
        sig,
        msg,
        ctx,
        pk
    )
}

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

    #[test]
    pub fn test_sign() {
        let mut rng = rand::thread_rng();
        let len: u16 = rng.gen();

        let message = (0..len).map(|_| rng.gen::<u8>()).collect::<Vec<_>>();
        let (pk, sk) = keypair();
        let sm = sign(&message, &sk);
        let verifiedmsg = open(&sm, &pk).unwrap();
        assert!(verifiedmsg == message);
    }

    #[test]
    pub fn test_sign_detached() {
        let mut rng = rand::thread_rng();
        let len: u16 = rng.gen();
        let message = (0..len).map(|_| rng.gen::<u8>()).collect::<Vec<_>>();

        let (pk, sk) = keypair();
        let sig = detached_sign(&message, &sk);
        assert!(verify_detached_signature(&sig, &message, &pk).is_ok());
        assert!(!verify_detached_signature(&sig, &message[..message.len() - 1], &pk).is_ok());
    }

    #[test]
    pub fn test_sign_ctx() {
        let mut rng = rand::thread_rng();
        let len: u16 = rng.gen();
        let ctx = (0..10).map(|_| rng.gen::<u8>()).collect::<Vec<_>>();

        let message = (0..len).map(|_| rng.gen::<u8>()).collect::<Vec<_>>();
        let (pk, sk) = keypair();
        let sm = sign_ctx(&message, &ctx, &sk);
        let verifiedmsg = open_ctx(&sm, &ctx, &pk).unwrap();
        assert!(verifiedmsg == message);
        assert!(open(&sm, &pk).is_err());
    }

    #[test]
    pub fn test_sign_detached_ctx() {
        let mut rng = rand::thread_rng();
        let len: u16 = rng.gen();
        let message = (0..len).map(|_| rng.gen::<u8>()).collect::<Vec<_>>();
        let ctx = (0..10).map(|_| rng.gen::<u8>()).collect::<Vec<_>>();

        let (pk, sk) = keypair();
        let sig = detached_sign_ctx(&message, &ctx, &sk);
        assert!(verify_detached_signature_ctx(&sig, &message, &ctx, &pk).is_ok());
        assert!(
            !verify_detached_signature_ctx(&sig, &message[..message.len() - 1], &ctx, &pk).is_ok()
        );
        assert!(!verify_detached_signature_ctx(
            &sig,
            &message[..message.len()],
            &ctx[..ctx.len() - 1],
            &pk
        )
        .is_ok());
        assert!(!verify_detached_signature(&sig, &message[..message.len() - 1], &pk).is_ok());
    }
}