Skip to main content

crypto_profile/
algorithm.rs

1//! The algorithms the crate names: signature keys, TLS signature schemes, key-exchange groups,
2//! cipher suites, hashes, TLS versions, MACs, KDFs, key agreements and AEADs.
3use std::fmt;
4use std::str::FromStr;
5
6/// A signature key algorithm: what a key is generated as, and what its CSR is signed with.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8#[non_exhaustive]
9pub enum SignatureAlgorithm {
10    /// ML-DSA-87 (FIPS 204).
11    MlDsa87,
12    /// ECDSA on P-256 with SHA-256.
13    EcdsaP256Sha256,
14    /// ECDSA on P-384 with SHA-384.
15    EcdsaP384Sha384,
16    /// ECDSA on P-521 with SHA-384.
17    EcdsaP521Sha384,
18    /// ECDSA on P-521 with SHA-512.
19    EcdsaP521Sha512,
20    /// Ed25519 (FIPS 186-5 EdDSA).
21    Ed25519,
22    /// A 2048-bit RSA key; its CSR is signed RSASSA-PKCS1-v1_5 with SHA-384.
23    Rsa2048Sha384,
24    /// A 3072-bit RSA key; its CSR is signed RSASSA-PKCS1-v1_5 with SHA-384.
25    Rsa3072Sha384,
26    /// A 4096-bit RSA key; its CSR is signed RSASSA-PKCS1-v1_5 with SHA-384.
27    Rsa4096Sha384,
28    /// A 2048-bit RSA key that signs RSASSA-PSS with SHA-384, MGF1 with SHA-384 and a 48-byte
29    /// salt (RFC 8017 §8.1). Outside TLS only: no TLS key list or certificate request takes it.
30    Rsa2048Sha384Pss,
31    /// A 3072-bit RSA key that signs RSASSA-PSS with SHA-384, MGF1 with SHA-384 and a 48-byte
32    /// salt (RFC 8017 §8.1). Outside TLS only: no TLS key list or certificate request takes it.
33    Rsa3072Sha384Pss,
34    /// A 4096-bit RSA key that signs RSASSA-PSS with SHA-384, MGF1 with SHA-384 and a 48-byte
35    /// salt (RFC 8017 §8.1). Outside TLS only: no TLS key list or certificate request takes it.
36    Rsa4096Sha384Pss,
37}
38
39impl SignatureAlgorithm {
40    /// Every signature key algorithm.
41    pub const ALL: &'static [SignatureAlgorithm] = &[
42        SignatureAlgorithm::MlDsa87,
43        SignatureAlgorithm::EcdsaP256Sha256,
44        SignatureAlgorithm::EcdsaP384Sha384,
45        SignatureAlgorithm::EcdsaP521Sha384,
46        SignatureAlgorithm::EcdsaP521Sha512,
47        SignatureAlgorithm::Ed25519,
48        SignatureAlgorithm::Rsa2048Sha384,
49        SignatureAlgorithm::Rsa3072Sha384,
50        SignatureAlgorithm::Rsa4096Sha384,
51        SignatureAlgorithm::Rsa2048Sha384Pss,
52        SignatureAlgorithm::Rsa3072Sha384Pss,
53        SignatureAlgorithm::Rsa4096Sha384Pss,
54    ];
55
56    /// The position of `self` in [`Self::ALL`].
57    #[cfg(test)]
58    pub(crate) const fn ordinal(self) -> usize {
59        match self {
60            SignatureAlgorithm::MlDsa87 => 0,
61            SignatureAlgorithm::EcdsaP256Sha256 => 1,
62            SignatureAlgorithm::EcdsaP384Sha384 => 2,
63            SignatureAlgorithm::EcdsaP521Sha384 => 3,
64            SignatureAlgorithm::EcdsaP521Sha512 => 4,
65            SignatureAlgorithm::Ed25519 => 5,
66            SignatureAlgorithm::Rsa2048Sha384 => 6,
67            SignatureAlgorithm::Rsa3072Sha384 => 7,
68            SignatureAlgorithm::Rsa4096Sha384 => 8,
69            SignatureAlgorithm::Rsa2048Sha384Pss => 9,
70            SignatureAlgorithm::Rsa3072Sha384Pss => 10,
71            SignatureAlgorithm::Rsa4096Sha384Pss => 11,
72        }
73    }
74
75    /// The algorithm's stable configuration name.
76    pub const fn as_str(self) -> &'static str {
77        match self {
78            SignatureAlgorithm::MlDsa87 => "ml-dsa-87",
79            SignatureAlgorithm::EcdsaP256Sha256 => "ecdsa-p256-sha256",
80            SignatureAlgorithm::EcdsaP384Sha384 => "ecdsa-p384-sha384",
81            SignatureAlgorithm::EcdsaP521Sha384 => "ecdsa-p521-sha384",
82            SignatureAlgorithm::EcdsaP521Sha512 => "ecdsa-p521-sha512",
83            SignatureAlgorithm::Ed25519 => "ed25519",
84            SignatureAlgorithm::Rsa2048Sha384 => "rsa2048-sha384",
85            SignatureAlgorithm::Rsa3072Sha384 => "rsa3072-sha384",
86            SignatureAlgorithm::Rsa4096Sha384 => "rsa4096-sha384",
87            SignatureAlgorithm::Rsa2048Sha384Pss => "rsa2048-sha384-pss",
88            SignatureAlgorithm::Rsa3072Sha384Pss => "rsa3072-sha384-pss",
89            SignatureAlgorithm::Rsa4096Sha384Pss => "rsa4096-sha384-pss",
90        }
91    }
92
93    /// The X.509 signature-algorithm OID a CSR or certificate signed by this key carries
94    /// (RFC 5758, RFC 8410, RFC 4055, and draft-ietf-lamps-dilithium-certificates for ML-DSA).
95    /// For an RSA-PSS variant it is `id-RSASSA-PSS` (RFC 4055 §3.1), whose parameters name the
96    /// hash, MGF1 hash and salt length.
97    pub const fn signature_oid(self) -> &'static str {
98        match self {
99            SignatureAlgorithm::MlDsa87 => "2.16.840.1.101.3.4.3.19",
100            SignatureAlgorithm::EcdsaP256Sha256 => "1.2.840.10045.4.3.2",
101            SignatureAlgorithm::EcdsaP384Sha384 | SignatureAlgorithm::EcdsaP521Sha384 => {
102                "1.2.840.10045.4.3.3"
103            }
104            SignatureAlgorithm::EcdsaP521Sha512 => "1.2.840.10045.4.3.4",
105            SignatureAlgorithm::Ed25519 => "1.3.101.112",
106            SignatureAlgorithm::Rsa2048Sha384
107            | SignatureAlgorithm::Rsa3072Sha384
108            | SignatureAlgorithm::Rsa4096Sha384 => "1.2.840.113549.1.1.12",
109            SignatureAlgorithm::Rsa2048Sha384Pss
110            | SignatureAlgorithm::Rsa3072Sha384Pss
111            | SignatureAlgorithm::Rsa4096Sha384Pss => "1.2.840.113549.1.1.10",
112        }
113    }
114
115    /// The TLS signature scheme this crate pairs with a key of this algorithm: the scheme the key
116    /// signs a handshake with when the peer offers this scheme alone. `None` for an algorithm that
117    /// is not a TLS key algorithm: the RSA-PSS variants, which sign outside TLS only.
118    ///
119    /// An ECDSA, Ed25519 or ML-DSA key has no other scheme. An RSA key's scheme comes from the
120    /// peer's offer, whatever the key's CSR was signed with: rustls signs with the first of RSA-PSS
121    /// with SHA-512, SHA-384 and SHA-256, then PKCS#1 v1.5 with SHA-512, SHA-384 and SHA-256, that
122    /// the peer offers (`RSA_SCHEMES` in `crypto-profile/src/provider/sign.rs`, the order rustls
123    /// 0.23.46 uses), and TLS 1.3 admits only the RSA-PSS ones (`src/enums.rs:554-579`). So an RSA
124    /// key signs with RSA-PSS with SHA-384 only when the peer offers it and does not offer RSA-PSS
125    /// with SHA-512.
126    pub const fn tls_scheme(self) -> Option<TlsSignatureScheme> {
127        match self {
128            SignatureAlgorithm::MlDsa87 => Some(TlsSignatureScheme::MlDsa87),
129            SignatureAlgorithm::EcdsaP256Sha256 => Some(TlsSignatureScheme::EcdsaNistp256Sha256),
130            SignatureAlgorithm::EcdsaP384Sha384 => Some(TlsSignatureScheme::EcdsaNistp384Sha384),
131            SignatureAlgorithm::EcdsaP521Sha384 | SignatureAlgorithm::EcdsaP521Sha512 => {
132                Some(TlsSignatureScheme::EcdsaNistp521Sha512)
133            }
134            SignatureAlgorithm::Ed25519 => Some(TlsSignatureScheme::Ed25519),
135            SignatureAlgorithm::Rsa2048Sha384
136            | SignatureAlgorithm::Rsa3072Sha384
137            | SignatureAlgorithm::Rsa4096Sha384 => Some(TlsSignatureScheme::RsaPssSha384),
138            SignatureAlgorithm::Rsa2048Sha384Pss
139            | SignatureAlgorithm::Rsa3072Sha384Pss
140            | SignatureAlgorithm::Rsa4096Sha384Pss => None,
141        }
142    }
143}
144
145/// A name that is not one of the crate's algorithms of the type parsed.
146#[derive(Debug, Clone, PartialEq, Eq)]
147#[non_exhaustive]
148pub struct ParseAlgorithmError(pub String);
149
150impl fmt::Display for ParseAlgorithmError {
151    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152        write!(f, "unknown algorithm name {:?}", self.0)
153    }
154}
155
156impl std::error::Error for ParseAlgorithmError {}
157
158impl FromStr for SignatureAlgorithm {
159    type Err = ParseAlgorithmError;
160    fn from_str(s: &str) -> Result<Self, Self::Err> {
161        SignatureAlgorithm::ALL
162            .iter()
163            .copied()
164            .find(|a| a.as_str() == s)
165            .ok_or_else(|| ParseAlgorithmError(s.to_string()))
166    }
167}
168
169impl fmt::Display for SignatureAlgorithm {
170    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171        f.write_str(self.as_str())
172    }
173}
174
175/// A TLS handshake signature scheme.
176#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
177#[non_exhaustive]
178pub enum TlsSignatureScheme {
179    /// `ecdsa_secp256r1_sha256`.
180    EcdsaNistp256Sha256,
181    /// `ecdsa_secp384r1_sha384`.
182    EcdsaNistp384Sha384,
183    /// `ecdsa_secp521r1_sha512`.
184    EcdsaNistp521Sha512,
185    /// `ed25519`.
186    Ed25519,
187    /// `rsa_pss_rsae_sha256`.
188    RsaPssSha256,
189    /// `rsa_pss_rsae_sha384`.
190    RsaPssSha384,
191    /// `rsa_pss_rsae_sha512`.
192    RsaPssSha512,
193    /// `rsa_pkcs1_sha256`.
194    RsaPkcs1Sha256,
195    /// `rsa_pkcs1_sha384`.
196    RsaPkcs1Sha384,
197    /// `rsa_pkcs1_sha512`.
198    RsaPkcs1Sha512,
199    /// `mldsa87`.
200    MlDsa87,
201}
202
203impl TlsSignatureScheme {
204    /// Whether a handshake at `v` can sign with this scheme. RFC 8446 §4.2.3 excludes RSA
205    /// PKCS#1 v1.5 from TLS 1.3 handshake signatures; ML-DSA is defined for TLS 1.3 only.
206    pub const fn usable_in(self, v: TlsVersion) -> bool {
207        match self {
208            TlsSignatureScheme::RsaPkcs1Sha256
209            | TlsSignatureScheme::RsaPkcs1Sha384
210            | TlsSignatureScheme::RsaPkcs1Sha512 => matches!(v, TlsVersion::Tls12),
211            TlsSignatureScheme::MlDsa87 => matches!(v, TlsVersion::Tls13),
212            TlsSignatureScheme::EcdsaNistp256Sha256
213            | TlsSignatureScheme::EcdsaNistp384Sha384
214            | TlsSignatureScheme::EcdsaNistp521Sha512
215            | TlsSignatureScheme::Ed25519
216            | TlsSignatureScheme::RsaPssSha256
217            | TlsSignatureScheme::RsaPssSha384
218            | TlsSignatureScheme::RsaPssSha512 => true,
219        }
220    }
221
222    /// The IANA TLS SignatureScheme codepoint.
223    pub const fn iana(self) -> u16 {
224        match self {
225            TlsSignatureScheme::EcdsaNistp256Sha256 => 0x0403,
226            TlsSignatureScheme::EcdsaNistp384Sha384 => 0x0503,
227            TlsSignatureScheme::EcdsaNistp521Sha512 => 0x0603,
228            TlsSignatureScheme::Ed25519 => 0x0807,
229            TlsSignatureScheme::RsaPssSha256 => 0x0804,
230            TlsSignatureScheme::RsaPssSha384 => 0x0805,
231            TlsSignatureScheme::RsaPssSha512 => 0x0806,
232            TlsSignatureScheme::RsaPkcs1Sha256 => 0x0401,
233            TlsSignatureScheme::RsaPkcs1Sha384 => 0x0501,
234            TlsSignatureScheme::RsaPkcs1Sha512 => 0x0601,
235            TlsSignatureScheme::MlDsa87 => 0x0906,
236        }
237    }
238
239    /// The scheme's rank in the canonical order every profile lists its schemes in, and in which a
240    /// backend carries a policy's schemes: 0 first, one rank per scheme.
241    pub const fn preference(self) -> u8 {
242        match self {
243            TlsSignatureScheme::MlDsa87 => 0,
244            TlsSignatureScheme::EcdsaNistp384Sha384 => 1,
245            TlsSignatureScheme::EcdsaNistp256Sha256 => 2,
246            TlsSignatureScheme::EcdsaNistp521Sha512 => 3,
247            TlsSignatureScheme::Ed25519 => 4,
248            TlsSignatureScheme::RsaPssSha384 => 5,
249            TlsSignatureScheme::RsaPssSha512 => 6,
250            TlsSignatureScheme::RsaPssSha256 => 7,
251            TlsSignatureScheme::RsaPkcs1Sha384 => 8,
252            TlsSignatureScheme::RsaPkcs1Sha512 => 9,
253            TlsSignatureScheme::RsaPkcs1Sha256 => 10,
254        }
255    }
256
257    /// Every TLS signature scheme.
258    pub const ALL: &'static [TlsSignatureScheme] = &[
259        TlsSignatureScheme::EcdsaNistp256Sha256,
260        TlsSignatureScheme::EcdsaNistp384Sha384,
261        TlsSignatureScheme::EcdsaNistp521Sha512,
262        TlsSignatureScheme::Ed25519,
263        TlsSignatureScheme::RsaPssSha256,
264        TlsSignatureScheme::RsaPssSha384,
265        TlsSignatureScheme::RsaPssSha512,
266        TlsSignatureScheme::RsaPkcs1Sha256,
267        TlsSignatureScheme::RsaPkcs1Sha384,
268        TlsSignatureScheme::RsaPkcs1Sha512,
269        TlsSignatureScheme::MlDsa87,
270    ];
271
272    /// The position of `self` in [`Self::ALL`].
273    #[cfg(test)]
274    pub(crate) const fn ordinal(self) -> usize {
275        match self {
276            TlsSignatureScheme::EcdsaNistp256Sha256 => 0,
277            TlsSignatureScheme::EcdsaNistp384Sha384 => 1,
278            TlsSignatureScheme::EcdsaNistp521Sha512 => 2,
279            TlsSignatureScheme::Ed25519 => 3,
280            TlsSignatureScheme::RsaPssSha256 => 4,
281            TlsSignatureScheme::RsaPssSha384 => 5,
282            TlsSignatureScheme::RsaPssSha512 => 6,
283            TlsSignatureScheme::RsaPkcs1Sha256 => 7,
284            TlsSignatureScheme::RsaPkcs1Sha384 => 8,
285            TlsSignatureScheme::RsaPkcs1Sha512 => 9,
286            TlsSignatureScheme::MlDsa87 => 10,
287        }
288    }
289}
290
291// `PeerVerifierIdentity::Owned::handshake_schemes` is a u64 with bit `preference()` per scheme,
292// and the preferences are exactly `0..ALL.len()`.
293const _: () = assert!(TlsSignatureScheme::ALL.len() <= u64::BITS as usize);
294
295/// A TLS cipher suite.
296#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
297#[non_exhaustive]
298pub enum CipherSuite {
299    /// `TLS_AES_256_GCM_SHA384`.
300    Tls13Aes256GcmSha384,
301    /// `TLS_AES_128_GCM_SHA256`.
302    Tls13Aes128GcmSha256,
303    /// `TLS_CHACHA20_POLY1305_SHA256`.
304    Tls13Chacha20Poly1305Sha256,
305    /// `TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384`.
306    Tls12EcdheEcdsaAes256GcmSha384,
307    /// `TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256`.
308    Tls12EcdheEcdsaAes128GcmSha256,
309    /// `TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256`.
310    Tls12EcdheEcdsaChacha20Poly1305Sha256,
311    /// `TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384`.
312    Tls12EcdheRsaAes256GcmSha384,
313    /// `TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256`.
314    Tls12EcdheRsaAes128GcmSha256,
315    /// `TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256`.
316    Tls12EcdheRsaChacha20Poly1305Sha256,
317}
318
319impl CipherSuite {
320    /// Whether a handshake under this suite can sign with `t`. A TLS 1.2 suite fixes the
321    /// authentication algorithm (ECDSA or EdDSA for `EcdheEcdsa`, RSA for `EcdheRsa`); a TLS 1.3
322    /// suite does not.
323    pub const fn signs_with(self, t: TlsSignatureScheme) -> bool {
324        use TlsSignatureScheme as T;
325        match self {
326            CipherSuite::Tls13Aes256GcmSha384
327            | CipherSuite::Tls13Aes128GcmSha256
328            | CipherSuite::Tls13Chacha20Poly1305Sha256 => t.usable_in(TlsVersion::Tls13),
329            CipherSuite::Tls12EcdheEcdsaAes256GcmSha384
330            | CipherSuite::Tls12EcdheEcdsaAes128GcmSha256
331            | CipherSuite::Tls12EcdheEcdsaChacha20Poly1305Sha256 => matches!(
332                t,
333                T::EcdsaNistp256Sha256
334                    | T::EcdsaNistp384Sha384
335                    | T::EcdsaNistp521Sha512
336                    | T::Ed25519
337            ),
338            CipherSuite::Tls12EcdheRsaAes256GcmSha384
339            | CipherSuite::Tls12EcdheRsaAes128GcmSha256
340            | CipherSuite::Tls12EcdheRsaChacha20Poly1305Sha256 => matches!(
341                t,
342                T::RsaPssSha256
343                    | T::RsaPssSha384
344                    | T::RsaPssSha512
345                    | T::RsaPkcs1Sha256
346                    | T::RsaPkcs1Sha384
347                    | T::RsaPkcs1Sha512
348            ),
349        }
350    }
351
352    /// Every cipher suite.
353    pub const ALL: &'static [CipherSuite] = &[
354        CipherSuite::Tls13Aes256GcmSha384,
355        CipherSuite::Tls13Aes128GcmSha256,
356        CipherSuite::Tls13Chacha20Poly1305Sha256,
357        CipherSuite::Tls12EcdheEcdsaAes256GcmSha384,
358        CipherSuite::Tls12EcdheEcdsaAes128GcmSha256,
359        CipherSuite::Tls12EcdheEcdsaChacha20Poly1305Sha256,
360        CipherSuite::Tls12EcdheRsaAes256GcmSha384,
361        CipherSuite::Tls12EcdheRsaAes128GcmSha256,
362        CipherSuite::Tls12EcdheRsaChacha20Poly1305Sha256,
363    ];
364
365    /// The position of `self` in [`Self::ALL`].
366    #[cfg(test)]
367    pub(crate) const fn ordinal(self) -> usize {
368        match self {
369            CipherSuite::Tls13Aes256GcmSha384 => 0,
370            CipherSuite::Tls13Aes128GcmSha256 => 1,
371            CipherSuite::Tls13Chacha20Poly1305Sha256 => 2,
372            CipherSuite::Tls12EcdheEcdsaAes256GcmSha384 => 3,
373            CipherSuite::Tls12EcdheEcdsaAes128GcmSha256 => 4,
374            CipherSuite::Tls12EcdheEcdsaChacha20Poly1305Sha256 => 5,
375            CipherSuite::Tls12EcdheRsaAes256GcmSha384 => 6,
376            CipherSuite::Tls12EcdheRsaAes128GcmSha256 => 7,
377            CipherSuite::Tls12EcdheRsaChacha20Poly1305Sha256 => 8,
378        }
379    }
380
381    /// The IANA TLS Cipher Suite codepoint.
382    pub const fn iana(self) -> u16 {
383        match self {
384            CipherSuite::Tls13Aes256GcmSha384 => 0x1302,
385            CipherSuite::Tls13Aes128GcmSha256 => 0x1301,
386            CipherSuite::Tls13Chacha20Poly1305Sha256 => 0x1303,
387            CipherSuite::Tls12EcdheEcdsaAes256GcmSha384 => 0xC02C,
388            CipherSuite::Tls12EcdheEcdsaAes128GcmSha256 => 0xC02B,
389            CipherSuite::Tls12EcdheEcdsaChacha20Poly1305Sha256 => 0xCCA9,
390            CipherSuite::Tls12EcdheRsaAes256GcmSha384 => 0xC030,
391            CipherSuite::Tls12EcdheRsaAes128GcmSha256 => 0xC02F,
392            CipherSuite::Tls12EcdheRsaChacha20Poly1305Sha256 => 0xCCA8,
393        }
394    }
395
396    /// The TLS version the suite belongs to.
397    pub const fn version(self) -> TlsVersion {
398        match self {
399            CipherSuite::Tls13Aes256GcmSha384
400            | CipherSuite::Tls13Aes128GcmSha256
401            | CipherSuite::Tls13Chacha20Poly1305Sha256 => TlsVersion::Tls13,
402            CipherSuite::Tls12EcdheEcdsaAes256GcmSha384
403            | CipherSuite::Tls12EcdheEcdsaAes128GcmSha256
404            | CipherSuite::Tls12EcdheEcdsaChacha20Poly1305Sha256
405            | CipherSuite::Tls12EcdheRsaAes256GcmSha384
406            | CipherSuite::Tls12EcdheRsaAes128GcmSha256
407            | CipherSuite::Tls12EcdheRsaChacha20Poly1305Sha256 => TlsVersion::Tls12,
408        }
409    }
410}
411
412/// A TLS key-exchange group.
413#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
414#[non_exhaustive]
415pub enum KxGroup {
416    /// ML-KEM-1024 (FIPS 203).
417    MlKem1024,
418    /// The P-384 + ML-KEM-1024 hybrid (RFC 10024 §4.1-4.3; codepoint §7.3).
419    Secp384r1MlKem1024,
420    /// The X25519 + ML-KEM-768 hybrid.
421    X25519MlKem768,
422    /// The P-256 + ML-KEM-768 hybrid.
423    Secp256r1MlKem768,
424    /// ECDH on P-384.
425    Secp384r1,
426    /// ECDH on P-256.
427    Secp256r1,
428    /// X25519.
429    X25519,
430}
431
432impl KxGroup {
433    /// Whether a handshake at `v` can use this group. TLS 1.2 has no ML-KEM or hybrid key
434    /// exchange.
435    pub const fn usable_in(self, v: TlsVersion) -> bool {
436        match v {
437            TlsVersion::Tls13 => true,
438            TlsVersion::Tls12 => match self {
439                KxGroup::Secp384r1 | KxGroup::Secp256r1 | KxGroup::X25519 => true,
440                KxGroup::MlKem1024
441                | KxGroup::Secp384r1MlKem1024
442                | KxGroup::X25519MlKem768
443                | KxGroup::Secp256r1MlKem768 => false,
444            },
445        }
446    }
447
448    /// Whether the group's key exchange includes ML-KEM: pure ML-KEM or a hybrid.
449    pub const fn is_post_quantum(self) -> bool {
450        match self {
451            KxGroup::MlKem1024
452            | KxGroup::Secp384r1MlKem1024
453            | KxGroup::X25519MlKem768
454            | KxGroup::Secp256r1MlKem768 => true,
455            KxGroup::Secp384r1 | KxGroup::Secp256r1 | KxGroup::X25519 => false,
456        }
457    }
458
459    /// The IANA TLS Supported Groups codepoint.
460    pub const fn iana(self) -> u16 {
461        match self {
462            KxGroup::MlKem1024 => 0x0202,
463            KxGroup::Secp384r1MlKem1024 => 0x11ED,
464            KxGroup::X25519MlKem768 => 0x11EC,
465            KxGroup::Secp256r1MlKem768 => 0x11EB,
466            KxGroup::Secp384r1 => 0x0018,
467            KxGroup::Secp256r1 => 0x0017,
468            KxGroup::X25519 => 0x001D,
469        }
470    }
471
472    /// Every key-exchange group.
473    pub const ALL: &'static [KxGroup] = &[
474        KxGroup::MlKem1024,
475        KxGroup::Secp384r1MlKem1024,
476        KxGroup::X25519MlKem768,
477        KxGroup::Secp256r1MlKem768,
478        KxGroup::Secp384r1,
479        KxGroup::Secp256r1,
480        KxGroup::X25519,
481    ];
482
483    /// The position of `self` in [`Self::ALL`].
484    #[cfg(test)]
485    pub(crate) const fn ordinal(self) -> usize {
486        match self {
487            KxGroup::MlKem1024 => 0,
488            KxGroup::Secp384r1MlKem1024 => 1,
489            KxGroup::X25519MlKem768 => 2,
490            KxGroup::Secp256r1MlKem768 => 3,
491            KxGroup::Secp384r1 => 4,
492            KxGroup::Secp256r1 => 5,
493            KxGroup::X25519 => 6,
494        }
495    }
496}
497
498/// A hash function: SHA-2 (FIPS 180-4) or SHA-3 (FIPS 202), with its full-length output.
499#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
500#[non_exhaustive]
501pub enum HashAlgorithm {
502    /// SHA-256 (FIPS 180-4).
503    Sha256,
504    /// SHA-384 (FIPS 180-4).
505    Sha384,
506    /// SHA-512 (FIPS 180-4).
507    Sha512,
508    /// SHA3-256 (FIPS 202).
509    Sha3_256,
510    /// SHA3-384 (FIPS 202).
511    Sha3_384,
512    /// SHA3-512 (FIPS 202).
513    Sha3_512,
514}
515
516impl HashAlgorithm {
517    /// Every hash function.
518    pub const ALL: &'static [HashAlgorithm] = &[
519        HashAlgorithm::Sha256,
520        HashAlgorithm::Sha384,
521        HashAlgorithm::Sha512,
522        HashAlgorithm::Sha3_256,
523        HashAlgorithm::Sha3_384,
524        HashAlgorithm::Sha3_512,
525    ];
526
527    /// The position of `self` in [`Self::ALL`].
528    #[cfg(test)]
529    pub(crate) const fn ordinal(self) -> usize {
530        match self {
531            HashAlgorithm::Sha256 => 0,
532            HashAlgorithm::Sha384 => 1,
533            HashAlgorithm::Sha512 => 2,
534            HashAlgorithm::Sha3_256 => 3,
535            HashAlgorithm::Sha3_384 => 4,
536            HashAlgorithm::Sha3_512 => 5,
537        }
538    }
539
540    /// The algorithm's stable configuration name.
541    pub const fn as_str(self) -> &'static str {
542        match self {
543            HashAlgorithm::Sha256 => "sha256",
544            HashAlgorithm::Sha384 => "sha384",
545            HashAlgorithm::Sha512 => "sha512",
546            HashAlgorithm::Sha3_256 => "sha3-256",
547            HashAlgorithm::Sha3_384 => "sha3-384",
548            HashAlgorithm::Sha3_512 => "sha3-512",
549        }
550    }
551
552    /// The digest length in bytes.
553    pub const fn output_len(self) -> usize {
554        match self {
555            HashAlgorithm::Sha256 | HashAlgorithm::Sha3_256 => 32,
556            HashAlgorithm::Sha384 | HashAlgorithm::Sha3_384 => 48,
557            HashAlgorithm::Sha512 | HashAlgorithm::Sha3_512 => 64,
558        }
559    }
560}
561
562impl FromStr for HashAlgorithm {
563    type Err = ParseAlgorithmError;
564    fn from_str(s: &str) -> Result<Self, Self::Err> {
565        HashAlgorithm::ALL
566            .iter()
567            .copied()
568            .find(|a| a.as_str() == s)
569            .ok_or_else(|| ParseAlgorithmError(s.to_string()))
570    }
571}
572
573impl fmt::Display for HashAlgorithm {
574    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
575        f.write_str(self.as_str())
576    }
577}
578
579/// A message authentication code.
580#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
581#[non_exhaustive]
582pub enum MacAlgorithm {
583    /// HMAC with SHA-256 (FIPS 198-1).
584    HmacSha256,
585    /// HMAC with SHA-384 (FIPS 198-1).
586    HmacSha384,
587    /// HMAC with SHA-512 (FIPS 198-1).
588    HmacSha512,
589}
590
591impl MacAlgorithm {
592    /// Every message authentication code.
593    pub const ALL: &'static [MacAlgorithm] = &[
594        MacAlgorithm::HmacSha256,
595        MacAlgorithm::HmacSha384,
596        MacAlgorithm::HmacSha512,
597    ];
598
599    /// The position of `self` in [`Self::ALL`].
600    #[cfg(test)]
601    pub(crate) const fn ordinal(self) -> usize {
602        match self {
603            MacAlgorithm::HmacSha256 => 0,
604            MacAlgorithm::HmacSha384 => 1,
605            MacAlgorithm::HmacSha512 => 2,
606        }
607    }
608
609    /// The hash function the MAC is built on.
610    pub const fn hash(self) -> HashAlgorithm {
611        match self {
612            MacAlgorithm::HmacSha256 => HashAlgorithm::Sha256,
613            MacAlgorithm::HmacSha384 => HashAlgorithm::Sha384,
614            MacAlgorithm::HmacSha512 => HashAlgorithm::Sha512,
615        }
616    }
617
618    /// The full tag length in bytes.
619    pub const fn tag_len(self) -> usize {
620        self.hash().output_len()
621    }
622}
623
624/// A key-derivation function.
625#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
626#[non_exhaustive]
627pub enum KdfAlgorithm {
628    /// HKDF with SHA-256 (RFC 5869; SP 800-56C Rev. 2 §5).
629    HkdfSha256,
630    /// HKDF with SHA-384 (RFC 5869; SP 800-56C Rev. 2 §5).
631    HkdfSha384,
632    /// HKDF with SHA-512 (RFC 5869; SP 800-56C Rev. 2 §5).
633    HkdfSha512,
634    /// The one-step KDF with SHA-256 as its auxiliary function (SP 800-56C Rev. 2 §4.1, option 1).
635    OneStepSha256,
636    /// The one-step KDF with SHA-384 as its auxiliary function (SP 800-56C Rev. 2 §4.1, option 1).
637    OneStepSha384,
638    /// The one-step KDF with SHA-512 as its auxiliary function (SP 800-56C Rev. 2 §4.1, option 1).
639    OneStepSha512,
640}
641
642impl KdfAlgorithm {
643    /// Every key-derivation function.
644    pub const ALL: &'static [KdfAlgorithm] = &[
645        KdfAlgorithm::HkdfSha256,
646        KdfAlgorithm::HkdfSha384,
647        KdfAlgorithm::HkdfSha512,
648        KdfAlgorithm::OneStepSha256,
649        KdfAlgorithm::OneStepSha384,
650        KdfAlgorithm::OneStepSha512,
651    ];
652
653    /// The position of `self` in [`Self::ALL`].
654    #[cfg(test)]
655    pub(crate) const fn ordinal(self) -> usize {
656        match self {
657            KdfAlgorithm::HkdfSha256 => 0,
658            KdfAlgorithm::HkdfSha384 => 1,
659            KdfAlgorithm::HkdfSha512 => 2,
660            KdfAlgorithm::OneStepSha256 => 3,
661            KdfAlgorithm::OneStepSha384 => 4,
662            KdfAlgorithm::OneStepSha512 => 5,
663        }
664    }
665
666    /// The hash function the KDF is built on: HKDF's HMAC, or the one-step KDF's auxiliary
667    /// function.
668    pub const fn hash(self) -> HashAlgorithm {
669        match self {
670            KdfAlgorithm::HkdfSha256 | KdfAlgorithm::OneStepSha256 => HashAlgorithm::Sha256,
671            KdfAlgorithm::HkdfSha384 | KdfAlgorithm::OneStepSha384 => HashAlgorithm::Sha384,
672            KdfAlgorithm::HkdfSha512 | KdfAlgorithm::OneStepSha512 => HashAlgorithm::Sha512,
673        }
674    }
675
676    /// The longest output in bytes. HKDF: 255 times the hash length (RFC 5869 §2.3). The one-step
677    /// KDF: 2^30 bytes, the bound AWS-LC's `SSKDF` enforces on both module lines
678    /// (`SSKDF_MAX_INPUT_LEN`, `crypto/fipsmodule/kdf/sskdf.c`), inside SP 800-56C Rev. 2 §4.1's
679    /// (2^32 − 1) × HashLen bits.
680    pub const fn max_output_len(self) -> usize {
681        match self {
682            KdfAlgorithm::HkdfSha256 | KdfAlgorithm::HkdfSha384 | KdfAlgorithm::HkdfSha512 => {
683                255 * self.hash().output_len()
684            }
685            KdfAlgorithm::OneStepSha256
686            | KdfAlgorithm::OneStepSha384
687            | KdfAlgorithm::OneStepSha512 => 1 << 30,
688        }
689    }
690}
691
692/// A key-agreement algorithm outside TLS: Diffie-Hellman on a curve (SP 800-56A Rev. 3; RFC
693/// 7748). TLS key exchange is [`KxGroup`].
694#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
695#[non_exhaustive]
696pub enum KeyAgreementAlgorithm {
697    /// ECDH on P-256 (SP 800-56A Rev. 3, SP 800-186).
698    EcdhP256,
699    /// ECDH on P-384 (SP 800-56A Rev. 3, SP 800-186).
700    EcdhP384,
701    /// ECDH on P-521 (SP 800-56A Rev. 3, SP 800-186).
702    EcdhP521,
703    /// X25519 (RFC 7748).
704    X25519,
705}
706
707impl KeyAgreementAlgorithm {
708    /// Every key-agreement algorithm.
709    pub const ALL: &'static [KeyAgreementAlgorithm] = &[
710        KeyAgreementAlgorithm::EcdhP256,
711        KeyAgreementAlgorithm::EcdhP384,
712        KeyAgreementAlgorithm::EcdhP521,
713        KeyAgreementAlgorithm::X25519,
714    ];
715
716    /// The position of `self` in [`Self::ALL`].
717    #[cfg(test)]
718    pub(crate) const fn ordinal(self) -> usize {
719        match self {
720            KeyAgreementAlgorithm::EcdhP256 => 0,
721            KeyAgreementAlgorithm::EcdhP384 => 1,
722            KeyAgreementAlgorithm::EcdhP521 => 2,
723            KeyAgreementAlgorithm::X25519 => 3,
724        }
725    }
726
727    /// The algorithm's stable configuration name.
728    pub const fn as_str(self) -> &'static str {
729        match self {
730            KeyAgreementAlgorithm::EcdhP256 => "ecdh-p256",
731            KeyAgreementAlgorithm::EcdhP384 => "ecdh-p384",
732            KeyAgreementAlgorithm::EcdhP521 => "ecdh-p521",
733            KeyAgreementAlgorithm::X25519 => "x25519",
734        }
735    }
736}
737
738impl FromStr for KeyAgreementAlgorithm {
739    type Err = ParseAlgorithmError;
740    fn from_str(s: &str) -> Result<Self, Self::Err> {
741        KeyAgreementAlgorithm::ALL
742            .iter()
743            .copied()
744            .find(|a| a.as_str() == s)
745            .ok_or_else(|| ParseAlgorithmError(s.to_string()))
746    }
747}
748
749impl fmt::Display for KeyAgreementAlgorithm {
750    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
751        f.write_str(self.as_str())
752    }
753}
754
755/// An authenticated-encryption algorithm outside TLS (RFC 5116), with a 96-bit nonce and a 128-bit
756/// tag. TLS record protection is [`CipherSuite`].
757#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
758#[non_exhaustive]
759pub enum AeadAlgorithm {
760    /// AES-128 in Galois/Counter Mode (FIPS 197, SP 800-38D).
761    Aes128Gcm,
762    /// AES-256 in Galois/Counter Mode (FIPS 197, SP 800-38D).
763    Aes256Gcm,
764    /// ChaCha20-Poly1305 (RFC 8439).
765    Chacha20Poly1305,
766}
767
768impl AeadAlgorithm {
769    /// Every AEAD algorithm.
770    pub const ALL: &'static [AeadAlgorithm] = &[
771        AeadAlgorithm::Aes128Gcm,
772        AeadAlgorithm::Aes256Gcm,
773        AeadAlgorithm::Chacha20Poly1305,
774    ];
775
776    /// The position of `self` in [`Self::ALL`].
777    #[cfg(test)]
778    pub(crate) const fn ordinal(self) -> usize {
779        match self {
780            AeadAlgorithm::Aes128Gcm => 0,
781            AeadAlgorithm::Aes256Gcm => 1,
782            AeadAlgorithm::Chacha20Poly1305 => 2,
783        }
784    }
785
786    /// The algorithm's stable configuration name.
787    pub const fn as_str(self) -> &'static str {
788        match self {
789            AeadAlgorithm::Aes128Gcm => "aes-128-gcm",
790            AeadAlgorithm::Aes256Gcm => "aes-256-gcm",
791            AeadAlgorithm::Chacha20Poly1305 => "chacha20-poly1305",
792        }
793    }
794
795    /// The key length in bytes.
796    pub const fn key_len(self) -> usize {
797        match self {
798            AeadAlgorithm::Aes128Gcm => 16,
799            AeadAlgorithm::Aes256Gcm | AeadAlgorithm::Chacha20Poly1305 => 32,
800        }
801    }
802
803    /// The longest plaintext one seal takes, in bytes. AES-GCM: 2^36 − 32, SP 800-38D §5.2.1.1
804    /// (p. 8), len(P) ≤ 2^39 − 256 bits. ChaCha20-Poly1305: RFC 8439 §2.8 gives 274,877,906,880
805    /// and the module refuses that length, so the bound is one byte below it.
806    pub const fn max_plaintext_len(self) -> u64 {
807        match self {
808            AeadAlgorithm::Aes128Gcm | AeadAlgorithm::Aes256Gcm => (1 << 36) - 32,
809            AeadAlgorithm::Chacha20Poly1305 => 274_877_906_879,
810        }
811    }
812}
813
814impl FromStr for AeadAlgorithm {
815    type Err = ParseAlgorithmError;
816    fn from_str(s: &str) -> Result<Self, Self::Err> {
817        AeadAlgorithm::ALL
818            .iter()
819            .copied()
820            .find(|a| a.as_str() == s)
821            .ok_or_else(|| ParseAlgorithmError(s.to_string()))
822    }
823}
824
825impl fmt::Display for AeadAlgorithm {
826    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
827        f.write_str(self.as_str())
828    }
829}
830
831/// A TLS protocol version.
832#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
833#[non_exhaustive]
834pub enum TlsVersion {
835    /// TLS 1.2.
836    Tls12,
837    /// TLS 1.3.
838    Tls13,
839}
840
841impl TlsVersion {
842    /// The TLS ProtocolVersion codepoint.
843    pub const fn iana(self) -> u16 {
844        match self {
845            TlsVersion::Tls12 => 0x0303,
846            TlsVersion::Tls13 => 0x0304,
847        }
848    }
849
850    /// Every TLS version.
851    pub const ALL: &'static [TlsVersion] = &[TlsVersion::Tls12, TlsVersion::Tls13];
852
853    /// The position of `self` in [`Self::ALL`].
854    #[cfg(test)]
855    pub(crate) const fn ordinal(self) -> usize {
856        match self {
857            TlsVersion::Tls12 => 0,
858            TlsVersion::Tls13 => 1,
859        }
860    }
861}
862
863/// Any algorithm the capability table has a cell for.
864#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
865#[non_exhaustive]
866pub enum Algorithm {
867    /// A signature key algorithm.
868    Signature(SignatureAlgorithm),
869    /// A TLS signature scheme.
870    Scheme(TlsSignatureScheme),
871    /// A key-exchange group.
872    Kx(KxGroup),
873    /// A cipher suite.
874    Cipher(CipherSuite),
875    /// A hash function.
876    Hash(HashAlgorithm),
877    /// A TLS version.
878    Protocol(TlsVersion),
879    /// A message authentication code.
880    Mac(MacAlgorithm),
881    /// A key-derivation function.
882    Kdf(KdfAlgorithm),
883    /// A key-agreement algorithm outside TLS.
884    KeyAgreement(KeyAgreementAlgorithm),
885    /// An AEAD algorithm outside TLS.
886    Aead(AeadAlgorithm),
887}
888
889impl Algorithm {
890    /// Every algorithm, in family order.
891    pub fn all() -> Vec<Algorithm> {
892        let mut v = Vec::new();
893        v.extend(
894            SignatureAlgorithm::ALL
895                .iter()
896                .copied()
897                .map(Algorithm::Signature)
898                .collect::<Vec<_>>(),
899        );
900        v.extend(
901            TlsSignatureScheme::ALL
902                .iter()
903                .copied()
904                .map(Algorithm::Scheme)
905                .collect::<Vec<_>>(),
906        );
907        v.extend(
908            KxGroup::ALL
909                .iter()
910                .copied()
911                .map(Algorithm::Kx)
912                .collect::<Vec<_>>(),
913        );
914        v.extend(
915            CipherSuite::ALL
916                .iter()
917                .copied()
918                .map(Algorithm::Cipher)
919                .collect::<Vec<_>>(),
920        );
921        v.extend(
922            HashAlgorithm::ALL
923                .iter()
924                .copied()
925                .map(Algorithm::Hash)
926                .collect::<Vec<_>>(),
927        );
928        v.extend(
929            TlsVersion::ALL
930                .iter()
931                .copied()
932                .map(Algorithm::Protocol)
933                .collect::<Vec<_>>(),
934        );
935        v.extend(
936            MacAlgorithm::ALL
937                .iter()
938                .copied()
939                .map(Algorithm::Mac)
940                .collect::<Vec<_>>(),
941        );
942        v.extend(
943            KdfAlgorithm::ALL
944                .iter()
945                .copied()
946                .map(Algorithm::Kdf)
947                .collect::<Vec<_>>(),
948        );
949        v.extend(
950            KeyAgreementAlgorithm::ALL
951                .iter()
952                .copied()
953                .map(Algorithm::KeyAgreement)
954                .collect::<Vec<_>>(),
955        );
956        v.extend(
957            AeadAlgorithm::ALL
958                .iter()
959                .copied()
960                .map(Algorithm::Aead)
961                .collect::<Vec<_>>(),
962        );
963        v
964    }
965}
966
967#[cfg(test)]
968mod tests {
969    use super::*;
970
971    #[test]
972    fn usability_helpers_decide_per_version() {
973        use TlsSignatureScheme as T;
974        assert!(KxGroup::Secp384r1.usable_in(TlsVersion::Tls12));
975        assert!(!KxGroup::MlKem1024.usable_in(TlsVersion::Tls12));
976        assert!(KxGroup::MlKem1024.usable_in(TlsVersion::Tls13));
977        assert!(T::RsaPkcs1Sha256.usable_in(TlsVersion::Tls12));
978        assert!(!T::RsaPkcs1Sha256.usable_in(TlsVersion::Tls13));
979        assert!(T::MlDsa87.usable_in(TlsVersion::Tls13));
980        assert!(!T::MlDsa87.usable_in(TlsVersion::Tls12));
981        assert!(T::Ed25519.usable_in(TlsVersion::Tls12));
982        let c = CipherSuite::Tls12EcdheEcdsaAes256GcmSha384;
983        assert!(c.signs_with(T::EcdsaNistp384Sha384));
984        assert!(!c.signs_with(T::RsaPssSha384));
985        let r = CipherSuite::Tls12EcdheRsaAes256GcmSha384;
986        assert!(r.signs_with(T::RsaPkcs1Sha384));
987        assert!(!r.signs_with(T::Ed25519));
988        let t13 = CipherSuite::Tls13Aes256GcmSha384;
989        assert!(t13.signs_with(T::MlDsa87));
990        assert!(!t13.signs_with(T::RsaPkcs1Sha384));
991    }
992
993    #[test]
994    fn preference_is_the_canonical_order() {
995        let mut all = TlsSignatureScheme::ALL.to_vec();
996        all.sort_by_key(|t| t.preference());
997        assert_eq!(
998            all.into_iter()
999                .map(TlsSignatureScheme::iana)
1000                .collect::<Vec<_>>(),
1001            [
1002                0x0906, 0x0503, 0x0403, 0x0603, 0x0807, 0x0805, 0x0806, 0x0804, 0x0501, 0x0601,
1003                0x0401
1004            ]
1005        );
1006        let mut ranks = TlsSignatureScheme::ALL
1007            .iter()
1008            .copied()
1009            .map(TlsSignatureScheme::preference)
1010            .collect::<Vec<_>>();
1011        ranks.sort_unstable();
1012        assert_eq!(ranks, std::array::from_fn::<u8, 11, _>(|i| i as u8));
1013    }
1014
1015    #[test]
1016    fn every_preference_is_a_bit_of_the_handshake_scheme_mask() {
1017        for &t in TlsSignatureScheme::ALL {
1018            assert!(u32::from(t.preference()) < u64::BITS, "{t:?}");
1019            assert!(
1020                usize::from(t.preference()) < TlsSignatureScheme::ALL.len(),
1021                "{t:?}"
1022            );
1023        }
1024    }
1025
1026    #[test]
1027    fn post_quantum_groups_are_the_ml_kem_ones() {
1028        assert_eq!(
1029            KxGroup::ALL
1030                .iter()
1031                .copied()
1032                .map(KxGroup::is_post_quantum)
1033                .collect::<Vec<_>>(),
1034            [true, true, true, true, false, false, false]
1035        );
1036    }
1037
1038    #[test]
1039    fn signature_names_are_stable_and_round_trip() {
1040        assert_eq!(
1041            SignatureAlgorithm::ALL
1042                .iter()
1043                .copied()
1044                .map(SignatureAlgorithm::as_str)
1045                .collect::<Vec<_>>(),
1046            [
1047                "ml-dsa-87",
1048                "ecdsa-p256-sha256",
1049                "ecdsa-p384-sha384",
1050                "ecdsa-p521-sha384",
1051                "ecdsa-p521-sha512",
1052                "ed25519",
1053                "rsa2048-sha384",
1054                "rsa3072-sha384",
1055                "rsa4096-sha384",
1056                "rsa2048-sha384-pss",
1057                "rsa3072-sha384-pss",
1058                "rsa4096-sha384-pss",
1059            ]
1060        );
1061        for &a in SignatureAlgorithm::ALL {
1062            assert_eq!(a.as_str().parse::<SignatureAlgorithm>().unwrap(), a);
1063            assert_eq!(a.to_string(), a.as_str());
1064        }
1065        assert_eq!(
1066            ParseAlgorithmError("p384".to_string()).to_string(),
1067            "unknown algorithm name \"p384\""
1068        );
1069        for bad in [
1070            "",
1071            "p384",
1072            "ML-DSA-87",
1073            "ml-dsa-65",
1074            "rsa-2048",
1075            "ecdsa-p256-sha384",
1076            "rsa3072-pss",
1077            "rsa3072-sha256-pss",
1078            "RSA3072-SHA384-PSS",
1079            "rsa3072-sha384-pss ",
1080        ] {
1081            assert_eq!(
1082                bad.parse::<SignatureAlgorithm>(),
1083                Err(ParseAlgorithmError(bad.to_string())),
1084                "{bad}"
1085            );
1086        }
1087    }
1088
1089    #[test]
1090    fn every_key_algorithm_has_its_tls_scheme() {
1091        use SignatureAlgorithm as S;
1092        use TlsSignatureScheme as T;
1093        let table = [
1094            (S::MlDsa87, Some(T::MlDsa87)),
1095            (S::EcdsaP256Sha256, Some(T::EcdsaNistp256Sha256)),
1096            (S::EcdsaP384Sha384, Some(T::EcdsaNistp384Sha384)),
1097            (S::EcdsaP521Sha384, Some(T::EcdsaNistp521Sha512)),
1098            (S::EcdsaP521Sha512, Some(T::EcdsaNistp521Sha512)),
1099            (S::Ed25519, Some(T::Ed25519)),
1100            (S::Rsa2048Sha384, Some(T::RsaPssSha384)),
1101            (S::Rsa3072Sha384, Some(T::RsaPssSha384)),
1102            (S::Rsa4096Sha384, Some(T::RsaPssSha384)),
1103            (S::Rsa2048Sha384Pss, None),
1104            (S::Rsa3072Sha384Pss, None),
1105            (S::Rsa4096Sha384Pss, None),
1106        ];
1107        assert_eq!(table.len(), SignatureAlgorithm::ALL.len());
1108        for (s, t) in table {
1109            assert_eq!(s.tls_scheme(), t, "{s}");
1110        }
1111    }
1112
1113    #[test]
1114    fn cipher_suites_know_their_version() {
1115        use TlsVersion::{Tls12, Tls13};
1116        assert_eq!(
1117            CipherSuite::ALL
1118                .iter()
1119                .copied()
1120                .map(CipherSuite::version)
1121                .collect::<Vec<_>>(),
1122            [
1123                Tls13, Tls13, Tls13, Tls12, Tls12, Tls12, Tls12, Tls12, Tls12
1124            ]
1125        );
1126    }
1127
1128    #[test]
1129    fn iana_codepoints_are_the_registry_values() {
1130        use CipherSuite as C;
1131        use KxGroup as K;
1132        use TlsSignatureScheme as T;
1133        assert_eq!(
1134            C::ALL.iter().copied().map(C::iana).collect::<Vec<_>>(),
1135            [
1136                0x1302, 0x1301, 0x1303, 0xC02C, 0xC02B, 0xCCA9, 0xC030, 0xC02F, 0xCCA8
1137            ]
1138        );
1139        assert_eq!(
1140            K::ALL.iter().copied().map(K::iana).collect::<Vec<_>>(),
1141            [0x0202, 0x11ED, 0x11EC, 0x11EB, 0x0018, 0x0017, 0x001D]
1142        );
1143        assert_eq!(
1144            T::ALL.iter().copied().map(T::iana).collect::<Vec<_>>(),
1145            [
1146                0x0403, 0x0503, 0x0603, 0x0807, 0x0804, 0x0805, 0x0806, 0x0401, 0x0501, 0x0601,
1147                0x0906
1148            ]
1149        );
1150        assert_eq!(
1151            TlsVersion::ALL
1152                .iter()
1153                .copied()
1154                .map(TlsVersion::iana)
1155                .collect::<Vec<_>>(),
1156            [0x0303, 0x0304]
1157        );
1158    }
1159
1160    #[test]
1161    fn signature_oids_are_the_registry_values() {
1162        use SignatureAlgorithm as S;
1163        assert_eq!(
1164            S::ALL
1165                .iter()
1166                .copied()
1167                .map(S::signature_oid)
1168                .collect::<Vec<_>>(),
1169            [
1170                "2.16.840.1.101.3.4.3.19",
1171                "1.2.840.10045.4.3.2",
1172                "1.2.840.10045.4.3.3",
1173                "1.2.840.10045.4.3.3",
1174                "1.2.840.10045.4.3.4",
1175                "1.3.101.112",
1176                "1.2.840.113549.1.1.12",
1177                "1.2.840.113549.1.1.12",
1178                "1.2.840.113549.1.1.12",
1179                "1.2.840.113549.1.1.10",
1180                "1.2.840.113549.1.1.10",
1181                "1.2.840.113549.1.1.10",
1182            ]
1183        );
1184    }
1185
1186    #[test]
1187    fn hash_lengths() {
1188        assert_eq!(
1189            HashAlgorithm::ALL
1190                .iter()
1191                .copied()
1192                .map(HashAlgorithm::output_len)
1193                .collect::<Vec<_>>(),
1194            [32, 48, 64, 32, 48, 64]
1195        );
1196    }
1197
1198    #[test]
1199    fn hash_names_are_stable_and_round_trip() {
1200        assert_eq!(
1201            HashAlgorithm::ALL
1202                .iter()
1203                .copied()
1204                .map(HashAlgorithm::as_str)
1205                .collect::<Vec<_>>(),
1206            [
1207                "sha256", "sha384", "sha512", "sha3-256", "sha3-384", "sha3-512"
1208            ]
1209        );
1210        for &h in HashAlgorithm::ALL {
1211            assert_eq!(h.as_str().parse::<HashAlgorithm>(), Ok(h));
1212            assert_eq!(h.to_string(), h.as_str());
1213        }
1214        for bad in [
1215            "", "SHA256", "sha-256", "sha256 ", "sha3_256", "sha3256", "sha224", "sha3-224",
1216            "shake256",
1217        ] {
1218            assert_eq!(
1219                bad.parse::<HashAlgorithm>(),
1220                Err(ParseAlgorithmError(bad.to_string())),
1221                "{bad:?}"
1222            );
1223        }
1224    }
1225
1226    #[test]
1227    fn algorithm_all_is_every_variant_once() {
1228        let all = Algorithm::all();
1229        let expected = SignatureAlgorithm::ALL.len()
1230            + TlsSignatureScheme::ALL.len()
1231            + KxGroup::ALL.len()
1232            + CipherSuite::ALL.len()
1233            + HashAlgorithm::ALL.len()
1234            + TlsVersion::ALL.len()
1235            + MacAlgorithm::ALL.len()
1236            + KdfAlgorithm::ALL.len()
1237            + KeyAgreementAlgorithm::ALL.len()
1238            + AeadAlgorithm::ALL.len();
1239        assert_eq!(all.len(), expected);
1240        assert_eq!(expected, 12 + 11 + 7 + 9 + 6 + 2 + 3 + 6 + 4 + 3);
1241        for (i, a) in all.iter().enumerate() {
1242            assert!(!all[i + 1..].contains(a), "{a:?} twice");
1243        }
1244        assert_eq!(
1245            all[all.len() - 16..all.len() - 13],
1246            MacAlgorithm::ALL
1247                .iter()
1248                .copied()
1249                .map(Algorithm::Mac)
1250                .collect::<Vec<_>>()
1251        );
1252        assert_eq!(
1253            all[all.len() - 13..all.len() - 7],
1254            KdfAlgorithm::ALL
1255                .iter()
1256                .copied()
1257                .map(Algorithm::Kdf)
1258                .collect::<Vec<_>>()
1259        );
1260        assert_eq!(
1261            all[all.len() - 7..all.len() - 3],
1262            KeyAgreementAlgorithm::ALL
1263                .iter()
1264                .copied()
1265                .map(Algorithm::KeyAgreement)
1266                .collect::<Vec<_>>()
1267        );
1268        assert_eq!(
1269            all[all.len() - 3..],
1270            AeadAlgorithm::ALL
1271                .iter()
1272                .copied()
1273                .map(Algorithm::Aead)
1274                .collect::<Vec<_>>()
1275        );
1276    }
1277
1278    #[test]
1279    fn aead_algorithm_all_lists_every_variant_in_ordinal_order() {
1280        assert_eq!(
1281            AeadAlgorithm::ALL,
1282            [
1283                AeadAlgorithm::Aes128Gcm,
1284                AeadAlgorithm::Aes256Gcm,
1285                AeadAlgorithm::Chacha20Poly1305,
1286            ]
1287        );
1288        assert_eq!(
1289            AeadAlgorithm::ALL
1290                .iter()
1291                .copied()
1292                .map(AeadAlgorithm::ordinal)
1293                .collect::<Vec<_>>(),
1294            std::array::from_fn::<usize, 3, _>(|i| i)
1295        );
1296    }
1297
1298    #[test]
1299    fn aead_names_are_stable_and_round_trip() {
1300        assert_eq!(
1301            AeadAlgorithm::ALL
1302                .iter()
1303                .copied()
1304                .map(AeadAlgorithm::as_str)
1305                .collect::<Vec<_>>(),
1306            ["aes-128-gcm", "aes-256-gcm", "chacha20-poly1305"]
1307        );
1308        for &a in AeadAlgorithm::ALL {
1309            assert_eq!(a.as_str().parse::<AeadAlgorithm>(), Ok(a));
1310            assert_eq!(a.to_string(), a.as_str());
1311        }
1312        for bad in [
1313            "",
1314            "aes256gcm",
1315            "AES-256-GCM",
1316            "aes-256-gcm ",
1317            "aes-192-gcm",
1318            "chacha20",
1319        ] {
1320            assert_eq!(
1321                bad.parse::<AeadAlgorithm>(),
1322                Err(ParseAlgorithmError(bad.to_string())),
1323                "{bad:?}"
1324            );
1325        }
1326    }
1327
1328    #[test]
1329    fn each_aead_knows_its_key_and_plaintext_limits() {
1330        assert_eq!(
1331            AeadAlgorithm::ALL
1332                .iter()
1333                .map(|a| (a.key_len(), a.max_plaintext_len()))
1334                .collect::<Vec<_>>(),
1335            [
1336                (16, 68_719_476_704),
1337                (32, 68_719_476_704),
1338                (32, 274_877_906_879)
1339            ]
1340        );
1341        assert_eq!(
1342            AeadAlgorithm::Aes256Gcm.max_plaintext_len(),
1343            ((1 << 39) - 256) / 8
1344        );
1345        assert_eq!(
1346            AeadAlgorithm::Chacha20Poly1305.max_plaintext_len(),
1347            64 * ((1 << 32) - 1) - 1
1348        );
1349    }
1350
1351    #[test]
1352    fn mac_algorithm_all_lists_every_variant_in_ordinal_order() {
1353        assert_eq!(
1354            MacAlgorithm::ALL,
1355            [
1356                MacAlgorithm::HmacSha256,
1357                MacAlgorithm::HmacSha384,
1358                MacAlgorithm::HmacSha512
1359            ]
1360        );
1361        assert_eq!(
1362            MacAlgorithm::ALL
1363                .iter()
1364                .copied()
1365                .map(MacAlgorithm::ordinal)
1366                .collect::<Vec<_>>(),
1367            [0, 1, 2]
1368        );
1369    }
1370
1371    #[test]
1372    fn each_mac_names_its_hash_and_a_full_length_tag() {
1373        assert_eq!(
1374            MacAlgorithm::ALL
1375                .iter()
1376                .copied()
1377                .map(MacAlgorithm::hash)
1378                .collect::<Vec<_>>(),
1379            [
1380                HashAlgorithm::Sha256,
1381                HashAlgorithm::Sha384,
1382                HashAlgorithm::Sha512
1383            ]
1384        );
1385        assert_eq!(
1386            MacAlgorithm::ALL
1387                .iter()
1388                .copied()
1389                .map(MacAlgorithm::tag_len)
1390                .collect::<Vec<_>>(),
1391            [32, 48, 64]
1392        );
1393    }
1394
1395    #[test]
1396    fn kdf_algorithm_all_lists_every_variant_in_ordinal_order() {
1397        assert_eq!(
1398            KdfAlgorithm::ALL,
1399            [
1400                KdfAlgorithm::HkdfSha256,
1401                KdfAlgorithm::HkdfSha384,
1402                KdfAlgorithm::HkdfSha512,
1403                KdfAlgorithm::OneStepSha256,
1404                KdfAlgorithm::OneStepSha384,
1405                KdfAlgorithm::OneStepSha512,
1406            ]
1407        );
1408        assert_eq!(
1409            KdfAlgorithm::ALL
1410                .iter()
1411                .copied()
1412                .map(KdfAlgorithm::ordinal)
1413                .collect::<Vec<_>>(),
1414            std::array::from_fn::<usize, 6, _>(|i| i)
1415        );
1416    }
1417
1418    #[test]
1419    fn each_kdf_names_its_hash_and_its_output_limit() {
1420        use HashAlgorithm::{Sha256, Sha384, Sha512};
1421        assert_eq!(
1422            KdfAlgorithm::ALL
1423                .iter()
1424                .copied()
1425                .map(KdfAlgorithm::hash)
1426                .collect::<Vec<_>>(),
1427            [Sha256, Sha384, Sha512, Sha256, Sha384, Sha512]
1428        );
1429        assert_eq!(
1430            KdfAlgorithm::ALL
1431                .iter()
1432                .copied()
1433                .map(KdfAlgorithm::max_output_len)
1434                .collect::<Vec<_>>(),
1435            [
1436                8160,
1437                12240,
1438                16320,
1439                1_073_741_824,
1440                1_073_741_824,
1441                1_073_741_824
1442            ]
1443        );
1444    }
1445
1446    #[test]
1447    fn key_agreement_algorithm_all_lists_every_variant_in_ordinal_order() {
1448        assert_eq!(
1449            KeyAgreementAlgorithm::ALL,
1450            [
1451                KeyAgreementAlgorithm::EcdhP256,
1452                KeyAgreementAlgorithm::EcdhP384,
1453                KeyAgreementAlgorithm::EcdhP521,
1454                KeyAgreementAlgorithm::X25519,
1455            ]
1456        );
1457        assert_eq!(
1458            KeyAgreementAlgorithm::ALL
1459                .iter()
1460                .copied()
1461                .map(KeyAgreementAlgorithm::ordinal)
1462                .collect::<Vec<_>>(),
1463            std::array::from_fn::<usize, 4, _>(|i| i)
1464        );
1465    }
1466
1467    #[test]
1468    fn key_agreement_names_are_stable_and_round_trip() {
1469        assert_eq!(
1470            KeyAgreementAlgorithm::ALL
1471                .iter()
1472                .copied()
1473                .map(KeyAgreementAlgorithm::as_str)
1474                .collect::<Vec<_>>(),
1475            ["ecdh-p256", "ecdh-p384", "ecdh-p521", "x25519"]
1476        );
1477        for &a in KeyAgreementAlgorithm::ALL {
1478            assert_eq!(a.as_str().parse::<KeyAgreementAlgorithm>(), Ok(a));
1479            assert_eq!(a.to_string(), a.as_str());
1480        }
1481        for bad in ["", "p384", "ECDH-P384", "ecdh-p384 ", "x448", "secp384r1"] {
1482            assert_eq!(
1483                bad.parse::<KeyAgreementAlgorithm>(),
1484                Err(ParseAlgorithmError(bad.to_string())),
1485                "{bad:?}"
1486            );
1487        }
1488    }
1489
1490    #[test]
1491    fn signature_algorithm_all_lists_every_variant_in_ordinal_order() {
1492        assert_eq!(
1493            SignatureAlgorithm::ALL[9..],
1494            [
1495                SignatureAlgorithm::Rsa2048Sha384Pss,
1496                SignatureAlgorithm::Rsa3072Sha384Pss,
1497                SignatureAlgorithm::Rsa4096Sha384Pss,
1498            ]
1499        );
1500        assert_eq!(
1501            SignatureAlgorithm::ALL
1502                .iter()
1503                .copied()
1504                .map(SignatureAlgorithm::ordinal)
1505                .collect::<Vec<_>>(),
1506            std::array::from_fn::<usize, 12, _>(|i| i)
1507        );
1508    }
1509
1510    #[test]
1511    fn tls_signature_scheme_all_lists_every_variant_in_ordinal_order() {
1512        assert_eq!(
1513            TlsSignatureScheme::ALL
1514                .iter()
1515                .copied()
1516                .map(TlsSignatureScheme::ordinal)
1517                .collect::<Vec<_>>(),
1518            std::array::from_fn::<usize, 11, _>(|i| i)
1519        );
1520    }
1521
1522    #[test]
1523    fn cipher_suite_all_lists_every_variant_in_ordinal_order() {
1524        assert_eq!(
1525            CipherSuite::ALL
1526                .iter()
1527                .copied()
1528                .map(CipherSuite::ordinal)
1529                .collect::<Vec<_>>(),
1530            std::array::from_fn::<usize, 9, _>(|i| i)
1531        );
1532    }
1533
1534    #[test]
1535    fn kx_group_all_lists_every_variant_in_ordinal_order() {
1536        assert_eq!(
1537            KxGroup::ALL
1538                .iter()
1539                .copied()
1540                .map(KxGroup::ordinal)
1541                .collect::<Vec<_>>(),
1542            std::array::from_fn::<usize, 7, _>(|i| i)
1543        );
1544    }
1545
1546    #[test]
1547    fn hash_algorithm_all_lists_every_variant_in_ordinal_order() {
1548        assert_eq!(
1549            HashAlgorithm::ALL,
1550            [
1551                HashAlgorithm::Sha256,
1552                HashAlgorithm::Sha384,
1553                HashAlgorithm::Sha512,
1554                HashAlgorithm::Sha3_256,
1555                HashAlgorithm::Sha3_384,
1556                HashAlgorithm::Sha3_512,
1557            ]
1558        );
1559        assert_eq!(
1560            HashAlgorithm::ALL
1561                .iter()
1562                .copied()
1563                .map(HashAlgorithm::ordinal)
1564                .collect::<Vec<_>>(),
1565            std::array::from_fn::<usize, 6, _>(|i| i)
1566        );
1567    }
1568
1569    #[test]
1570    fn tls_version_all_lists_every_variant_in_ordinal_order() {
1571        assert_eq!(
1572            TlsVersion::ALL
1573                .iter()
1574                .copied()
1575                .map(TlsVersion::ordinal)
1576                .collect::<Vec<_>>(),
1577            std::array::from_fn::<usize, 2, _>(|i| i)
1578        );
1579    }
1580}