Skip to content

Commit a17a5a3

Browse files
committed
Rework the SecretBox type
1 parent c84c5b7 commit a17a5a3

File tree

1 file changed

+58
-5
lines changed

1 file changed

+58
-5
lines changed

secrecy/src/boxed.rs

+58-5
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,63 @@
11
//! `Box` types containing secrets
22
3-
use super::{DebugSecret, Secret};
3+
use core::{
4+
any,
5+
fmt::{self, Debug},
6+
};
7+
48
use alloc::boxed::Box;
5-
use zeroize::Zeroize;
9+
use zeroize::{Zeroize, ZeroizeOnDrop};
10+
11+
/// Same as [`Secret`], but keeps the secret value in the heap instead of on the stack.
12+
pub struct SecretBox<S: Zeroize> {
13+
inner_secret: Box<S>,
14+
}
15+
16+
impl<S: Zeroize + Clone> SecretBox<S> {
17+
/// Create a secret value using the provided function as a constructor.
18+
///
19+
/// The implementation makes an effort to zeroize the locally constructed value
20+
/// before it is copied to the heap, and constructing it inside the closure minimizes
21+
/// the possibility of it being accidentally copied by other code.
22+
pub fn new(ctr: impl FnOnce() -> S) -> Self {
23+
let mut data = ctr();
24+
let secret = Self {
25+
inner_secret: Box::new(data.clone()),
26+
};
27+
data.zeroize();
28+
secret
29+
}
30+
}
31+
32+
impl<S: Zeroize + Default> Default for SecretBox<S> {
33+
fn default() -> Self {
34+
Self {
35+
inner_secret: Box::new(S::default()),
36+
}
37+
}
38+
}
39+
40+
impl<S: Zeroize> Zeroize for SecretBox<S> {
41+
fn zeroize(&mut self) {
42+
self.inner_secret.as_mut().zeroize()
43+
}
44+
}
45+
46+
impl<S: Zeroize> Drop for SecretBox<S> {
47+
fn drop(&mut self) {
48+
self.zeroize()
49+
}
50+
}
651

7-
/// `Box` types containing a secret value
8-
pub type SecretBox<S> = Secret<Box<S>>;
52+
impl<S: Zeroize> ZeroizeOnDrop for SecretBox<S> {}
953

10-
impl<S: DebugSecret + Zeroize> DebugSecret for Box<S> {}
54+
impl<S> Debug for SecretBox<S>
55+
where
56+
S: Zeroize,
57+
{
58+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59+
f.write_str("SecretBox(")?;
60+
f.write_str(any::type_name::<Self>())?;
61+
f.write_str(")")
62+
}
63+
}

0 commit comments

Comments
 (0)