algae_cli/
streams.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
use std::iter;

use age::{Decryptor, Encryptor, Identity, Recipient};
use miette::{Context as _, IntoDiagnostic as _, Result};
use tokio::io::AsyncWriteExt as _;
use tokio_util::compat::{FuturesAsyncReadCompatExt as _, FuturesAsyncWriteCompatExt as _};
use tracing::trace;

/// Encrypt a bytestream given a [`Recipient`].
pub async fn encrypt_stream<R: tokio::io::AsyncRead + Unpin, W: futures::AsyncWrite + Unpin>(
	mut reader: R,
	writer: W,
	key: Box<dyn Recipient + Send>,
) -> Result<u64> {
	let mut encrypting_writer = Encryptor::with_recipients(iter::once(&*key as _))
		.expect("BUG: a single recipient is always given")
		.wrap_async_output(writer)
		.await
		.into_diagnostic()?
		.compat_write();

	let bytes = tokio::io::copy(&mut reader, &mut encrypting_writer)
		.await
		.into_diagnostic()
		.wrap_err("encrypting data in stream")?;

	encrypting_writer
		.shutdown()
		.await
		.into_diagnostic()
		.wrap_err("closing the encrypted output")?;

	trace!(?bytes, "bytestream encrypted");

	Ok(bytes)
}

/// Decrypt a bytestream given an [`Identity`].
pub async fn decrypt_stream<R: futures::AsyncRead + Unpin, W: tokio::io::AsyncWrite + Unpin>(
	reader: R,
	mut writer: W,
	key: Box<dyn Identity>,
) -> Result<u64> {
	let mut decrypting_reader = Decryptor::new_async(reader)
		.await
		.into_diagnostic()?
		.decrypt_async(iter::once(&*key))
		.into_diagnostic()?
		.compat();

	let bytes = tokio::io::copy(&mut decrypting_reader, &mut writer)
		.await
		.into_diagnostic()
		.wrap_err("decrypting data")?;

	writer
		.shutdown()
		.await
		.into_diagnostic()
		.wrap_err("closing the output stream")?;

	trace!(?bytes, "bytestream decrypted");

	Ok(bytes)
}