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 and TLS versions.
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)]
8pub enum SignatureAlgorithm {
9    /// ML-DSA-87 (FIPS 204).
10    MlDsa87,
11    /// ECDSA on P-256 with SHA-256.
12    EcdsaP256Sha256,
13    /// ECDSA on P-384 with SHA-384.
14    EcdsaP384Sha384,
15    /// ECDSA on P-521 with SHA-384.
16    EcdsaP521Sha384,
17    /// ECDSA on P-521 with SHA-512.
18    EcdsaP521Sha512,
19    /// Ed25519 (FIPS 186-5 EdDSA).
20    Ed25519,
21    /// A 2048-bit RSA key; its CSR is signed RSASSA-PKCS1-v1_5 with SHA-384.
22    Rsa2048Sha384,
23    /// A 3072-bit RSA key; its CSR is signed RSASSA-PKCS1-v1_5 with SHA-384.
24    Rsa3072Sha384,
25    /// A 4096-bit RSA key; its CSR is signed RSASSA-PKCS1-v1_5 with SHA-384.
26    Rsa4096Sha384,
27}
28
29impl SignatureAlgorithm {
30    /// Every signature key algorithm.
31    pub const ALL: [SignatureAlgorithm; 9] = [
32        SignatureAlgorithm::MlDsa87,
33        SignatureAlgorithm::EcdsaP256Sha256,
34        SignatureAlgorithm::EcdsaP384Sha384,
35        SignatureAlgorithm::EcdsaP521Sha384,
36        SignatureAlgorithm::EcdsaP521Sha512,
37        SignatureAlgorithm::Ed25519,
38        SignatureAlgorithm::Rsa2048Sha384,
39        SignatureAlgorithm::Rsa3072Sha384,
40        SignatureAlgorithm::Rsa4096Sha384,
41    ];
42
43    /// The position of `self` in [`Self::ALL`].
44    #[cfg(test)]
45    pub(crate) const fn ordinal(self) -> usize {
46        match self {
47            SignatureAlgorithm::MlDsa87 => 0,
48            SignatureAlgorithm::EcdsaP256Sha256 => 1,
49            SignatureAlgorithm::EcdsaP384Sha384 => 2,
50            SignatureAlgorithm::EcdsaP521Sha384 => 3,
51            SignatureAlgorithm::EcdsaP521Sha512 => 4,
52            SignatureAlgorithm::Ed25519 => 5,
53            SignatureAlgorithm::Rsa2048Sha384 => 6,
54            SignatureAlgorithm::Rsa3072Sha384 => 7,
55            SignatureAlgorithm::Rsa4096Sha384 => 8,
56        }
57    }
58
59    /// The algorithm's stable configuration name.
60    pub const fn as_str(self) -> &'static str {
61        match self {
62            SignatureAlgorithm::MlDsa87 => "ml-dsa-87",
63            SignatureAlgorithm::EcdsaP256Sha256 => "ecdsa-p256-sha256",
64            SignatureAlgorithm::EcdsaP384Sha384 => "ecdsa-p384-sha384",
65            SignatureAlgorithm::EcdsaP521Sha384 => "ecdsa-p521-sha384",
66            SignatureAlgorithm::EcdsaP521Sha512 => "ecdsa-p521-sha512",
67            SignatureAlgorithm::Ed25519 => "ed25519",
68            SignatureAlgorithm::Rsa2048Sha384 => "rsa2048-sha384",
69            SignatureAlgorithm::Rsa3072Sha384 => "rsa3072-sha384",
70            SignatureAlgorithm::Rsa4096Sha384 => "rsa4096-sha384",
71        }
72    }
73
74    /// The X.509 signature-algorithm OID a CSR or certificate signed by this key carries
75    /// (RFC 5758, RFC 8410, RFC 4055, and draft-ietf-lamps-dilithium-certificates for ML-DSA).
76    pub const fn signature_oid(self) -> &'static str {
77        match self {
78            SignatureAlgorithm::MlDsa87 => "2.16.840.1.101.3.4.3.19",
79            SignatureAlgorithm::EcdsaP256Sha256 => "1.2.840.10045.4.3.2",
80            SignatureAlgorithm::EcdsaP384Sha384 | SignatureAlgorithm::EcdsaP521Sha384 => {
81                "1.2.840.10045.4.3.3"
82            }
83            SignatureAlgorithm::EcdsaP521Sha512 => "1.2.840.10045.4.3.4",
84            SignatureAlgorithm::Ed25519 => "1.3.101.112",
85            SignatureAlgorithm::Rsa2048Sha384
86            | SignatureAlgorithm::Rsa3072Sha384
87            | SignatureAlgorithm::Rsa4096Sha384 => "1.2.840.113549.1.1.12",
88        }
89    }
90
91    /// The TLS signature scheme this crate pairs with a key of this algorithm: the scheme the key
92    /// signs a handshake with when the peer offers this scheme alone.
93    ///
94    /// An ECDSA, Ed25519 or ML-DSA key has no other scheme. An RSA key's scheme comes from the
95    /// peer's offer, whatever the key's CSR was signed with: rustls signs with the first of RSA-PSS
96    /// with SHA-512, SHA-384 and SHA-256, then PKCS#1 v1.5 with SHA-512, SHA-384 and SHA-256, that
97    /// the peer offers (`RSA_SCHEMES` in `crypto-profile/src/provider/sign.rs`, the order rustls
98    /// 0.23.46 uses), and TLS 1.3 admits only the RSA-PSS ones (`src/enums.rs:554-579`). So an RSA
99    /// key signs with RSA-PSS with SHA-384 only when the peer offers it and does not offer RSA-PSS
100    /// with SHA-512.
101    pub const fn tls_scheme(self) -> TlsSignatureScheme {
102        match self {
103            SignatureAlgorithm::MlDsa87 => TlsSignatureScheme::MlDsa87,
104            SignatureAlgorithm::EcdsaP256Sha256 => TlsSignatureScheme::EcdsaNistp256Sha256,
105            SignatureAlgorithm::EcdsaP384Sha384 => TlsSignatureScheme::EcdsaNistp384Sha384,
106            SignatureAlgorithm::EcdsaP521Sha384 | SignatureAlgorithm::EcdsaP521Sha512 => {
107                TlsSignatureScheme::EcdsaNistp521Sha512
108            }
109            SignatureAlgorithm::Ed25519 => TlsSignatureScheme::Ed25519,
110            SignatureAlgorithm::Rsa2048Sha384
111            | SignatureAlgorithm::Rsa3072Sha384
112            | SignatureAlgorithm::Rsa4096Sha384 => TlsSignatureScheme::RsaPssSha384,
113        }
114    }
115}
116
117/// A name that is not one of the crate's algorithms.
118#[derive(Debug, Clone, PartialEq, Eq)]
119pub struct ParseAlgorithmError(pub String);
120
121impl fmt::Display for ParseAlgorithmError {
122    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123        write!(f, "unknown signature algorithm {:?}", self.0)
124    }
125}
126
127impl std::error::Error for ParseAlgorithmError {}
128
129impl FromStr for SignatureAlgorithm {
130    type Err = ParseAlgorithmError;
131    fn from_str(s: &str) -> Result<Self, Self::Err> {
132        SignatureAlgorithm::ALL
133            .into_iter()
134            .find(|a| a.as_str() == s)
135            .ok_or_else(|| ParseAlgorithmError(s.to_string()))
136    }
137}
138
139impl fmt::Display for SignatureAlgorithm {
140    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141        f.write_str(self.as_str())
142    }
143}
144
145/// A TLS handshake signature scheme.
146#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
147pub enum TlsSignatureScheme {
148    /// `ecdsa_secp256r1_sha256`.
149    EcdsaNistp256Sha256,
150    /// `ecdsa_secp384r1_sha384`.
151    EcdsaNistp384Sha384,
152    /// `ecdsa_secp521r1_sha512`.
153    EcdsaNistp521Sha512,
154    /// `ed25519`.
155    Ed25519,
156    /// `rsa_pss_rsae_sha256`.
157    RsaPssSha256,
158    /// `rsa_pss_rsae_sha384`.
159    RsaPssSha384,
160    /// `rsa_pss_rsae_sha512`.
161    RsaPssSha512,
162    /// `rsa_pkcs1_sha256`.
163    RsaPkcs1Sha256,
164    /// `rsa_pkcs1_sha384`.
165    RsaPkcs1Sha384,
166    /// `rsa_pkcs1_sha512`.
167    RsaPkcs1Sha512,
168    /// `mldsa87`.
169    MlDsa87,
170}
171
172impl TlsSignatureScheme {
173    /// Whether a handshake at `v` can sign with this scheme. RFC 8446 §4.2.3 excludes RSA
174    /// PKCS#1 v1.5 from TLS 1.3 handshake signatures; ML-DSA is defined for TLS 1.3 only.
175    pub const fn usable_in(self, v: TlsVersion) -> bool {
176        match self {
177            TlsSignatureScheme::RsaPkcs1Sha256
178            | TlsSignatureScheme::RsaPkcs1Sha384
179            | TlsSignatureScheme::RsaPkcs1Sha512 => matches!(v, TlsVersion::Tls12),
180            TlsSignatureScheme::MlDsa87 => matches!(v, TlsVersion::Tls13),
181            TlsSignatureScheme::EcdsaNistp256Sha256
182            | TlsSignatureScheme::EcdsaNistp384Sha384
183            | TlsSignatureScheme::EcdsaNistp521Sha512
184            | TlsSignatureScheme::Ed25519
185            | TlsSignatureScheme::RsaPssSha256
186            | TlsSignatureScheme::RsaPssSha384
187            | TlsSignatureScheme::RsaPssSha512 => true,
188        }
189    }
190
191    /// The IANA TLS SignatureScheme codepoint.
192    pub const fn iana(self) -> u16 {
193        match self {
194            TlsSignatureScheme::EcdsaNistp256Sha256 => 0x0403,
195            TlsSignatureScheme::EcdsaNistp384Sha384 => 0x0503,
196            TlsSignatureScheme::EcdsaNistp521Sha512 => 0x0603,
197            TlsSignatureScheme::Ed25519 => 0x0807,
198            TlsSignatureScheme::RsaPssSha256 => 0x0804,
199            TlsSignatureScheme::RsaPssSha384 => 0x0805,
200            TlsSignatureScheme::RsaPssSha512 => 0x0806,
201            TlsSignatureScheme::RsaPkcs1Sha256 => 0x0401,
202            TlsSignatureScheme::RsaPkcs1Sha384 => 0x0501,
203            TlsSignatureScheme::RsaPkcs1Sha512 => 0x0601,
204            TlsSignatureScheme::MlDsa87 => 0x0906,
205        }
206    }
207
208    /// The scheme's rank in the canonical order every profile lists its schemes in, and in which a
209    /// backend carries a policy's schemes: 0 first, one rank per scheme.
210    pub const fn preference(self) -> u8 {
211        match self {
212            TlsSignatureScheme::MlDsa87 => 0,
213            TlsSignatureScheme::EcdsaNistp384Sha384 => 1,
214            TlsSignatureScheme::EcdsaNistp256Sha256 => 2,
215            TlsSignatureScheme::EcdsaNistp521Sha512 => 3,
216            TlsSignatureScheme::Ed25519 => 4,
217            TlsSignatureScheme::RsaPssSha384 => 5,
218            TlsSignatureScheme::RsaPssSha512 => 6,
219            TlsSignatureScheme::RsaPssSha256 => 7,
220            TlsSignatureScheme::RsaPkcs1Sha384 => 8,
221            TlsSignatureScheme::RsaPkcs1Sha512 => 9,
222            TlsSignatureScheme::RsaPkcs1Sha256 => 10,
223        }
224    }
225
226    /// Every TLS signature scheme.
227    pub const ALL: [TlsSignatureScheme; 11] = [
228        TlsSignatureScheme::EcdsaNistp256Sha256,
229        TlsSignatureScheme::EcdsaNistp384Sha384,
230        TlsSignatureScheme::EcdsaNistp521Sha512,
231        TlsSignatureScheme::Ed25519,
232        TlsSignatureScheme::RsaPssSha256,
233        TlsSignatureScheme::RsaPssSha384,
234        TlsSignatureScheme::RsaPssSha512,
235        TlsSignatureScheme::RsaPkcs1Sha256,
236        TlsSignatureScheme::RsaPkcs1Sha384,
237        TlsSignatureScheme::RsaPkcs1Sha512,
238        TlsSignatureScheme::MlDsa87,
239    ];
240
241    /// The position of `self` in [`Self::ALL`].
242    #[cfg(test)]
243    pub(crate) const fn ordinal(self) -> usize {
244        match self {
245            TlsSignatureScheme::EcdsaNistp256Sha256 => 0,
246            TlsSignatureScheme::EcdsaNistp384Sha384 => 1,
247            TlsSignatureScheme::EcdsaNistp521Sha512 => 2,
248            TlsSignatureScheme::Ed25519 => 3,
249            TlsSignatureScheme::RsaPssSha256 => 4,
250            TlsSignatureScheme::RsaPssSha384 => 5,
251            TlsSignatureScheme::RsaPssSha512 => 6,
252            TlsSignatureScheme::RsaPkcs1Sha256 => 7,
253            TlsSignatureScheme::RsaPkcs1Sha384 => 8,
254            TlsSignatureScheme::RsaPkcs1Sha512 => 9,
255            TlsSignatureScheme::MlDsa87 => 10,
256        }
257    }
258}
259
260/// A TLS cipher suite.
261#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
262pub enum CipherSuite {
263    /// `TLS_AES_256_GCM_SHA384`.
264    Tls13Aes256GcmSha384,
265    /// `TLS_AES_128_GCM_SHA256`.
266    Tls13Aes128GcmSha256,
267    /// `TLS_CHACHA20_POLY1305_SHA256`.
268    Tls13Chacha20Poly1305Sha256,
269    /// `TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384`.
270    Tls12EcdheEcdsaAes256GcmSha384,
271    /// `TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256`.
272    Tls12EcdheEcdsaAes128GcmSha256,
273    /// `TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256`.
274    Tls12EcdheEcdsaChacha20Poly1305Sha256,
275    /// `TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384`.
276    Tls12EcdheRsaAes256GcmSha384,
277    /// `TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256`.
278    Tls12EcdheRsaAes128GcmSha256,
279    /// `TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256`.
280    Tls12EcdheRsaChacha20Poly1305Sha256,
281}
282
283impl CipherSuite {
284    /// Whether a handshake under this suite can sign with `t`. A TLS 1.2 suite fixes the
285    /// authentication algorithm (ECDSA or EdDSA for `EcdheEcdsa`, RSA for `EcdheRsa`); a TLS 1.3
286    /// suite does not.
287    pub const fn signs_with(self, t: TlsSignatureScheme) -> bool {
288        use TlsSignatureScheme as T;
289        match self {
290            CipherSuite::Tls13Aes256GcmSha384
291            | CipherSuite::Tls13Aes128GcmSha256
292            | CipherSuite::Tls13Chacha20Poly1305Sha256 => t.usable_in(TlsVersion::Tls13),
293            CipherSuite::Tls12EcdheEcdsaAes256GcmSha384
294            | CipherSuite::Tls12EcdheEcdsaAes128GcmSha256
295            | CipherSuite::Tls12EcdheEcdsaChacha20Poly1305Sha256 => matches!(
296                t,
297                T::EcdsaNistp256Sha256
298                    | T::EcdsaNistp384Sha384
299                    | T::EcdsaNistp521Sha512
300                    | T::Ed25519
301            ),
302            CipherSuite::Tls12EcdheRsaAes256GcmSha384
303            | CipherSuite::Tls12EcdheRsaAes128GcmSha256
304            | CipherSuite::Tls12EcdheRsaChacha20Poly1305Sha256 => matches!(
305                t,
306                T::RsaPssSha256
307                    | T::RsaPssSha384
308                    | T::RsaPssSha512
309                    | T::RsaPkcs1Sha256
310                    | T::RsaPkcs1Sha384
311                    | T::RsaPkcs1Sha512
312            ),
313        }
314    }
315
316    /// Every cipher suite.
317    pub const ALL: [CipherSuite; 9] = [
318        CipherSuite::Tls13Aes256GcmSha384,
319        CipherSuite::Tls13Aes128GcmSha256,
320        CipherSuite::Tls13Chacha20Poly1305Sha256,
321        CipherSuite::Tls12EcdheEcdsaAes256GcmSha384,
322        CipherSuite::Tls12EcdheEcdsaAes128GcmSha256,
323        CipherSuite::Tls12EcdheEcdsaChacha20Poly1305Sha256,
324        CipherSuite::Tls12EcdheRsaAes256GcmSha384,
325        CipherSuite::Tls12EcdheRsaAes128GcmSha256,
326        CipherSuite::Tls12EcdheRsaChacha20Poly1305Sha256,
327    ];
328
329    /// The position of `self` in [`Self::ALL`].
330    #[cfg(test)]
331    pub(crate) const fn ordinal(self) -> usize {
332        match self {
333            CipherSuite::Tls13Aes256GcmSha384 => 0,
334            CipherSuite::Tls13Aes128GcmSha256 => 1,
335            CipherSuite::Tls13Chacha20Poly1305Sha256 => 2,
336            CipherSuite::Tls12EcdheEcdsaAes256GcmSha384 => 3,
337            CipherSuite::Tls12EcdheEcdsaAes128GcmSha256 => 4,
338            CipherSuite::Tls12EcdheEcdsaChacha20Poly1305Sha256 => 5,
339            CipherSuite::Tls12EcdheRsaAes256GcmSha384 => 6,
340            CipherSuite::Tls12EcdheRsaAes128GcmSha256 => 7,
341            CipherSuite::Tls12EcdheRsaChacha20Poly1305Sha256 => 8,
342        }
343    }
344
345    /// The IANA TLS Cipher Suite codepoint.
346    pub const fn iana(self) -> u16 {
347        match self {
348            CipherSuite::Tls13Aes256GcmSha384 => 0x1302,
349            CipherSuite::Tls13Aes128GcmSha256 => 0x1301,
350            CipherSuite::Tls13Chacha20Poly1305Sha256 => 0x1303,
351            CipherSuite::Tls12EcdheEcdsaAes256GcmSha384 => 0xC02C,
352            CipherSuite::Tls12EcdheEcdsaAes128GcmSha256 => 0xC02B,
353            CipherSuite::Tls12EcdheEcdsaChacha20Poly1305Sha256 => 0xCCA9,
354            CipherSuite::Tls12EcdheRsaAes256GcmSha384 => 0xC030,
355            CipherSuite::Tls12EcdheRsaAes128GcmSha256 => 0xC02F,
356            CipherSuite::Tls12EcdheRsaChacha20Poly1305Sha256 => 0xCCA8,
357        }
358    }
359
360    /// The TLS version the suite belongs to.
361    pub const fn version(self) -> TlsVersion {
362        match self {
363            CipherSuite::Tls13Aes256GcmSha384
364            | CipherSuite::Tls13Aes128GcmSha256
365            | CipherSuite::Tls13Chacha20Poly1305Sha256 => TlsVersion::Tls13,
366            CipherSuite::Tls12EcdheEcdsaAes256GcmSha384
367            | CipherSuite::Tls12EcdheEcdsaAes128GcmSha256
368            | CipherSuite::Tls12EcdheEcdsaChacha20Poly1305Sha256
369            | CipherSuite::Tls12EcdheRsaAes256GcmSha384
370            | CipherSuite::Tls12EcdheRsaAes128GcmSha256
371            | CipherSuite::Tls12EcdheRsaChacha20Poly1305Sha256 => TlsVersion::Tls12,
372        }
373    }
374}
375
376/// A TLS key-exchange group.
377#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
378pub enum KxGroup {
379    /// ML-KEM-1024 (FIPS 203).
380    MlKem1024,
381    /// The P-384 + ML-KEM-1024 hybrid (RFC 10024 §4.1-4.3; codepoint §7.3).
382    Secp384r1MlKem1024,
383    /// The X25519 + ML-KEM-768 hybrid.
384    X25519MlKem768,
385    /// The P-256 + ML-KEM-768 hybrid.
386    Secp256r1MlKem768,
387    /// ECDH on P-384.
388    Secp384r1,
389    /// ECDH on P-256.
390    Secp256r1,
391    /// X25519.
392    X25519,
393}
394
395impl KxGroup {
396    /// Whether a handshake at `v` can use this group. TLS 1.2 has no ML-KEM or hybrid key
397    /// exchange.
398    pub const fn usable_in(self, v: TlsVersion) -> bool {
399        match v {
400            TlsVersion::Tls13 => true,
401            TlsVersion::Tls12 => match self {
402                KxGroup::Secp384r1 | KxGroup::Secp256r1 | KxGroup::X25519 => true,
403                KxGroup::MlKem1024
404                | KxGroup::Secp384r1MlKem1024
405                | KxGroup::X25519MlKem768
406                | KxGroup::Secp256r1MlKem768 => false,
407            },
408        }
409    }
410
411    /// Whether the group's key exchange includes ML-KEM: pure ML-KEM or a hybrid.
412    pub const fn is_post_quantum(self) -> bool {
413        match self {
414            KxGroup::MlKem1024
415            | KxGroup::Secp384r1MlKem1024
416            | KxGroup::X25519MlKem768
417            | KxGroup::Secp256r1MlKem768 => true,
418            KxGroup::Secp384r1 | KxGroup::Secp256r1 | KxGroup::X25519 => false,
419        }
420    }
421
422    /// The IANA TLS Supported Groups codepoint.
423    pub const fn iana(self) -> u16 {
424        match self {
425            KxGroup::MlKem1024 => 0x0202,
426            KxGroup::Secp384r1MlKem1024 => 0x11ED,
427            KxGroup::X25519MlKem768 => 0x11EC,
428            KxGroup::Secp256r1MlKem768 => 0x11EB,
429            KxGroup::Secp384r1 => 0x0018,
430            KxGroup::Secp256r1 => 0x0017,
431            KxGroup::X25519 => 0x001D,
432        }
433    }
434
435    /// Every key-exchange group.
436    pub const ALL: [KxGroup; 7] = [
437        KxGroup::MlKem1024,
438        KxGroup::Secp384r1MlKem1024,
439        KxGroup::X25519MlKem768,
440        KxGroup::Secp256r1MlKem768,
441        KxGroup::Secp384r1,
442        KxGroup::Secp256r1,
443        KxGroup::X25519,
444    ];
445
446    /// The position of `self` in [`Self::ALL`].
447    #[cfg(test)]
448    pub(crate) const fn ordinal(self) -> usize {
449        match self {
450            KxGroup::MlKem1024 => 0,
451            KxGroup::Secp384r1MlKem1024 => 1,
452            KxGroup::X25519MlKem768 => 2,
453            KxGroup::Secp256r1MlKem768 => 3,
454            KxGroup::Secp384r1 => 4,
455            KxGroup::Secp256r1 => 5,
456            KxGroup::X25519 => 6,
457        }
458    }
459}
460
461/// A hash function.
462#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
463pub enum HashAlgorithm {
464    /// SHA-256.
465    Sha256,
466    /// SHA-384.
467    Sha384,
468    /// SHA-512.
469    Sha512,
470}
471
472impl HashAlgorithm {
473    /// Every hash function.
474    pub const ALL: [HashAlgorithm; 3] = [
475        HashAlgorithm::Sha256,
476        HashAlgorithm::Sha384,
477        HashAlgorithm::Sha512,
478    ];
479
480    /// The position of `self` in [`Self::ALL`].
481    #[cfg(test)]
482    pub(crate) const fn ordinal(self) -> usize {
483        match self {
484            HashAlgorithm::Sha256 => 0,
485            HashAlgorithm::Sha384 => 1,
486            HashAlgorithm::Sha512 => 2,
487        }
488    }
489
490    /// The digest length in bytes.
491    pub const fn output_len(self) -> usize {
492        match self {
493            HashAlgorithm::Sha256 => 32,
494            HashAlgorithm::Sha384 => 48,
495            HashAlgorithm::Sha512 => 64,
496        }
497    }
498}
499
500/// A TLS protocol version.
501#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
502pub enum TlsVersion {
503    /// TLS 1.2.
504    Tls12,
505    /// TLS 1.3.
506    Tls13,
507}
508
509impl TlsVersion {
510    /// The TLS ProtocolVersion codepoint.
511    pub const fn iana(self) -> u16 {
512        match self {
513            TlsVersion::Tls12 => 0x0303,
514            TlsVersion::Tls13 => 0x0304,
515        }
516    }
517
518    /// Every TLS version.
519    pub const ALL: [TlsVersion; 2] = [TlsVersion::Tls12, TlsVersion::Tls13];
520
521    /// The position of `self` in [`Self::ALL`].
522    #[cfg(test)]
523    pub(crate) const fn ordinal(self) -> usize {
524        match self {
525            TlsVersion::Tls12 => 0,
526            TlsVersion::Tls13 => 1,
527        }
528    }
529}
530
531/// Any algorithm the capability table has a cell for.
532#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
533pub enum Algorithm {
534    /// A signature key algorithm.
535    Signature(SignatureAlgorithm),
536    /// A TLS signature scheme.
537    Scheme(TlsSignatureScheme),
538    /// A key-exchange group.
539    Kx(KxGroup),
540    /// A cipher suite.
541    Cipher(CipherSuite),
542    /// A hash function.
543    Hash(HashAlgorithm),
544    /// A TLS version.
545    Protocol(TlsVersion),
546}
547
548impl Algorithm {
549    /// Every algorithm, in family order.
550    pub fn all() -> Vec<Algorithm> {
551        let mut v = Vec::new();
552        v.extend(SignatureAlgorithm::ALL.map(Algorithm::Signature));
553        v.extend(TlsSignatureScheme::ALL.map(Algorithm::Scheme));
554        v.extend(KxGroup::ALL.map(Algorithm::Kx));
555        v.extend(CipherSuite::ALL.map(Algorithm::Cipher));
556        v.extend(HashAlgorithm::ALL.map(Algorithm::Hash));
557        v.extend(TlsVersion::ALL.map(Algorithm::Protocol));
558        v
559    }
560}
561
562#[cfg(test)]
563mod tests {
564    use super::*;
565
566    #[test]
567    fn usability_helpers_decide_per_version() {
568        use TlsSignatureScheme as T;
569        assert!(KxGroup::Secp384r1.usable_in(TlsVersion::Tls12));
570        assert!(!KxGroup::MlKem1024.usable_in(TlsVersion::Tls12));
571        assert!(KxGroup::MlKem1024.usable_in(TlsVersion::Tls13));
572        assert!(T::RsaPkcs1Sha256.usable_in(TlsVersion::Tls12));
573        assert!(!T::RsaPkcs1Sha256.usable_in(TlsVersion::Tls13));
574        assert!(T::MlDsa87.usable_in(TlsVersion::Tls13));
575        assert!(!T::MlDsa87.usable_in(TlsVersion::Tls12));
576        assert!(T::Ed25519.usable_in(TlsVersion::Tls12));
577        let c = CipherSuite::Tls12EcdheEcdsaAes256GcmSha384;
578        assert!(c.signs_with(T::EcdsaNistp384Sha384));
579        assert!(!c.signs_with(T::RsaPssSha384));
580        let r = CipherSuite::Tls12EcdheRsaAes256GcmSha384;
581        assert!(r.signs_with(T::RsaPkcs1Sha384));
582        assert!(!r.signs_with(T::Ed25519));
583        let t13 = CipherSuite::Tls13Aes256GcmSha384;
584        assert!(t13.signs_with(T::MlDsa87));
585        assert!(!t13.signs_with(T::RsaPkcs1Sha384));
586    }
587
588    #[test]
589    fn preference_is_the_canonical_order() {
590        let mut all = TlsSignatureScheme::ALL;
591        all.sort_by_key(|t| t.preference());
592        assert_eq!(
593            all.map(TlsSignatureScheme::iana),
594            [
595                0x0906, 0x0503, 0x0403, 0x0603, 0x0807, 0x0805, 0x0806, 0x0804, 0x0501, 0x0601,
596                0x0401
597            ]
598        );
599        let mut ranks = TlsSignatureScheme::ALL.map(TlsSignatureScheme::preference);
600        ranks.sort_unstable();
601        assert_eq!(ranks, std::array::from_fn::<u8, 11, _>(|i| i as u8));
602    }
603
604    #[test]
605    fn post_quantum_groups_are_the_ml_kem_ones() {
606        assert_eq!(
607            KxGroup::ALL.map(KxGroup::is_post_quantum),
608            [true, true, true, true, false, false, false]
609        );
610    }
611
612    #[test]
613    fn signature_names_are_stable_and_round_trip() {
614        assert_eq!(
615            SignatureAlgorithm::ALL.map(SignatureAlgorithm::as_str),
616            [
617                "ml-dsa-87",
618                "ecdsa-p256-sha256",
619                "ecdsa-p384-sha384",
620                "ecdsa-p521-sha384",
621                "ecdsa-p521-sha512",
622                "ed25519",
623                "rsa2048-sha384",
624                "rsa3072-sha384",
625                "rsa4096-sha384",
626            ]
627        );
628        for a in SignatureAlgorithm::ALL {
629            assert_eq!(a.as_str().parse::<SignatureAlgorithm>().unwrap(), a);
630            assert_eq!(a.to_string(), a.as_str());
631        }
632        assert_eq!(
633            ParseAlgorithmError("p384".to_string()).to_string(),
634            "unknown signature algorithm \"p384\""
635        );
636        for bad in [
637            "",
638            "p384",
639            "ML-DSA-87",
640            "ml-dsa-65",
641            "rsa-2048",
642            "ecdsa-p256-sha384",
643        ] {
644            assert_eq!(
645                bad.parse::<SignatureAlgorithm>(),
646                Err(ParseAlgorithmError(bad.to_string())),
647                "{bad}"
648            );
649        }
650    }
651
652    #[test]
653    fn every_key_algorithm_has_its_tls_scheme() {
654        use SignatureAlgorithm as S;
655        use TlsSignatureScheme as T;
656        let table = [
657            (S::MlDsa87, T::MlDsa87),
658            (S::EcdsaP256Sha256, T::EcdsaNistp256Sha256),
659            (S::EcdsaP384Sha384, T::EcdsaNistp384Sha384),
660            (S::EcdsaP521Sha384, T::EcdsaNistp521Sha512),
661            (S::EcdsaP521Sha512, T::EcdsaNistp521Sha512),
662            (S::Ed25519, T::Ed25519),
663            (S::Rsa2048Sha384, T::RsaPssSha384),
664            (S::Rsa3072Sha384, T::RsaPssSha384),
665            (S::Rsa4096Sha384, T::RsaPssSha384),
666        ];
667        assert_eq!(table.len(), SignatureAlgorithm::ALL.len());
668        for (s, t) in table {
669            assert_eq!(s.tls_scheme(), t, "{s}");
670        }
671    }
672
673    #[test]
674    fn cipher_suites_know_their_version() {
675        use TlsVersion::{Tls12, Tls13};
676        assert_eq!(
677            CipherSuite::ALL.map(CipherSuite::version),
678            [
679                Tls13, Tls13, Tls13, Tls12, Tls12, Tls12, Tls12, Tls12, Tls12
680            ]
681        );
682    }
683
684    #[test]
685    fn iana_codepoints_are_the_registry_values() {
686        use CipherSuite as C;
687        use KxGroup as K;
688        use TlsSignatureScheme as T;
689        assert_eq!(
690            C::ALL.map(C::iana),
691            [
692                0x1302, 0x1301, 0x1303, 0xC02C, 0xC02B, 0xCCA9, 0xC030, 0xC02F, 0xCCA8
693            ]
694        );
695        assert_eq!(
696            K::ALL.map(K::iana),
697            [0x0202, 0x11ED, 0x11EC, 0x11EB, 0x0018, 0x0017, 0x001D]
698        );
699        assert_eq!(
700            T::ALL.map(T::iana),
701            [
702                0x0403, 0x0503, 0x0603, 0x0807, 0x0804, 0x0805, 0x0806, 0x0401, 0x0501, 0x0601,
703                0x0906
704            ]
705        );
706        assert_eq!(TlsVersion::ALL.map(TlsVersion::iana), [0x0303, 0x0304]);
707    }
708
709    #[test]
710    fn signature_oids_are_the_registry_values() {
711        use SignatureAlgorithm as S;
712        assert_eq!(
713            S::ALL.map(S::signature_oid),
714            [
715                "2.16.840.1.101.3.4.3.19",
716                "1.2.840.10045.4.3.2",
717                "1.2.840.10045.4.3.3",
718                "1.2.840.10045.4.3.3",
719                "1.2.840.10045.4.3.4",
720                "1.3.101.112",
721                "1.2.840.113549.1.1.12",
722                "1.2.840.113549.1.1.12",
723                "1.2.840.113549.1.1.12",
724            ]
725        );
726    }
727
728    #[test]
729    fn hash_lengths() {
730        assert_eq!(
731            HashAlgorithm::ALL.map(HashAlgorithm::output_len),
732            [32, 48, 64]
733        );
734    }
735
736    #[test]
737    fn algorithm_all_is_every_variant_once() {
738        let all = Algorithm::all();
739        let expected = SignatureAlgorithm::ALL.len()
740            + TlsSignatureScheme::ALL.len()
741            + KxGroup::ALL.len()
742            + CipherSuite::ALL.len()
743            + HashAlgorithm::ALL.len()
744            + TlsVersion::ALL.len();
745        assert_eq!(all.len(), expected);
746        assert_eq!(expected, 9 + 11 + 7 + 9 + 3 + 2);
747        for (i, a) in all.iter().enumerate() {
748            assert!(!all[i + 1..].contains(a), "{a:?} twice");
749        }
750    }
751
752    #[test]
753    fn signature_algorithm_all_lists_every_variant_in_ordinal_order() {
754        assert_eq!(
755            SignatureAlgorithm::ALL.map(SignatureAlgorithm::ordinal),
756            std::array::from_fn::<usize, 9, _>(|i| i)
757        );
758    }
759
760    #[test]
761    fn tls_signature_scheme_all_lists_every_variant_in_ordinal_order() {
762        assert_eq!(
763            TlsSignatureScheme::ALL.map(TlsSignatureScheme::ordinal),
764            std::array::from_fn::<usize, 11, _>(|i| i)
765        );
766    }
767
768    #[test]
769    fn cipher_suite_all_lists_every_variant_in_ordinal_order() {
770        assert_eq!(
771            CipherSuite::ALL.map(CipherSuite::ordinal),
772            std::array::from_fn::<usize, 9, _>(|i| i)
773        );
774    }
775
776    #[test]
777    fn kx_group_all_lists_every_variant_in_ordinal_order() {
778        assert_eq!(
779            KxGroup::ALL.map(KxGroup::ordinal),
780            std::array::from_fn::<usize, 7, _>(|i| i)
781        );
782    }
783
784    #[test]
785    fn hash_algorithm_all_lists_every_variant_in_ordinal_order() {
786        assert_eq!(
787            HashAlgorithm::ALL.map(HashAlgorithm::ordinal),
788            std::array::from_fn::<usize, 3, _>(|i| i)
789        );
790    }
791
792    #[test]
793    fn tls_version_all_lists_every_variant_in_ordinal_order() {
794        assert_eq!(
795            TlsVersion::ALL.map(TlsVersion::ordinal),
796            std::array::from_fn::<usize, 2, _>(|i| i)
797        );
798    }
799}