| 1 |
use zeroize::{Zeroize, ZeroizeOnDrop}; |
| 2 |
|
| 3 |
/// A wrapper around a `Box<[u8]>` that automatically zeroizes the memory when dropped. |
| 4 |
/// |
| 5 |
/// This struct is intended to hold sensitive data that needs to be stored on the heap. |
| 6 |
/// The `Box<[u8]>` ensures that the data is not accidentally copied, and `ZeroizeOnDrop` |
| 7 |
/// ensures that the memory is cleared when the struct goes out of scope. |
| 8 |
#[derive(Zeroize, ZeroizeOnDrop)] |
| 9 |
pub struct SecretBox(Box<[u8]>); |
| 10 |
|
| 11 |
impl SecretBox { |
| 12 |
/// Creates a new `SecretBox` from a `Vec<u8>`. |
| 13 |
pub fn new(data: Vec<u8>) -> Self { |
| 14 |
Self(data.into_boxed_slice()) |
| 15 |
} |
| 16 |
|
| 17 |
/// Returns a reference to the inner slice. |
| 18 |
pub fn as_slice(&self) -> &[u8] { |
| 19 |
&self.0 |
| 20 |
} |
| 21 |
|
| 22 |
/// Returns a mutable reference to the inner slice. |
| 23 |
pub fn as_mut_slice(&mut self) -> &mut [u8] { |
| 24 |
&mut self.0 |
| 25 |
} |
| 26 |
} |
| 27 |
|
| 28 |
impl AsRef<[u8]> for SecretBox { |
| 29 |
fn as_ref(&self) -> &[u8] { |
| 30 |
self.as_slice() |
| 31 |
} |
| 32 |
} |
| 33 |
|
| 34 |
impl From<Vec<u8>> for SecretBox { |
| 35 |
fn from(data: Vec<u8>) -> Self { |
| 36 |
Self::new(data) |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
#[cfg(test)] |
| 41 |
mod tests { |
| 42 |
use super::*; |
| 43 |
|
| 44 |
#[test] |
| 45 |
fn test_secret_box_creation() { |
| 46 |
let data = vec![1, 2, 3, 4]; |
| 47 |
let secret = SecretBox::new(data.clone()); |
| 48 |
assert_eq!(secret.as_slice(), &data[..]); |
| 49 |
} |
| 50 |
|
| 51 |
#[test] |
| 52 |
fn test_secret_box_modification() { |
| 53 |
let data = vec![1, 2, 3, 4]; |
| 54 |
let mut secret = SecretBox::new(data.clone()); |
| 55 |
secret.as_mut_slice()[0] = 99; |
| 56 |
assert_eq!(secret.as_slice(), &[99, 2, 3, 4]); |
| 57 |
} |
| 58 |
|
| 59 |
#[test] |
| 60 |
fn test_secret_box_from_vec() { |
| 61 |
let data = vec![10, 11, 12]; |
| 62 |
let secret: SecretBox = data.clone().into(); |
| 63 |
assert_eq!(secret.as_slice(), &data[..]); |
| 64 |
} |
| 65 |
|
| 66 |
#[test] |
| 67 |
fn test_secret_box_as_ref() { |
| 68 |
let data = vec![20, 21, 22]; |
| 69 |
let secret = SecretBox::new(data.clone()); |
| 70 |
let slice: &[u8] = secret.as_ref(); |
| 71 |
assert_eq!(slice, &data[..]); |
| 72 |
} |
| 73 |
} |