Skip to main content

hpke_dispatch/
aead.rs

1use std::str::FromStr;
2
3use num_enum::TryFromPrimitive;
4
5use crate::IdLookupError;
6
7/// An authenticated encryption with additional data encryption function, as per [RFC9180ยง7.3][1].
8///
9/// [1]: https://www.rfc-editor.org/rfc/rfc9180.html#section-7.3
10#[non_exhaustive]
11#[repr(u16)]
12#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive)]
13#[cfg_attr(
14    feature = "serde",
15    derive(serde_crate::Serialize, serde_crate::Deserialize)
16)]
17#[cfg_attr(feature = "serde", serde(crate = "serde_crate"))]
18pub enum Aead {
19    /// AES-128-GCM [GCM](https://doi.org/10.6028/nist.sp.800-38d)
20    #[cfg(feature = "aes")]
21    AesGcm128 = 1,
22    /// AES-256-GCM [GCM](https://doi.org/10.6028/nist.sp.800-38d)
23    #[cfg(feature = "aes")]
24    AesGcm256 = 2,
25    /// ChaCha20Poly1305 [RFC8439](https://www.rfc-editor.org/info/rfc8439)
26    #[cfg(feature = "chacha")]
27    ChaCha20Poly1305 = 3,
28}
29
30impl FromStr for Aead {
31    type Err = IdLookupError;
32
33    fn from_str(s: &str) -> Result<Self, Self::Err> {
34        match &*s.to_lowercase().replace('-', "") {
35            #[cfg(feature = "aes")]
36            "aesgcm128" | "aes128gcm" => Ok(Self::AesGcm128),
37            #[cfg(feature = "aes")]
38            "aesgcm256" | "aes256gcm" => Ok(Self::AesGcm256),
39            #[cfg(feature = "chacha")]
40            "chacha20poly1305" => Ok(Self::ChaCha20Poly1305),
41            _ => Err(IdLookupError("aead not recognized")),
42        }
43    }
44}
45
46/// An iterable slice of [`Aead`] variants
47pub const AEAD_ALL: &[Aead] = &[
48    #[cfg(feature = "aes")]
49    Aead::AesGcm128,
50    #[cfg(feature = "aes")]
51    Aead::AesGcm256,
52    #[cfg(feature = "chacha")]
53    Aead::ChaCha20Poly1305,
54];