Skip to main content

arx_kw/
memory.rs

1use crate::ArxKwError;
2use std::{
3    fmt,
4    ops::{Deref, DerefMut},
5};
6use zeroize::{Zeroize, ZeroizeOnDrop};
7
8/// Maximum accepted plaintext size: one MiB. E/G retain their stricter 64-byte limit.
9pub const MAX_INPUT_LENGTH: usize = 1024 * 1024;
10/// Owned plaintext that is wiped on drop and redacted from debug output.
11/// Avoid making unguarded copies through the borrowed slice.
12#[derive(Zeroize, ZeroizeOnDrop)]
13pub struct SecretBytes(Vec<u8>);
14
15impl SecretBytes {
16    pub(crate) const fn new(bytes: Vec<u8>) -> Self {
17        Self(bytes)
18    }
19}
20impl Deref for SecretBytes {
21    type Target = [u8];
22    fn deref(&self) -> &[u8] {
23        &self.0
24    }
25}
26impl AsRef<[u8]> for SecretBytes {
27    fn as_ref(&self) -> &[u8] {
28        &self.0
29    }
30}
31impl fmt::Debug for SecretBytes {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        f.write_str("SecretBytes([REDACTED])")
34    }
35}
36
37/// Owned wrapping key that is wiped on drop and redacted from debug output.
38/// Borrow with `&*key` when calling this crate. Caller-owned copies are not erased.
39#[derive(Zeroize, ZeroizeOnDrop)]
40pub struct SecretKey<const N: usize>([u8; N]);
41impl<const N: usize> SecretKey<N> {
42    /// Takes ownership of a key array. Erase any remaining caller-owned copies.
43    #[must_use]
44    pub const fn new(key: [u8; N]) -> Self {
45        Self(key)
46    }
47}
48impl<const N: usize> Deref for SecretKey<N> {
49    type Target = [u8; N];
50    fn deref(&self) -> &[u8; N] {
51        &self.0
52    }
53}
54impl<const N: usize> DerefMut for SecretKey<N> {
55    fn deref_mut(&mut self) -> &mut [u8; N] {
56        &mut self.0
57    }
58}
59impl<const N: usize> fmt::Debug for SecretKey<N> {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        f.write_str("SecretKey([REDACTED])")
62    }
63}
64
65#[cfg(any(feature = "envelope", feature = "ex", feature = "gx"))]
66pub fn check_length(length: usize, maximum: usize) -> Result<(), ArxKwError> {
67    if length > maximum {
68        return Err(crate::InvalidLengthError::UpTo(length, maximum).into());
69    }
70    Ok(())
71}
72
73pub fn allocate(length: usize) -> Result<Vec<u8>, ArxKwError> {
74    let mut buffer = Vec::new();
75    buffer
76        .try_reserve_exact(length)
77        .map_err(|_| ArxKwError::AllocationFailed)?;
78    Ok(buffer)
79}
80
81#[cfg(any(feature = "e", feature = "g", feature = "ex", feature = "gx"))]
82pub fn copy_secret(input: &[u8]) -> Result<zeroize::Zeroizing<Vec<u8>>, ArxKwError> {
83    let mut output = zeroize::Zeroizing::new(allocate(input.len())?);
84    output.extend_from_slice(input);
85    Ok(output)
86}
87
88#[cfg(test)]
89mod tests {
90    use super::*;
91    #[test]
92    fn allocation_overflow_is_an_error() {
93        assert!(matches!(
94            allocate(usize::MAX),
95            Err(ArxKwError::AllocationFailed)
96        ));
97    }
98}
99
100#[cfg(test)]
101mod secret_tests {
102    use super::*;
103    #[test]
104    fn secrets_are_redacted_and_explicitly_erasable() {
105        fn requires_drop_wipe<T: ZeroizeOnDrop>() {}
106        requires_drop_wipe::<SecretKey<32>>();
107        requires_drop_wipe::<SecretBytes>();
108        let mut key = SecretKey::new([0x42; 32]);
109        assert_eq!(format!("{key:?}"), "SecretKey([REDACTED])");
110        key.zeroize();
111        assert_eq!(&*key, &[0; 32]);
112        let mut plaintext = SecretBytes::new(vec![0x42; 32]);
113        assert_eq!(format!("{plaintext:?}"), "SecretBytes([REDACTED])");
114        plaintext.zeroize();
115        assert!(plaintext.is_empty());
116    }
117}