devolutions_crypto/online_ciphertext/mod.rs
1//! Module for chunked, streaming symmetric/asymmetric encryption/decryption.
2//!
3//! Unlike the [`ciphertext`](super::ciphertext) module, which encrypts a whole buffer at
4//! once, this module processes the data one chunk at a time using the STREAM construction.
5//! This lets you encrypt or decrypt data that does not fit in memory, or that arrives
6//! progressively, without ever holding the full plaintext at once.
7//!
8//! You start by creating an `OnlineCiphertextEncryptor`, which produces an
9//! `OnlineCiphertextHeader`. That header is not secret but is required to decrypt: keep it
10//! alongside the ciphertext. You then feed each chunk to `encrypt_next_chunk`, and the final
11//! (possibly smaller) chunk to `encrypt_last_chunk`. Every chunk fed to `encrypt_next_chunk`
12//! must be exactly `chunk_size` bytes; the last chunk may be smaller. Each produced chunk is
13//! `get_tag_size()` bytes larger than its input because of the authentication tag.
14//!
15//! ### Symmetric
16//!
17//! ```rust
18//! use devolutions_crypto::utils::generate_key;
19//! use devolutions_crypto::online_ciphertext::{
20//! OnlineCiphertextEncryptor, OnlineCiphertextHeader, OnlineCiphertextVersion,
21//! };
22//! use std::convert::TryFrom;
23//!
24//! let key: Vec<u8> = generate_key(32).expect("generate key shouldn't fail");
25//! let chunk_size = 16u32;
26//!
27//! // Encrypt the data one chunk at a time.
28//! let mut encryptor =
29//! OnlineCiphertextEncryptor::new(&key, b"", chunk_size, OnlineCiphertextVersion::Latest)
30//! .expect("creating the encryptor shouldn't fail");
31//!
32//! // The header is required to decrypt; store or transmit it alongside the ciphertext.
33//! let header: Vec<u8> = (&encryptor.get_header()).into();
34//!
35//! // Each `_next_chunk` input must be exactly `chunk_size` bytes; the last chunk may be smaller.
36//! let chunk1 = encryptor.encrypt_next_chunk(b"0123456789abcdef", b"").expect("encrypting a chunk shouldn't fail");
37//! let chunk2 = encryptor.encrypt_last_chunk(b"the last chunk", b"").expect("encrypting the last chunk shouldn't fail");
38//!
39//! // Decrypt using the header.
40//! let header = OnlineCiphertextHeader::try_from(header.as_slice()).expect("the header should be valid");
41//! let mut decryptor = header.into_decryptor(&key, b"").expect("creating the decryptor shouldn't fail");
42//!
43//! let mut decrypted = decryptor.decrypt_next_chunk(&chunk1, b"").expect("decrypting a chunk shouldn't fail");
44//! decrypted.extend_from_slice(&decryptor.decrypt_last_chunk(&chunk2, b"").expect("decrypting the last chunk shouldn't fail"));
45//!
46//! assert_eq!(decrypted, b"0123456789abcdefthe last chunk");
47//! ```
48//!
49//! ### Asymmetric
50//! Here, you will need a `PublicKey` to encrypt data and the corresponding
51//! `PrivateKey` to decrypt it. You can generate them by using `generate_keypair`
52//! in the [Key module](super::key).
53//!
54//! ```rust
55//! use devolutions_crypto::key::{generate_keypair, KeyVersion, KeyPair};
56//! use devolutions_crypto::online_ciphertext::{
57//! OnlineCiphertextEncryptor, OnlineCiphertextHeader, OnlineCiphertextVersion,
58//! };
59//! use std::convert::TryFrom;
60//!
61//! let keypair: KeyPair = generate_keypair(KeyVersion::Latest);
62//! let chunk_size = 16u32;
63//!
64//! let mut encryptor = OnlineCiphertextEncryptor::new_asymmetric(
65//! &keypair.public_key, b"", chunk_size, OnlineCiphertextVersion::Latest,
66//! ).expect("creating the encryptor shouldn't fail");
67//!
68//! let header: Vec<u8> = (&encryptor.get_header()).into();
69//!
70//! let chunk1 = encryptor.encrypt_next_chunk(b"0123456789abcdef", b"").expect("encrypting a chunk shouldn't fail");
71//! let chunk2 = encryptor.encrypt_last_chunk(b"the last chunk", b"").expect("encrypting the last chunk shouldn't fail");
72//!
73//! let header = OnlineCiphertextHeader::try_from(header.as_slice()).expect("the header should be valid");
74//! let mut decryptor = header.into_decryptor_asymmetric(&keypair.private_key, b"").expect("creating the decryptor shouldn't fail");
75//!
76//! let mut decrypted = decryptor.decrypt_next_chunk(&chunk1, b"").expect("decrypting a chunk shouldn't fail");
77//! decrypted.extend_from_slice(&decryptor.decrypt_last_chunk(&chunk2, b"").expect("decrypting the last chunk shouldn't fail"));
78//!
79//! assert_eq!(decrypted, b"0123456789abcdefthe last chunk");
80//! ```
81
82mod online_ciphertext_v1;
83
84use std::borrow::Borrow;
85
86use super::CiphertextSubtype;
87use super::DataType;
88use super::Error;
89use super::Header;
90use super::HeaderType;
91pub use super::OnlineCiphertextVersion;
92use super::Result;
93
94use super::key::{PrivateKey, PublicKey};
95
96use online_ciphertext_v1::{OnlineCiphertextV1Decryptor, OnlineCiphertextV1Encryptor};
97use online_ciphertext_v1::{
98 OnlineCiphertextV1Header, OnlineCiphertextV1HeaderAsymmetric, OnlineCiphertextV1HeaderSymmetric,
99};
100
101use paste::paste;
102
103impl OnlineCiphertextHeader {
104 pub fn into_decryptor(self, key: &[u8], aad: &[u8]) -> Result<OnlineCiphertextDecryptor> {
105 let mut full_aad: Vec<u8> = self.header.borrow().into();
106 full_aad.extend_from_slice(aad);
107
108 match self.payload {
109 OnlineCiphertextHeaderPayload::V1(header) => match header {
110 OnlineCiphertextV1Header::Symmetric(header) => {
111 let cipher = OnlineCiphertextV1Decryptor::new(key, full_aad, header);
112
113 Ok(OnlineCiphertextDecryptor::V1(cipher))
114 }
115 _ => Err(Error::InvalidDataType),
116 },
117 }
118 }
119
120 pub fn into_decryptor_asymmetric(
121 self,
122 key: &PrivateKey,
123 aad: &[u8],
124 ) -> Result<OnlineCiphertextDecryptor> {
125 let mut full_aad: Vec<u8> = self.header.borrow().into();
126 full_aad.extend_from_slice(aad);
127
128 match self.payload {
129 OnlineCiphertextHeaderPayload::V1(header) => match header {
130 OnlineCiphertextV1Header::Asymmetric(header) => {
131 let cipher =
132 OnlineCiphertextV1Decryptor::new_asymmetric(key, full_aad, header)?;
133
134 Ok(OnlineCiphertextDecryptor::V1(cipher))
135 }
136 _ => Err(Error::InvalidDataType),
137 },
138 }
139 }
140
141 pub fn get_serialized_size(&self) -> usize {
142 self.payload.get_serialized_size() + 8
143 }
144
145 pub fn get_chunk_size(&self) -> u32 {
146 self.payload.get_chunk_size()
147 }
148}
149
150impl OnlineCiphertextEncryptor {
151 pub fn new(
152 key: &[u8],
153 aad: &[u8],
154 chunk_size: u32,
155 version: OnlineCiphertextVersion,
156 ) -> Result<OnlineCiphertextEncryptor> {
157 let header = Header::<OnlineCiphertextHeader> {
158 data_subtype: CiphertextSubtype::Symmetric,
159 ..Default::default()
160 };
161
162 let mut full_aad: Vec<u8> = header.borrow().into();
163 full_aad.extend_from_slice(aad);
164
165 match version {
166 OnlineCiphertextVersion::V1 | OnlineCiphertextVersion::Latest => {
167 let cipher = OnlineCiphertextV1Encryptor::new(key, full_aad, chunk_size)?;
168
169 Ok(OnlineCiphertextEncryptor::V1(cipher))
170 }
171 }
172 }
173
174 pub fn new_asymmetric(
175 public_key: &PublicKey,
176 aad: &[u8],
177 chunk_size: u32,
178 version: OnlineCiphertextVersion,
179 ) -> Result<OnlineCiphertextEncryptor> {
180 let header = Header::<OnlineCiphertextHeader> {
181 data_subtype: CiphertextSubtype::Asymmetric,
182 ..Default::default()
183 };
184
185 let mut full_aad: Vec<u8> = header.borrow().into();
186 full_aad.extend_from_slice(aad);
187
188 match version {
189 OnlineCiphertextVersion::V1 | OnlineCiphertextVersion::Latest => {
190 let cipher =
191 OnlineCiphertextV1Encryptor::new_asymmetric(public_key, full_aad, chunk_size)?;
192
193 Ok(OnlineCiphertextEncryptor::V1(cipher))
194 }
195 }
196 }
197}
198
199macro_rules! online_ciphertext_header_impl {
200 ($($version_name:ident),+) => {
201 paste! {
202 /// A versionned online ciphertext.
203 #[derive(Clone, Debug)]
204 pub struct OnlineCiphertextHeader {
205 pub(crate) header: Header<OnlineCiphertextHeader>,
206 payload: OnlineCiphertextHeaderPayload,
207 }
208
209 impl HeaderType for OnlineCiphertextHeader {
210 type Version = OnlineCiphertextVersion;
211 type Subtype = CiphertextSubtype;
212
213 fn data_type() -> DataType {
214 DataType::OnlineCiphertext
215 }
216 }
217
218 #[derive(Clone, Debug)]
219 enum OnlineCiphertextHeaderPayload {
220 $(
221 $version_name([<OnlineCiphertext $version_name Header>]),
222 ),+
223 }
224
225 impl OnlineCiphertextHeaderPayload {
226 pub fn get_serialized_size(&self) -> usize {
227 match &self {
228 $(
229 Self::$version_name(p) => p.get_serialized_size(),
230 ),+
231 }
232 }
233
234 pub fn get_chunk_size(&self) -> u32 {
235 match &self {
236 $(
237 Self::$version_name(p) => p.get_chunk_size(),
238 ),+
239 }
240 }
241 }
242
243 impl From<&OnlineCiphertextHeader> for Vec<u8> {
244 fn from(value: &OnlineCiphertextHeader) -> Self {
245 let mut output: Vec<u8> = value.header.borrow().into();
246 let mut payload: Vec<u8> = match &value.payload {
247 $(
248 OnlineCiphertextHeaderPayload::$version_name(p) => {
249 p.into()
250 },
251 ),+
252 };
253
254 output.append(&mut payload);
255 output
256 }
257 }
258
259 impl TryFrom<&[u8]> for OnlineCiphertextHeader {
260 type Error = Error;
261
262 fn try_from(value: &[u8]) -> Result<Self> {
263 if value.len() < 8 {
264 return Err(Error::InvalidLength);
265 }
266 let header = Header::<OnlineCiphertextHeader>::try_from(&value[..8])?;
267
268 let version = if header.version == OnlineCiphertextVersion::Latest { OnlineCiphertextVersion::V1 } else { header.version };
269 match version {
270 $(
271 OnlineCiphertextVersion::$version_name => {
272 match header.data_subtype {
273 CiphertextSubtype::Symmetric => {
274 Ok(Self {
275 header,
276 payload:
277 OnlineCiphertextHeaderPayload::$version_name
278 ([<OnlineCiphertext $version_name Header>]::Symmetric
279 ([<OnlineCiphertext $version_name HeaderSymmetric>]::try_from(&value[8..])?))
280 })
281 }
282 CiphertextSubtype::Asymmetric => {
283 Ok(Self {
284 header,
285 payload:
286 OnlineCiphertextHeaderPayload::$version_name
287 ([<OnlineCiphertext $version_name Header>]::Asymmetric
288 ([<OnlineCiphertext $version_name HeaderAsymmetric>]::try_from(&value[8..])?))
289 })
290 }
291 CiphertextSubtype::None => Err(Error::UnknownSubtype)
292 }
293 }
294 ),+
295 OnlineCiphertextVersion::Latest => unreachable!("Latest is checked before the match arm")
296 }
297 }
298 }
299 }
300 };
301}
302
303macro_rules! online_ciphertext_impl {
304 ($name:ident, $func:ident, $($version_name:ident),+) => {
305 paste! {
306 pub enum [<OnlineCiphertext $name>] {
307 $(
308 $version_name([<OnlineCiphertext $version_name $name>]),
309 ),+
310 }
311
312 impl [<OnlineCiphertext $name>] {
313 pub fn get_chunk_size(&self) -> u32 {
314 match &self {
315 $(
316 [<OnlineCiphertext $name>]::$version_name(cipher) => {
317 cipher.get_chunk_size()
318 }
319 ),+
320 }
321 }
322
323 pub fn get_tag_size(&self) -> usize {
324 match &self {
325 $(
326 [<OnlineCiphertext $name>]::$version_name(cipher) => {
327 cipher.get_tag_size()
328 }
329 ),+
330 }
331 }
332
333 pub fn get_header(&self) -> OnlineCiphertextHeader {
334 match self {
335 $(
336 Self::$version_name(encryptor) => {
337 let data_subtype = encryptor.get_header().get_subtype();
338 OnlineCiphertextHeader {
339 header: Header::<OnlineCiphertextHeader> {
340 data_subtype,
341 ..Default::default()
342 },
343 payload: OnlineCiphertextHeaderPayload::$version_name(encryptor.get_header().clone()),
344 }
345 }
346 ),+
347 }
348 }
349
350 pub fn [<$func _next_chunk>](
351 &mut self,
352 data: &[u8],
353 aad: &[u8],
354 ) -> Result<Vec<u8>> {
355 match self {
356 $(
357 [<OnlineCiphertext $name>]::$version_name(cipher) => {
358 cipher.[<$func _next_chunk>](data, aad)
359 }
360 ),+
361 }
362 }
363
364 pub fn [<$func _next_chunk_in_place>](
365 &mut self,
366 data: &mut Vec<u8>,
367 aad: &[u8],
368 ) -> Result<()> {
369 match self {
370 $(
371 [<OnlineCiphertext $name>]::$version_name(cipher) => {
372 cipher.[<$func _next_chunk_in_place>](data, aad)
373 }
374 ),+
375 }
376 }
377
378 pub fn [<$func _last_chunk>](
379 self,
380 data: &[u8],
381 aad: &[u8],
382 ) -> Result<Vec<u8>> {
383 match self {
384 $(
385 [<OnlineCiphertext $name>]::$version_name(cipher) => {
386 cipher.[<$func _last_chunk>](data, aad)
387 }
388 ),+
389 }
390 }
391
392 pub fn [<$func _last_chunk_in_place>](
393 self,
394 data: &mut Vec<u8>,
395 aad: &[u8],
396 ) -> Result<()> {
397 match self {
398 $(
399 [<OnlineCiphertext $name>]::$version_name(cipher) => {
400 cipher.[<$func _last_chunk_in_place>](data, aad)
401 }
402 ),+
403 }
404 }
405 }
406 }
407 };
408}
409
410online_ciphertext_impl!(Encryptor, encrypt, V1);
411online_ciphertext_impl!(Decryptor, decrypt, V1);
412
413online_ciphertext_header_impl!(V1);