channels_serdes/
aead.rs

1//! Middleware that encrypts data for transport.
2
3use core::fmt;
4
5use alloc::vec::Vec;
6
7use ring::aead::{self, Aad};
8
9use crate::{Deserializer, Serializer};
10
11/// Algorithms usable with this middleware.
12///
13/// This module reexports the algorithms from [`ring::aead`].
14pub mod algorithm {
15	pub use super::aead::{
16		AES_128_GCM, AES_256_GCM, CHACHA20_POLY1305,
17	};
18}
19
20pub use self::aead::{
21	BoundKey, Nonce, NonceSequence, OpeningKey, SealingKey,
22	UnboundKey,
23};
24
25/// Middleware that encrypts data for transport.
26///
27/// This is the serializer.
28#[derive(Debug)]
29pub struct Encrypt<U, N>
30where
31	N: NonceSequence,
32{
33	next: U,
34	key: SealingKey<N>,
35}
36
37impl<U, N> Encrypt<U, N>
38where
39	N: NonceSequence,
40{
41	/// Create a new [`Encrypt`] serializer that uses `key`.
42	pub fn new(next: U, key: SealingKey<N>) -> Self {
43		Self { next, key }
44	}
45
46	/// Get a reference to the next serializer/deserializer in the chain.
47	pub fn next_ref(&self) -> &U {
48		&self.next
49	}
50
51	/// Get a reference to the next serializer/deserializer in the chain.
52	pub fn next_mut(&mut self) -> &mut U {
53		&mut self.next
54	}
55
56	/// Consume `self` and return the next serializer/deserializer in the chain.
57	pub fn into_next(self) -> U {
58		self.next
59	}
60}
61
62/// Possible errors that might occur during serialization.
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub enum SerializeError<T> {
65	/// An error from the next serializer in the chain.
66	Next(T),
67	/// The data could not be encrypted.
68	EncryptError,
69}
70
71impl<T> fmt::Display for SerializeError<T>
72where
73	T: fmt::Display,
74{
75	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76		match self {
77			Self::Next(e) => e.fmt(f),
78			Self::EncryptError => f.write_str("encryption failure"),
79		}
80	}
81}
82
83#[cfg(feature = "std")]
84impl<T: std::error::Error> std::error::Error for SerializeError<T> {}
85
86impl<T, U, N> Serializer<T> for Encrypt<U, N>
87where
88	N: NonceSequence,
89	U: Serializer<T>,
90{
91	type Error = SerializeError<U::Error>;
92
93	fn serialize(&mut self, t: &T) -> Result<Vec<u8>, Self::Error> {
94		let mut data =
95			self.next.serialize(t).map_err(SerializeError::Next)?;
96
97		let tag = self
98			.key
99			.seal_in_place_separate_tag(Aad::empty(), &mut data)
100			.map_err(|_| SerializeError::EncryptError)?;
101
102		let out = [&data, tag.as_ref()].concat();
103
104		Ok(out)
105	}
106}
107
108/// Middleware that encrypts data for transport.
109///
110/// This is the deserializer.
111#[derive(Debug)]
112pub struct Decrypt<U, N>
113where
114	N: NonceSequence,
115{
116	next: U,
117	key: OpeningKey<N>,
118}
119
120impl<U, N> Decrypt<U, N>
121where
122	N: NonceSequence,
123{
124	/// Create a new [`Decrypt`] serializer that uses `key`.
125	pub fn new(next: U, key: OpeningKey<N>) -> Self {
126		Self { next, key }
127	}
128
129	/// Get a reference to the next serializer/deserializer in the chain.
130	pub fn next_ref(&self) -> &U {
131		&self.next
132	}
133
134	/// Get a reference to the next serializer/deserializer in the chain.
135	pub fn next_mut(&mut self) -> &mut U {
136		&mut self.next
137	}
138
139	/// Consume `self` and return the next serializer/deserializer in the chain.
140	pub fn into_next(self) -> U {
141		self.next
142	}
143}
144
145/// Possible errors that might occur during deserialization.
146#[derive(Debug, Clone, PartialEq, Eq)]
147pub enum DeserializeError<T> {
148	/// An error from the next deserializer in the chain.
149	Next(T),
150	/// The data does not have a tag.
151	NoTag,
152	/// The data could not be decrypted.
153	DecryptError,
154}
155
156impl<T> fmt::Display for DeserializeError<T>
157where
158	T: fmt::Display,
159{
160	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161		match self {
162			Self::Next(e) => e.fmt(f),
163			Self::NoTag => f.write_str("no tag"),
164			Self::DecryptError => f.write_str("decryption failure"),
165		}
166	}
167}
168
169#[cfg(feature = "std")]
170impl<T: std::error::Error> std::error::Error for DeserializeError<T> {}
171
172impl<T, U, N> Deserializer<T> for Decrypt<U, N>
173where
174	N: NonceSequence,
175	U: Deserializer<T>,
176{
177	type Error = DeserializeError<U::Error>;
178
179	fn deserialize(
180		&mut self,
181		buf: &mut [u8],
182	) -> Result<T, Self::Error> {
183		let plaintext = self
184			.key
185			.open_in_place(Aad::empty(), buf)
186			.map_err(|_| DeserializeError::DecryptError)?;
187
188		self.next
189			.deserialize(plaintext)
190			.map_err(DeserializeError::Next)
191	}
192}