Skip to main content

opentdf_crypto/
types.rs

1//! Zeroizing cryptographic key types
2//!
3//! This module provides secure wrappers for cryptographic key material that
4//! automatically clear memory on drop to prevent key leakage.
5
6use zeroize::{Zeroize, ZeroizeOnDrop};
7
8#[cfg(feature = "kem-ec")]
9use zeroize::Zeroizing;
10
11/// AES-256 key (32 bytes) that zeroizes on drop
12#[derive(Clone, Zeroize, ZeroizeOnDrop)]
13pub struct AesKey(pub(crate) [u8; 32]);
14
15impl AesKey {
16    /// Create a new AES key from a 32-byte slice
17    pub fn from_slice(bytes: &[u8]) -> Result<Self, KeyError> {
18        if bytes.len() != 32 {
19            return Err(KeyError::InvalidLength {
20                expected: 32,
21                got: bytes.len(),
22            });
23        }
24        let mut key = [0u8; 32];
25        key.copy_from_slice(bytes);
26        Ok(AesKey(key))
27    }
28
29    /// Get a reference to the key bytes
30    pub fn as_slice(&self) -> &[u8] {
31        &self.0
32    }
33
34    /// Get a mutable reference to the key bytes
35    pub fn as_mut_slice(&mut self) -> &mut [u8] {
36        &mut self.0
37    }
38}
39
40/// Policy key (32 bytes) that zeroizes on drop
41#[derive(Clone, Zeroize, ZeroizeOnDrop)]
42pub struct PolicyKey(pub(crate) [u8; 32]);
43
44impl PolicyKey {
45    /// Create a new policy key from a 32-byte slice
46    pub fn from_slice(bytes: &[u8]) -> Result<Self, KeyError> {
47        if bytes.len() != 32 {
48            return Err(KeyError::InvalidLength {
49                expected: 32,
50                got: bytes.len(),
51            });
52        }
53        let mut key = [0u8; 32];
54        key.copy_from_slice(bytes);
55        Ok(PolicyKey(key))
56    }
57
58    /// Get a reference to the key bytes
59    pub fn as_slice(&self) -> &[u8] {
60        &self.0
61    }
62
63    /// Get a mutable reference to the key bytes
64    pub fn as_mut_slice(&mut self) -> &mut [u8] {
65        &mut self.0
66    }
67}
68
69/// Payload key (32 bytes) that zeroizes on drop
70#[derive(Clone, Zeroize, ZeroizeOnDrop)]
71pub struct PayloadKey(pub(crate) [u8; 32]);
72
73impl PayloadKey {
74    /// Create a new payload key from a 32-byte slice
75    pub fn from_slice(bytes: &[u8]) -> Result<Self, KeyError> {
76        if bytes.len() != 32 {
77            return Err(KeyError::InvalidLength {
78                expected: 32,
79                got: bytes.len(),
80            });
81        }
82        let mut key = [0u8; 32];
83        key.copy_from_slice(bytes);
84        Ok(PayloadKey(key))
85    }
86
87    /// Get a reference to the key bytes
88    pub fn as_slice(&self) -> &[u8] {
89        &self.0
90    }
91
92    /// Get a mutable reference to the key bytes
93    pub fn as_mut_slice(&mut self) -> &mut [u8] {
94        &mut self.0
95    }
96}
97
98/// 96-bit nonce (12 bytes) that zeroizes on drop
99#[derive(Clone, Zeroize, ZeroizeOnDrop, Default)]
100pub struct Nonce96(pub(crate) [u8; 12]);
101
102impl Nonce96 {
103    /// Create a new nonce from a 12-byte slice
104    pub fn from_slice(bytes: &[u8]) -> Result<Self, KeyError> {
105        if bytes.len() != 12 {
106            return Err(KeyError::InvalidLength {
107                expected: 12,
108                got: bytes.len(),
109            });
110        }
111        let mut nonce = [0u8; 12];
112        nonce.copy_from_slice(bytes);
113        Ok(Nonce96(nonce))
114    }
115
116    /// Get a reference to the nonce bytes
117    pub fn as_slice(&self) -> &[u8] {
118        &self.0
119    }
120
121    /// Get a mutable reference to the nonce bytes
122    pub fn as_mut_slice(&mut self) -> &mut [u8] {
123        &mut self.0
124    }
125}
126
127/// EC private key that zeroizes on drop (for NanoTDF)
128#[cfg(feature = "kem-ec")]
129#[derive(Clone, Zeroize, ZeroizeOnDrop)]
130pub struct EcPrivateKey(pub(crate) Zeroizing<Vec<u8>>);
131
132#[cfg(feature = "kem-ec")]
133impl EcPrivateKey {
134    /// Create from P-256 secret key
135    pub fn from_p256(key: &p256::SecretKey) -> Self {
136        use p256::pkcs8::EncodePrivateKey;
137        let der = key.to_pkcs8_der().expect("Failed to encode key");
138        EcPrivateKey(Zeroizing::new(der.to_bytes().to_vec()))
139    }
140
141    /// Get the bytes
142    pub fn as_bytes(&self) -> &[u8] {
143        &self.0
144    }
145}
146
147/// Key-related errors
148#[derive(Debug, thiserror::Error)]
149pub enum KeyError {
150    #[error("Invalid key length: expected {expected}, got {got}")]
151    InvalidLength { expected: usize, got: usize },
152
153    #[error("Key generation failed")]
154    GenerationFailed,
155}