mail-auth 0.15.1

DKIM, ARC, SPF and DMARC library for Rust
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
/*
 * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
 *
 * SPDX-License-Identifier: Apache-2.0 OR MIT
 */

//! Signing and verification keys backed by `aws-lc-rs`.

use super::{
    Algorithm, CryptoError, ED25519_PUBLIC_KEY_LEN, HashContext, HashImpl, HashOutput,
    MLDSA44_MESSAGE_CAPACITY, Sha1, Sha256, Sha512, SigningKey, VerifyingKey,
    aws_lc_mldsa::MlDsa44,
    mldsa::{self, CONTEXT, SIGNATURE_LEN, Seed, library_error},
    rsa_private_key_heap_size,
};
use crate::{
    Error, Result,
    dkim::Canonicalization,
    headers::{Writable, Writer},
};
use aws_lc_rs::digest::{Context, SHA1_FOR_LEGACY_USE_ONLY, SHA256, SHA512};
use aws_lc_rs::rand::SystemRandom;
use aws_lc_rs::signature::{
    ED25519, Ed25519KeyPair, KeyPair, RSA_PKCS1_1024_8192_SHA1_FOR_LEGACY_USE_ONLY,
    RSA_PKCS1_1024_8192_SHA256_FOR_LEGACY_USE_ONLY, RSA_PKCS1_SHA256, RsaKeyPair,
    UnparsedPublicKey,
};
use rustls_pki_types::{PrivateKeyDer, PrivatePkcs1KeyDer, PrivatePkcs8KeyDer, pem::PemObject};
use std::marker::PhantomData;

const ED25519_PRIVATE_KEY_HEAP_SIZE: usize = 112;
const MLDSA44_PRIVATE_KEY_HEAP_SIZE: usize = 4096;
const MLDSA44_PUBLIC_KEY_HEAP_SIZE: usize = 1600;

/// An RSA private key for `rsa-sha256` signing (RFC 6376 Section 3.3.2).
///
/// `T` selects the hash function; only `RsaKey<Sha256>` implements
/// [`SigningKey`]. Load a key with [`from_key_der`](Self::from_key_der).
#[derive(Debug)]
pub struct RsaKey<T> {
    inner: RsaKeyPair,
    rng: SystemRandom,
    padding: PhantomData<T>,
}

impl<T: HashImpl> RsaKey<T> {
    /// Loads an RSA private key from a PKCS #8 PEM string.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Crypto`] with [`CryptoError::Library`] if the key
    /// cannot be decoded.
    #[deprecated(since = "0.7.4", note = "use `from_key_der()` instead")]
    pub fn from_pkcs8_pem(pkcs8_pem: &str) -> Result<Self> {
        Self::from_key_der(PrivateKeyDer::Pkcs8(
            PrivatePkcs8KeyDer::from_pem_slice(pkcs8_pem.as_bytes())
                .map_err(|err| Error::Crypto(CryptoError::Library(err.to_string())))?,
        ))
    }

    /// Loads an RSA private key from PKCS #8 DER bytes.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Crypto`] with [`CryptoError::Library`] if the key
    /// cannot be decoded.
    #[deprecated(since = "0.7.4", note = "use `from_key_der()` instead")]
    pub fn from_pkcs8_der(pkcs8_der: &[u8]) -> Result<Self> {
        Self::from_key_der(PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(pkcs8_der)))
    }

    /// Loads an RSA private key from a PKCS #1 PEM string
    /// (`BEGIN RSA PRIVATE KEY`).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Crypto`] with [`CryptoError::Library`] if the key
    /// cannot be decoded.
    #[deprecated(since = "0.7.4", note = "use `from_key_der()` instead")]
    pub fn from_rsa_pem(rsa_pem: &str) -> Result<Self> {
        Self::from_key_der(PrivateKeyDer::Pkcs1(
            PrivatePkcs1KeyDer::from_pem_slice(rsa_pem.as_bytes())
                .map_err(|err| Error::Crypto(CryptoError::Library(err.to_string())))?,
        ))
    }

    /// Loads an RSA private key from PKCS #1 DER bytes.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Crypto`] with [`CryptoError::Library`] if the key
    /// cannot be decoded.
    #[deprecated(since = "0.7.4", note = "use `from_key_der()` instead")]
    pub fn from_der(der: &[u8]) -> Result<Self> {
        Self::from_key_der(PrivateKeyDer::Pkcs1(PrivatePkcs1KeyDer::from(der)))
    }

    /// Loads an RSA private key from DER, in PKCS #1 (`RSAPrivateKey`) or
    /// PKCS #8 (`PrivateKeyInfo`) form. Parse PEM input first with
    /// [`PrivateKeyDer::from_pem_slice`](rustls_pki_types::pem::PemObject::from_pem_slice).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Crypto`] with [`CryptoError::Library`] if the key is
    /// in another format (such as SEC1) or cannot be decoded.
    pub fn from_key_der(key_der: PrivateKeyDer<'_>) -> Result<Self> {
        let inner = match key_der {
            PrivateKeyDer::Pkcs1(der) => RsaKeyPair::from_der(der.secret_pkcs1_der())
                .map_err(|err| Error::Crypto(CryptoError::Library(err.to_string())))?,
            PrivateKeyDer::Pkcs8(der) => RsaKeyPair::from_pkcs8(der.secret_pkcs8_der())
                .map_err(|err| Error::Crypto(CryptoError::Library(err.to_string())))?,
            _ => {
                return Err(Error::Crypto(CryptoError::Library(
                    "Unsupported RSA key format".to_string(),
                )));
            }
        };

        Ok(Self {
            inner,
            rng: SystemRandom::new(),
            padding: PhantomData,
        })
    }

    /// Returns the public key of the RSA key pair, encoded as a DER PKCS #1
    /// `RSAPublicKey`.
    pub fn public_key(&self) -> Vec<u8> {
        self.inner.public_key().as_ref().to_vec()
    }
}

impl SigningKey for RsaKey<Sha256> {
    type Hasher = Sha256;

    fn sign(&self, input: impl Writable) -> Result<Vec<u8>> {
        let mut data = Vec::with_capacity(256);
        input.write(&mut data);

        let mut signature = vec![0; self.inner.public_key().modulus_len()];
        self.inner
            .sign(&RSA_PKCS1_SHA256, &self.rng, &data, &mut signature)
            .map_err(|err| Error::Crypto(CryptoError::Library(err.to_string())))?;
        Ok(signature)
    }

    fn algorithm(&self) -> Algorithm {
        Algorithm::RsaSha256
    }

    fn heap_size(&self) -> usize {
        rsa_private_key_heap_size(self.inner.public_key().modulus_len())
    }
}

/// An Ed25519 private key for `ed25519-sha256` signing (RFC 8463).
///
/// The signature is computed over the SHA-256 hash of the signed data, as
/// RFC 8463 Section 3 requires.
pub struct Ed25519Key {
    inner: Ed25519KeyPair,
}

impl Ed25519Key {
    /// Generates a new random Ed25519 key pair and returns it as PKCS #8 DER
    /// bytes, ready for [`from_pkcs8_der`](Self::from_pkcs8_der).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Crypto`] with [`CryptoError::Library`] if key
    /// generation or encoding fails.
    pub fn generate_pkcs8() -> Result<Vec<u8>> {
        Ok(Ed25519KeyPair::generate_pkcs8(&SystemRandom::new())
            .map_err(|err| Error::Crypto(CryptoError::Library(err.to_string())))?
            .as_ref()
            .to_vec())
    }

    /// Loads an Ed25519 key pair from PKCS #8 v2 DER bytes (RFC 5958), checking
    /// that the embedded public key matches the private key. PKCS #8 v1
    /// documents are rejected by `ring`; load them with
    /// [`from_pkcs8_maybe_unchecked_der`](Self::from_pkcs8_maybe_unchecked_der).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Crypto`] with [`CryptoError::Library`] if the key
    /// cannot be decoded.
    pub fn from_pkcs8_der(pkcs8_der: &[u8]) -> Result<Self> {
        Ok(Self {
            inner: Ed25519KeyPair::from_pkcs8(pkcs8_der)
                .map_err(|err| Error::Crypto(CryptoError::Library(err.to_string())))?,
        })
    }

    /// Loads an Ed25519 key pair from PKCS #8 v1 or v2 DER bytes. A v1
    /// document (as produced by `openssl genpkey -algorithm ED25519`) carries
    /// no public key, so no consistency check is possible; v2 documents are
    /// checked as in [`from_pkcs8_der`](Self::from_pkcs8_der).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Crypto`] with [`CryptoError::Library`] if the key
    /// cannot be decoded.
    pub fn from_pkcs8_maybe_unchecked_der(pkcs8_der: &[u8]) -> Result<Self> {
        Ok(Self {
            inner: Ed25519KeyPair::from_pkcs8_maybe_unchecked(pkcs8_der)
                .map_err(|err| Error::Crypto(CryptoError::Library(err.to_string())))?,
        })
    }

    /// Builds an Ed25519 key pair from its 32-byte seed (private key) and
    /// 32-byte public key.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Crypto`] with [`CryptoError::Library`] if either
    /// value has the wrong length or the public key does not match the seed.
    pub fn from_seed_and_public_key(seed: &[u8], public_key: &[u8]) -> Result<Self> {
        Ok(Self {
            inner: Ed25519KeyPair::from_seed_and_public_key(seed, public_key)
                .map_err(|err| Error::Crypto(CryptoError::Library(err.to_string())))?,
        })
    }

    /// Returns the 32-byte raw Ed25519 public key, as published in the `p=`
    /// tag of a DKIM key record.
    pub fn public_key(&self) -> Vec<u8> {
        self.inner.public_key().as_ref().to_vec()
    }
}

impl SigningKey for Ed25519Key {
    type Hasher = Sha256;

    fn sign(&self, input: impl Writable) -> Result<Vec<u8>> {
        let mut data = Sha256::hasher();
        input.write(&mut data);
        Ok(self.inner.sign(data.complete().as_ref()).as_ref().to_vec())
    }

    fn algorithm(&self) -> Algorithm {
        Algorithm::Ed25519Sha256
    }

    fn heap_size(&self) -> usize {
        ED25519_PRIVATE_KEY_HEAP_SIZE
    }
}

pub(crate) struct RsaPublicKey {
    key: Vec<u8>,
}

impl RsaPublicKey {
    pub(crate) fn verifying_key_from_bytes(
        bytes: &[u8],
    ) -> Result<Box<dyn VerifyingKey + Send + Sync>> {
        Ok(Box::new(Self {
            key: try_strip_rsa_prefix(bytes).unwrap_or(bytes).to_vec(),
        }))
    }
}

/// Computes the RSA modulus size in bits from a DER-encoded RSAPublicKey
fn rsa_modulus_bits(key: &[u8]) -> Option<usize> {
    if *key.first()? != DER_SEQUENCE_TAG {
        return None;
    }
    let (_, rest) = decode_multi_byte_len(&key[1..])?;
    if *rest.first()? != DER_INTEGER_TAG {
        return None;
    }
    let (len, after_len) = decode_multi_byte_len(&rest[1..])?;
    after_len
        .get(..len)?
        .iter()
        .position(|&b| b != 0)
        .map(|leading_zeros| (len - leading_zeros) * 8)
}

/// Try to strip an ASN.1 DER-encoded RSA public key prefix
///
/// Returns the original slice if the prefix is not found.
fn try_strip_rsa_prefix(bytes: &[u8]) -> Option<&[u8]> {
    if *bytes.first()? != DER_SEQUENCE_TAG {
        return None;
    }

    let (_, bytes) = decode_multi_byte_len(&bytes[1..])?;
    if *bytes.first()? != DER_SEQUENCE_TAG {
        return None;
    }

    let (byte_len, bytes) = decode_multi_byte_len(&bytes[1..])?;
    if *bytes.first()? != DER_OBJECT_ID_TAG || byte_len != 13 {
        return None;
    }

    let bytes = bytes.get(13..)?;
    if *bytes.first()? != DER_BIT_STRING_TAG {
        return None;
    }

    decode_multi_byte_len(&bytes[1..]).and_then(|(_, bytes)| bytes.get(1..))
}

fn decode_multi_byte_len(bytes: &[u8]) -> Option<(usize, &[u8])> {
    if bytes.first()? & 0x80 == 0 {
        return Some((bytes[0] as usize, &bytes[1..]));
    }

    let len_len = (bytes[0] & 0x7f) as usize;
    if bytes.len() < len_len + 1 {
        return None;
    }

    let mut len = 0;
    for i in 0..len_len {
        len = (len << 8) | bytes[1 + i] as usize;
    }

    Some((len, &bytes[len_len + 1..]))
}

const DER_OBJECT_ID_TAG: u8 = 0x06;
const DER_BIT_STRING_TAG: u8 = 0x03;
const DER_SEQUENCE_TAG: u8 = 0x30;
const DER_INTEGER_TAG: u8 = 0x02;

impl VerifyingKey for RsaPublicKey {
    fn verify<'a>(
        &self,
        headers: &mut dyn Iterator<Item = (&'a [u8], &'a [u8])>,
        signature: &[u8],
        canonicalization: Canonicalization,
        algorithm: Algorithm,
    ) -> Result<()> {
        let mut data = Vec::with_capacity(256);
        canonicalization.canonicalize_headers(headers, &mut data);

        match algorithm {
            Algorithm::RsaSha256 => UnparsedPublicKey::new(
                &RSA_PKCS1_1024_8192_SHA256_FOR_LEGACY_USE_ONLY,
                self.key.as_slice(),
            )
            .verify(&data, signature)
            .map_err(|_| Error::Crypto(CryptoError::FailedVerification)),
            Algorithm::RsaSha1 => UnparsedPublicKey::new(
                &RSA_PKCS1_1024_8192_SHA1_FOR_LEGACY_USE_ONLY,
                self.key.as_slice(),
            )
            .verify(&data, signature)
            .map_err(|_| Error::Crypto(CryptoError::FailedVerification)),
            Algorithm::Ed25519Sha256 | Algorithm::MlDsa44 => {
                Err(Error::Crypto(CryptoError::IncompatibleAlgorithms))
            }
        }
    }

    fn verify_bytes(&self, input: &[u8], signature: &[u8], algorithm: Algorithm) -> Result<()> {
        match algorithm {
            Algorithm::RsaSha256 => UnparsedPublicKey::new(
                &RSA_PKCS1_1024_8192_SHA256_FOR_LEGACY_USE_ONLY,
                self.key.as_slice(),
            )
            .verify(input, signature)
            .map_err(|_| Error::Crypto(CryptoError::FailedVerification)),
            Algorithm::RsaSha1 => UnparsedPublicKey::new(
                &RSA_PKCS1_1024_8192_SHA1_FOR_LEGACY_USE_ONLY,
                self.key.as_slice(),
            )
            .verify(input, signature)
            .map_err(|_| Error::Crypto(CryptoError::FailedVerification)),
            Algorithm::Ed25519Sha256 | Algorithm::MlDsa44 => {
                Err(Error::Crypto(CryptoError::IncompatibleAlgorithms))
            }
        }
    }

    fn public_key_bits(&self) -> usize {
        rsa_modulus_bits(&self.key).unwrap_or_default()
    }

    fn heap_size(&self) -> usize {
        self.key.capacity()
    }
}

pub(crate) struct Ed25519PublicKey {
    inner: UnparsedPublicKey<[u8; ED25519_PUBLIC_KEY_LEN]>,
}

impl Ed25519PublicKey {
    pub(crate) fn verifying_key_from_bytes(
        bytes: &[u8],
    ) -> Result<Box<dyn VerifyingKey + Send + Sync>> {
        let key: [u8; ED25519_PUBLIC_KEY_LEN] = bytes
            .try_into()
            .map_err(|_| Error::Crypto(CryptoError::MalformedPublicKey))?;
        Ok(Box::new(Self {
            inner: UnparsedPublicKey::new(&ED25519, key),
        }))
    }
}

impl VerifyingKey for Ed25519PublicKey {
    fn verify<'a>(
        &self,
        headers: &mut dyn Iterator<Item = (&'a [u8], &'a [u8])>,
        signature: &[u8],
        canonicalization: Canonicalization,
        algorithm: Algorithm,
    ) -> Result<()> {
        if !matches!(algorithm, Algorithm::Ed25519Sha256) {
            return Err(Error::Crypto(CryptoError::IncompatibleAlgorithms));
        }

        let mut hasher = Sha256::hasher();
        canonicalization.canonicalize_headers(headers, &mut hasher);
        self.inner
            .verify(hasher.complete().as_ref(), signature)
            .map_err(|err| Error::Crypto(CryptoError::Library(err.to_string())))
    }

    fn verify_bytes(&self, input: &[u8], signature: &[u8], algorithm: Algorithm) -> Result<()> {
        if !matches!(algorithm, Algorithm::Ed25519Sha256) {
            return Err(Error::Crypto(CryptoError::IncompatibleAlgorithms));
        }

        let mut hasher = Sha256::hasher();
        hasher.write(input);
        self.inner
            .verify(hasher.complete().as_ref(), signature)
            .map_err(|_| Error::Crypto(CryptoError::FailedVerification))
    }
}

/// An ML-DSA-44 private key for `mldsa44` signing (DKIM2 only,
/// draft-ietf-dkim-dkim2-spec Section 3.4).
///
/// Signatures use "pure" ML-DSA-44 (FIPS 204) with the `DKIM2` context
/// string. They are hedged (randomized), as the specification recommends, so
/// signing the same input twice gives different signatures.
pub struct MlDsa44Key {
    inner: MlDsa44,
}

impl MlDsa44Key {
    /// Generates a new random key and returns it as PKCS #8 DER bytes (the
    /// RFC 9881 seed-only private key encoding), ready for
    /// [`from_pkcs8_der`](Self::from_pkcs8_der).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Crypto`] with [`CryptoError::Library`] if the system
    /// random number generator fails.
    pub fn generate_pkcs8() -> Result<Vec<u8>> {
        let mut seed = Seed::default();
        aws_lc_rs::rand::fill(&mut seed)
            .map_err(|err| Error::Crypto(CryptoError::Library(err.to_string())))?;
        Ok(mldsa::pkcs8_der(&seed))
    }

    /// Loads a key from PKCS #8 DER bytes holding an ML-DSA-44 private key in
    /// the RFC 9881 seed-only or both (seed and expanded key) form. The key
    /// is derived from the seed.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Crypto`] with [`CryptoError::Library`] if the key
    /// cannot be decoded or has no seed.
    pub fn from_pkcs8_der(pkcs8_der: &[u8]) -> Result<Self> {
        Self::from_seed(mldsa::seed_from_pkcs8_der(pkcs8_der)?)
    }

    /// Loads a key from its 32-byte seed.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Crypto`] with [`CryptoError::Library`] if the seed
    /// has the wrong length or cannot be expanded.
    pub fn from_raw_private_key(raw: &[u8]) -> Result<Self> {
        Self::from_seed(mldsa::seed_from_raw(raw)?)
    }

    fn from_seed(seed: &Seed) -> Result<Self> {
        MlDsa44::from_seed(seed)
            .map(|inner| Self { inner })
            .ok_or_else(|| library_error("Invalid ML-DSA-44 seed"))
    }

    /// Returns the 1312-byte ML-DSA-44 public key, as published in the `p=`
    /// tag of a `k=mldsa44` key record.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Crypto`] with [`CryptoError::Library`] if the backend
    /// cannot export the public key.
    pub fn public_key(&self) -> Result<Vec<u8>> {
        self.inner
            .public_key()
            .map(Vec::from)
            .ok_or_else(|| library_error("Cannot export the ML-DSA-44 public key"))
    }
}

impl SigningKey for MlDsa44Key {
    type Hasher = Sha256;

    fn sign(&self, input: impl Writable) -> Result<Vec<u8>> {
        let mut message = Vec::with_capacity(MLDSA44_MESSAGE_CAPACITY);
        input.write(&mut message);
        self.inner
            .sign(&message, CONTEXT)
            .map(Vec::from)
            .ok_or_else(|| library_error("ML-DSA-44 signing failed"))
    }

    fn algorithm(&self) -> Algorithm {
        Algorithm::MlDsa44
    }

    fn heap_size(&self) -> usize {
        MLDSA44_PRIVATE_KEY_HEAP_SIZE
    }
}

pub(crate) struct MlDsa44PublicKey {
    inner: MlDsa44,
}

impl MlDsa44PublicKey {
    pub(crate) fn verifying_key_from_bytes(
        bytes: &[u8],
    ) -> Result<Box<dyn VerifyingKey + Send + Sync>> {
        let key = mldsa::public_key_from_bytes(bytes)?;
        Ok(Box::new(Self {
            inner: MlDsa44::from_public_key(key)
                .ok_or(Error::Crypto(CryptoError::MalformedPublicKey))?,
        }))
    }
}

impl VerifyingKey for MlDsa44PublicKey {
    fn verify<'a>(
        &self,
        _: &mut dyn Iterator<Item = (&'a [u8], &'a [u8])>,
        _: &[u8],
        _: Canonicalization,
        _: Algorithm,
    ) -> Result<()> {
        Err(Error::Crypto(CryptoError::IncompatibleAlgorithms))
    }

    fn verify_bytes(&self, input: &[u8], signature: &[u8], algorithm: Algorithm) -> Result<()> {
        if !matches!(algorithm, Algorithm::MlDsa44) {
            return Err(Error::Crypto(CryptoError::IncompatibleAlgorithms));
        }
        let signature: &[u8; SIGNATURE_LEN] = signature
            .try_into()
            .map_err(|_| Error::Crypto(CryptoError::FailedVerification))?;
        if self.inner.verify(input, CONTEXT, signature) {
            Ok(())
        } else {
            Err(Error::Crypto(CryptoError::FailedVerification))
        }
    }

    fn heap_size(&self) -> usize {
        MLDSA44_PUBLIC_KEY_HEAP_SIZE
    }
}

impl HashImpl for Sha1 {
    type Context = Context;

    fn hasher() -> Self::Context {
        Context::new(&SHA1_FOR_LEGACY_USE_ONLY)
    }
}

impl HashImpl for Sha256 {
    type Context = Context;

    fn hasher() -> Self::Context {
        Context::new(&SHA256)
    }
}

impl HashImpl for Sha512 {
    type Context = Context;

    fn hasher() -> Self::Context {
        Context::new(&SHA512)
    }
}

impl HashContext for Context {
    fn complete(self) -> HashOutput {
        HashOutput::Digest(self.finish())
    }
}

impl Writer for Context {
    fn write(&mut self, data: &[u8]) {
        self.update(data);
    }
}

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

    #[test]
    fn from_key_der_pkcs1() {
        let key_der = PrivateKeyDer::from_pem_slice(PKCS1_PEM.as_bytes()).unwrap();
        assert!(matches!(key_der, PrivateKeyDer::Pkcs1(_)));
        RsaKey::<Sha256>::from_key_der(key_der).unwrap();
    }

    #[test]
    fn from_key_der_pkcs8() {
        let key_der = PrivateKeyDer::from_pem_slice(PKCS8_PEM.as_bytes()).unwrap();
        assert!(matches!(key_der, PrivateKeyDer::Pkcs8(_)));
        RsaKey::<Sha256>::from_key_der(key_der).unwrap();
    }

    const PKCS1_PEM: &str = r#"-----BEGIN RSA PRIVATE KEY-----
MIIEoAIBAAKCAQEAplSshLNG7gYj7LckWBQ5Gg1mrFGj2soo3VuMKSbvfR6tMrnj
khKUSl3TWQyKdkuOOf4EzAyxhJdq/hWGvMdwfwH2q4UzjjcaRHDP54oBH6WHxyAn
UUkJTFfJo2i8jFE/um09igLr5sEaKMiHgjQIdUScuQRGqKhqS9e4tPpTnfP4ayvM
zVvD1ptUnaV4O9+GkpEwx/vLVXItMO2KNXXKADYBuWcY9g+Dlpp637radmLJjnvj
bCJipWjuVzUEQvIvf3x1dZ4b899Bycp4uScmdz5brfxkhLaA9vchnmr+F7aAuwwK
N5X2Ep6n5d1M0XjA02Z9Zi2W4NkZiNBBmb/f6QIDAQABAoIBAAPzPANNGv4L98jx
+C3o/F/YbyE1sXmV9lP8I1nr1+FbETvEleQSHGL1aPpIVbZ6/gugXdP3E4qFqmUS
ik1hQtRFWJVuDPwk5ghiPHxwIYLd+cRFHiHsT96isWzNJTiDinWpN/5XKkE5QfTe
KaJc4tGJebEG1LhsgtUTxbTImCPxYvKUItDlApOusVvhARjqCnXunNEu5iDiADHH
Wsv3eSPdWkdF5Jjgt/bI4I9XmagX3e1z6ZQiGvdBwCc8ccwkU6yTswXgWCPqyw/t
lbTFqE19lEoHGTYYElKaHUo9hCmI3HZS69ShYKG7dMT9dVLhzRlNx7AzZcYWh8Mx
Ptc8OY0CgYEA1LJe5EpfJ/XvzbiVtNiq07CGhlQj62DAH+XpyqtWHHrUNgMbnBZS
29had9h2NyfIFDIZAKPGWRuSB6PSyDR6w5Sugh5nRoXshzaFr1pAHmo18s+QELjj
XyccwivxRXurwmdDL5Bx0YCKII4LJyE3CBlJzq0/wOxvi+iKDRG+TIUCgYEAyDG8
DXk+E6f9Vd4phaN3sLVDd228U/NNuEr+K74AF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