strong_box/
key.rs

1use secrecy::ExposeSecret as _;
2
3/// A key used by various kinds of [`StrongBox`](super::StrongBox) for encrypting or decrypting data.
4#[derive(Debug)]
5pub struct Key(secrecy::SecretBox<[u8; 32]>);
6
7impl Key {
8	pub fn expose_secret(&self) -> &[u8; 32] {
9		self.0.expose_secret()
10	}
11}
12
13impl Clone for Key {
14	fn clone(&self) -> Self {
15		Self(Box::new(*self.expose_secret()).into())
16	}
17}
18
19impl From<Box<[u8; 32]>> for Key {
20	fn from(k: Box<[u8; 32]>) -> Self {
21		Key(k.into())
22	}
23}
24
25/// Create a key suitable for use in a [`StrongBox`](super::StrongBox).
26///
27/// This isn't usually required in real-world usage, as you'll *usually* have your keys
28/// stored somewhere out of the way.  However, for testing use, or the odd occasion when
29/// encryption/decryption is very temporary, a simple function to generate a secure key
30/// is useful to have laying around.
31#[tracing::instrument(level = "debug")]
32pub fn generate_key() -> Key {
33	use rand::{RngCore, rng};
34
35	let mut k = [0u8; 32];
36
37	rng().fill_bytes(&mut k);
38
39	Box::new(k).into()
40}