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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
use chacha20poly1305::{
	aead::{Aead as _, Payload},
	ChaCha20Poly1305, KeyInit as _,
};
use rand::{thread_rng, RngCore};
use secrecy::ExposeSecret as _;
use std::{collections::HashMap, fmt::Debug};

use super::{Error, Key, KeyId};

/// A secure symmetric encryption container, supporting key rotation and AAD contexts.
///
/// This is your basic, Mark 1 mod 0 [`StrongBox`].  Given an encryption key, it will
/// encrypt data all day long with a modern, fast cipher (ChaCha20) with integrity protection and
/// authenticated additional data (using Poly1305).  If provided with one or more decryption keys,
/// it will decrypt data that was encrypted with *any* of those keys, giving you the ability to
/// "rotate" your key over time, by creating a new key, making it the new encryption key, and
/// keeping the old key in the set of "decryption" keys until such time as all data has been
/// re-encrypted with the new key.
///
/// The "authenticated additional data" is a mouthful, but what it means is that when you encrypt
/// data, you provide the encryption with a "context", such as the ID of the user that the
/// encrypted data belongs to.  When you decrypt the data again, you provide the ID of the user the
/// data belongs to, and if they don't match, decryption fails.  Why is that useful?  Because if
/// an attacker gets write access to the database, and moves encrypted data from one user to
/// another, Bad Things can happen.  [This Security StackExchange answer](https://security.stackexchange.com/a/179279/167630) is an excellent explanation of
/// why an encryption context is useful.
///
/// # Example
///
/// ```rust
/// # use strong_box::{Error, StrongBox};
/// fn main() -> Result<(), Error> {
///
/// // A couple of keys are always useful to have
/// let old_key = strong_box::generate_key();
/// let new_key = strong_box::generate_key();
///
/// let old_strongbox = StrongBox::new(old_key.clone(), [old_key]);
/// let new_strongbox = StrongBox::new(new_key.clone(), [new_key]);
/// // This StrongBox encrypts with `new_key`, but can decrypt ciphertexts
/// // encrypted with *either* `new_key` *or* `old_key`
/// let fallback_strongbox = StrongBox::new(new_key.clone(), vec![new_key, old_key]);
///
/// /////////////////////////////////////////////////////////
/// // A ciphertext encrypted using the old key
///
/// let ciphertext = old_strongbox.encrypt(b"Hello, old world!", b"some context")?;
///
/// // We'd *hope* that we can decrypt what we encrypted
/// assert_eq!(
///     b"Hello, old world!".to_vec(),
///     old_strongbox.decrypt(&ciphertext, b"some context")?
/// );
///
/// // A StrongBox that uses a different key won't be able to decrypt
/// let result = new_strongbox.decrypt(&ciphertext, b"some context");
/// assert!(matches!(result, Err(Error::Decryption)));
///
/// // Also, a StrongBox that uses the right key won't decrypt if the context isn't the
/// // same as was used to encrypt
/// let result = old_strongbox.decrypt(&ciphertext, b"a different context");
/// assert!(matches!(result, Err(Error::Decryption)));
///
/// // However, magic of magicks, the fallback StrongBox can do the job!
/// assert_eq!(
///     b"Hello, old world!".to_vec(),
///     fallback_strongbox.decrypt(&ciphertext, b"some context")?
/// );
///
/// //////////////////////////////////////////////////////////////
/// // Now, let's try a ciphertext encrypted using the new key
///
/// let ciphertext = new_strongbox.encrypt(b"Hello, new world!", b"new context")?;
///
/// // Again, the same StrongBox should be able to decrypt
/// assert_eq!(
///     b"Hello, new world!".to_vec(),
///     new_strongbox.decrypt(&ciphertext, b"new context")?
/// );
///
/// // Unsurprisingly, the fallback StrongBox can decrypt it too, as it uses the same key
/// assert_eq!(
///     b"Hello, new world!".to_vec(),
///     fallback_strongbox.decrypt(&ciphertext, b"new context")?
/// );
///
/// // A StrongBox using just the old key won't be able to decrypt, though
/// let result = old_strongbox.decrypt(&ciphertext, b"new context");
/// assert!(matches!(result, Err(Error::Decryption)));
///
/// // And again, the right StrongBox but the wrong context won't decrypt
/// let result = new_strongbox.decrypt(&ciphertext, b"some other context");
/// assert!(matches!(result, Err(Error::Decryption)));
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct StrongBox {
	encryption_key: Key<[u8; 32]>,
	encryption_key_id: KeyId,
	decryption_keys: HashMap<KeyId, Key<[u8; 32]>>,
}

impl StrongBox {
	/// Create a new [`StrongBox`].
	#[tracing::instrument(level = "debug", skip(enc_key, dec_keys))]
	pub fn new(
		enc_key: impl Into<Key<[u8; 32]>>,
		dec_keys: impl IntoIterator<Item = impl Into<Key<[u8; 32]>>>,
	) -> Self {
		let mut key_map: HashMap<KeyId, Key<[u8; 32]>> = HashMap::default();

		for key in dec_keys.into_iter() {
			let key = key.into();
			let key_id = super::key_id(&key);
			tracing::debug!(%key_id, "Including decryption key");
			key_map.insert(key_id, key);
		}

		let enc_key = enc_key.into();
		let enc_key_id = super::key_id(&enc_key);
		tracing::debug!("Encryption key is {enc_key_id}");

		Self {
			encryption_key_id: enc_key_id,
			encryption_key: enc_key,
			decryption_keys: key_map,
		}
	}

	/// Just like [`StrongBox::encrypt_secret`], but for data that isn't already protected by [`secrecy::Secret`].
	#[tracing::instrument(level = "debug", skip(plaintext))]
	pub fn encrypt(
		&self,
		plaintext: impl Into<Vec<u8>>,
		ctx: impl AsRef<[u8]> + Debug,
	) -> Result<Vec<u8>, Error> {
		self.encrypt_secret(Key::new(plaintext.into()), ctx.as_ref())
	}

	/// Encrypt secret data using the [`StrongBox`]'s encryption key, within the [`StrongBox`]'s specified context.
	///
	/// # Errors
	///
	/// Will return [`Error::Encryption`] or [`Error::Encoding`] in the (extremely
	/// unlikely) event something goes horribly wrong.
	#[tracing::instrument(level = "debug", skip(plaintext))]
	pub fn encrypt_secret(
		&self,
		plaintext: impl Into<Key<Vec<u8>>>,
		ctx: impl AsRef<[u8]> + Debug,
	) -> Result<Vec<u8>, Error> {
		let cipher = ChaCha20Poly1305::new((self.encryption_key.expose_secret()).into());
		let mut rng = thread_rng();
		let mut nonce = [0u8; 12];
		rng.fill_bytes(&mut nonce);

		let mut aad = Vec::<u8>::new();
		aad.extend_from_slice(ctx.as_ref());
		aad.extend_from_slice(self.encryption_key_id.as_bytes());
		aad.extend_from_slice(&nonce);

		let ciphertext = cipher
			.encrypt(
				(&nonce).into(),
				Payload {
					msg: plaintext.into().expose_secret(),
					aad: &aad,
				},
			)
			.map_err(|_| Error::Encryption)?;
		tracing::debug!(key_id=%self.encryption_key_id, "Encrypting");

		Ciphertext::new(self.encryption_key_id, nonce, ciphertext).to_bytes()
	}

	/// Decrypt a ciphertext, using any key the [`StrongBox`] knows, and validate that ciphertext
	/// was encrypted with the specified context.
	///
	/// # Errors
	///
	/// Will return [`Error::Decryption`] if the ciphertext was encrypted with a different
	/// key, or a different context.  A malformed ciphertext will return [`Error::Decoding`].
	#[tracing::instrument(level = "debug", skip(ciphertext))]
	pub fn decrypt(
		&self,
		ciphertext: impl AsRef<[u8]>,
		ctx: impl AsRef<[u8]> + Debug,
	) -> Result<Vec<u8>, Error> {
		let ciphertext = Ciphertext::try_from(ciphertext.as_ref())?;

		self.decrypt_ciphertext(&ciphertext, ctx.as_ref())
	}

	pub(crate) fn decrypt_ciphertext(
		&self,
		ciphertext: &Ciphertext,
		ctx: &[u8],
	) -> Result<Vec<u8>, Error> {
		if let Some(key) = self.decryption_keys.get(&ciphertext.key_id) {
			tracing::debug!(key_id=%ciphertext.key_id, "Decrypting");

			let mut aad = Vec::<u8>::new();
			aad.extend_from_slice(ctx.as_ref());
			aad.extend_from_slice(ciphertext.key_id.as_bytes());
			aad.extend_from_slice(&ciphertext.nonce);

			let cipher = ChaCha20Poly1305::new(key.expose_secret().into());
			let payload = Payload {
				msg: &ciphertext.ciphertext,
				aad: &aad,
			};
			cipher
				.decrypt((&ciphertext.nonce[..]).into(), payload)
				.map_err(|_| Error::Decryption)
		} else {
			tracing::debug!(key_id=%ciphertext.key_id, "Decryption key not found");
			Err(Error::Decryption)
		}
	}
}

// This makes more sense in base64
const CIPHERTEXT_MAGIC: [u8; 3] = [0xb1, 0xb8, 0xf5];

#[derive(Clone, Debug)]
pub(crate) struct Ciphertext {
	pub(crate) key_id: KeyId,
	pub(crate) nonce: [u8; 12],
	pub(crate) ciphertext: Vec<u8>,
}

impl Ciphertext {
	pub(crate) fn new(key_id: KeyId, nonce: [u8; 12], ciphertext: Vec<u8>) -> Self {
		Self {
			key_id,
			nonce,
			ciphertext,
		}
	}

	pub(crate) fn to_bytes(&self) -> Result<Vec<u8>, Error> {
		use ciborium_ll::{Encoder, Header};

		let mut v: Vec<u8> = Vec::new();

		v.extend_from_slice(&CIPHERTEXT_MAGIC);

		let mut enc = Encoder::from(&mut v);
		enc.push(Header::Array(Some(3)))
			.map_err(|e| Error::encoding("key_id", e))?;
		self.key_id.encode(&mut enc)?;
		enc.bytes(&self.nonce, None)
			.map_err(|e| Error::encoding("nonce", e))?;
		enc.bytes(&self.ciphertext, None)
			.map_err(|e| Error::encoding("ciphertext", e))?;

		tracing::debug!(
			nonce = self
				.nonce
				.iter()
				.map(|i| format!("{i:02x}"))
				.collect::<Vec<_>>()
				.join(""),
			ct = self
				.ciphertext
				.iter()
				.map(|i| format!("{i:02x}"))
				.collect::<Vec<_>>()
				.join(""),
			"{}",
			v.iter()
				.map(|i| format!("{i:02x}"))
				.collect::<Vec<_>>()
				.join("")
		);
		Ok(v)
	}
}

impl TryFrom<&[u8]> for Ciphertext {
	type Error = Error;

	fn try_from(b: &[u8]) -> Result<Self, Self::Error> {
		use ciborium_ll::{Decoder, Header};

		if b.len() < 21 {
			return Err(Error::invalid_ciphertext("too short"));
		}

		if b[0..3] != CIPHERTEXT_MAGIC {
			tracing::debug!(magic=?CIPHERTEXT_MAGIC, actual=?b[0..3]);
			return Err(Error::invalid_ciphertext("incorrect magic"));
		}

		let mut dec = Decoder::from(&b[3..]);

		let Header::Array(Some(3)) = dec.pull().map_err(|e| Error::decoding("array", e))? else {
			return Err(Error::invalid_ciphertext("expected array"));
		};

		let key_id = KeyId::decode(&mut dec)?;

		// CBOR's great, until you have to deal with segmented bytestrings...
		let Header::Bytes(len) = dec.pull().map_err(|e| Error::decoding("nonce header", e))? else {
			return Err(Error::invalid_ciphertext("expected nonce"));
		};

		let mut segments = dec.bytes(len);

		let Ok(Some(mut segment)) = segments.pull() else {
			return Err(Error::invalid_ciphertext("bad nonce"));
		};

		let mut buf = [0u8; 1024];
		let mut nonce = [0u8; 12];

		if let Some(chunk) = segment
			.pull(&mut buf[..])
			.map_err(|e| Error::decoding("nonce", e))?
		{
			// Is this necessary?  Probably better to be safe than sorry
			nonce[..].copy_from_slice(chunk);
		} else {
			return Err(Error::invalid_ciphertext("short nonce"));
		}

		// ibid.
		let Header::Bytes(len) = dec
			.pull()
			.map_err(|e| Error::decoding("ciphertext header", e))?
		else {
			return Err(Error::invalid_ciphertext("expected ciphertext"));
		};

		let mut segments = dec.bytes(len);

		let Ok(Some(mut segment)) = segments.pull() else {
			return Err(Error::invalid_ciphertext("bad ciphertext"));
		};

		let mut ciphertext: Vec<u8> = Vec::new();

		while let Some(chunk) = segment
			.pull(&mut buf[..])
			.map_err(|e| Error::decoding("ciphertext", e))?
		{
			ciphertext.extend_from_slice(chunk);
		}

		Ok(Self {
			key_id,
			nonce,
			ciphertext,
		})
	}
}