1use zeroize::{Zeroize, ZeroizeOnDrop};
7
8#[cfg(feature = "kem-ec")]
9use zeroize::Zeroizing;
10
11#[derive(Clone, Zeroize, ZeroizeOnDrop)]
13pub struct AesKey(pub(crate) [u8; 32]);
14
15impl AesKey {
16 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 pub fn as_slice(&self) -> &[u8] {
31 &self.0
32 }
33
34 pub fn as_mut_slice(&mut self) -> &mut [u8] {
36 &mut self.0
37 }
38}
39
40#[derive(Clone, Zeroize, ZeroizeOnDrop)]
42pub struct PolicyKey(pub(crate) [u8; 32]);
43
44impl PolicyKey {
45 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 pub fn as_slice(&self) -> &[u8] {
60 &self.0
61 }
62
63 pub fn as_mut_slice(&mut self) -> &mut [u8] {
65 &mut self.0
66 }
67}
68
69#[derive(Clone, Zeroize, ZeroizeOnDrop)]
71pub struct PayloadKey(pub(crate) [u8; 32]);
72
73impl PayloadKey {
74 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 pub fn as_slice(&self) -> &[u8] {
89 &self.0
90 }
91
92 pub fn as_mut_slice(&mut self) -> &mut [u8] {
94 &mut self.0
95 }
96}
97
98#[derive(Clone, Zeroize, ZeroizeOnDrop, Default)]
100pub struct Nonce96(pub(crate) [u8; 12]);
101
102impl Nonce96 {
103 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 pub fn as_slice(&self) -> &[u8] {
118 &self.0
119 }
120
121 pub fn as_mut_slice(&mut self) -> &mut [u8] {
123 &mut self.0
124 }
125}
126
127#[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 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 pub fn as_bytes(&self) -> &[u8] {
143 &self.0
144 }
145}
146
147#[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}