1use core::fmt;
4
5#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
11pub struct SystemTitle(pub [u8; 8]);
12
13impl SystemTitle {
14 #[must_use]
16 pub const fn new(bytes: [u8; 8]) -> Self {
17 Self(bytes)
18 }
19
20 pub fn from_slice(bytes: &[u8]) -> crate::codec::Result<Self> {
22 let arr: [u8; 8] = bytes
23 .try_into()
24 .map_err(|_| crate::codec::Error::new(crate::codec::ErrorKind::InvalidLength, 0))?;
25 Ok(Self(arr))
26 }
27
28 #[must_use]
30 pub const fn as_bytes(&self) -> &[u8; 8] {
31 &self.0
32 }
33
34 #[must_use]
36 pub fn manufacturer(&self) -> Option<&str> {
37 core::str::from_utf8(&self.0[..3]).ok().filter(|s| s.is_ascii())
38 }
39}
40
41impl fmt::Debug for SystemTitle {
42 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43 f.write_str("SystemTitle(")?;
44 for b in &self.0 {
45 write!(f, "{b:02X}")?;
46 }
47 f.write_str(")")
48 }
49}
50
51impl fmt::Display for SystemTitle {
52 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53 for b in &self.0 {
54 write!(f, "{b:02X}")?;
55 }
56 Ok(())
57 }
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
62pub enum KeyUsage {
63 GlobalUnicastEncryption,
65 GlobalBroadcastEncryption,
67 Authentication,
69 KeyEncrypting,
71 Dedicated,
73}
74
75impl KeyUsage {
76 #[must_use]
84 pub const fn key_id(self) -> Option<u8> {
85 match self {
86 Self::GlobalUnicastEncryption => Some(0),
87 Self::GlobalBroadcastEncryption => Some(1),
88 Self::Authentication | Self::KeyEncrypting | Self::Dedicated => None,
89 }
90 }
91}
92
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub enum KeyRef<'a> {
99 Usage(KeyUsage),
101 Raw(&'a [u8]),
103}
104
105impl From<KeyUsage> for KeyRef<'_> {
106 fn from(u: KeyUsage) -> Self {
107 Self::Usage(u)
108 }
109}
110
111#[derive(Clone, PartialEq, Eq)]
128pub struct Key {
129 buf: [u8; Self::MAX_LEN],
130 len: u8,
131}
132
133impl Key {
134 pub const MAX_LEN: usize = 32;
136
137 #[must_use]
139 pub const fn new(bytes: [u8; 16]) -> Self {
140 let mut buf = [0u8; Self::MAX_LEN];
141 let mut i = 0;
142 while i < 16 {
143 buf[i] = bytes[i];
144 i += 1;
145 }
146 Self { buf, len: 16 }
147 }
148
149 #[must_use]
151 pub const fn new_256(bytes: [u8; 32]) -> Self {
152 Self { buf: bytes, len: 32 }
153 }
154
155 pub fn from_slice(bytes: &[u8]) -> crate::codec::Result<Self> {
163 if bytes.len() != 16 && bytes.len() != 32 {
164 return Err(crate::codec::Error::new(crate::codec::ErrorKind::InvalidLength, 0));
165 }
166 let mut buf = [0u8; Self::MAX_LEN];
167 buf.get_mut(..bytes.len())
168 .ok_or_else(|| crate::codec::Error::new(crate::codec::ErrorKind::InvalidLength, 0))?
169 .copy_from_slice(bytes);
170 Ok(Self { buf, len: bytes.len() as u8 })
171 }
172
173 #[must_use]
176 pub fn expose(&self) -> &[u8] {
177 self.buf.get(..usize::from(self.len)).unwrap_or(&[])
178 }
179
180 #[must_use]
182 pub const fn len(&self) -> usize {
183 self.len as usize
184 }
185
186 #[must_use]
188 pub const fn is_empty(&self) -> bool {
189 false
190 }
191}
192
193impl fmt::Debug for Key {
194 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195 f.write_str("[REDACTED]")
196 }
197}
198
199#[cfg(feature = "crypto")]
200impl Drop for Key {
201 fn drop(&mut self) {
202 use zeroize::Zeroize;
203 self.buf.zeroize();
204 }
205}
206
207impl From<[u8; 16]> for Key {
208 fn from(v: [u8; 16]) -> Self {
209 Self::new(v)
210 }
211}
212
213impl From<[u8; 32]> for Key {
214 fn from(v: [u8; 32]) -> Self {
215 Self::new_256(v)
216 }
217}
218
219#[derive(Clone, PartialEq, Eq)]
225pub struct Secret {
226 buf: [u8; Self::MAX_LEN],
227 len: u8,
228}
229
230impl Secret {
231 pub const MAX_LEN: usize = 64;
233
234 pub fn new(bytes: &[u8]) -> crate::codec::Result<Self> {
240 if bytes.len() > Self::MAX_LEN {
241 return Err(crate::codec::Error::new(crate::codec::ErrorKind::InvalidLength, 0));
242 }
243 let mut buf = [0u8; Self::MAX_LEN];
244 buf[..bytes.len()].copy_from_slice(bytes);
245 Ok(Self { buf, len: bytes.len() as u8 })
246 }
247
248 #[must_use]
251 pub fn expose(&self) -> &[u8] {
252 &self.buf[..usize::from(self.len)]
253 }
254}
255
256impl fmt::Debug for Secret {
257 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258 f.write_str("[REDACTED]")
259 }
260}
261
262#[cfg(feature = "crypto")]
263impl Drop for Secret {
264 fn drop(&mut self) {
265 use zeroize::Zeroize;
266 self.buf.zeroize();
267 }
268}
269
270#[derive(Debug, Clone, Default)]
275pub struct KeyRing {
276 pub guek: Option<Key>,
278 pub gbek: Option<Key>,
280 pub gak: Option<Key>,
282 pub kek: Option<Key>,
284 pub dedicated: Option<Key>,
287}
288
289impl KeyRing {
290 #[must_use]
292 pub const fn new(guek: [u8; 16], gak: [u8; 16]) -> Self {
293 Self { guek: Some(Key::new(guek)), gak: Some(Key::new(gak)), gbek: None, kek: None, dedicated: None }
294 }
295
296 #[must_use]
298 pub const fn new_256(guek: [u8; 32], gak: [u8; 32]) -> Self {
299 Self {
300 guek: Some(Key::new_256(guek)),
301 gak: Some(Key::new_256(gak)),
302 gbek: None,
303 kek: None,
304 dedicated: None,
305 }
306 }
307
308 #[must_use]
310 pub fn get(&self, usage: KeyUsage) -> Option<&[u8]> {
311 let slot = match usage {
312 KeyUsage::GlobalUnicastEncryption => self.guek.as_ref(),
313 KeyUsage::GlobalBroadcastEncryption => self.gbek.as_ref(),
314 KeyUsage::Authentication => self.gak.as_ref(),
315 KeyUsage::KeyEncrypting => self.kek.as_ref(),
316 KeyUsage::Dedicated => self.dedicated.as_ref(),
317 };
318 slot.map(Key::expose)
319 }
320
321 pub fn set(&mut self, usage: KeyUsage, key: Key) {
323 match usage {
324 KeyUsage::GlobalUnicastEncryption => self.guek = Some(key),
325 KeyUsage::GlobalBroadcastEncryption => self.gbek = Some(key),
326 KeyUsage::Authentication => self.gak = Some(key),
327 KeyUsage::KeyEncrypting => self.kek = Some(key),
328 KeyUsage::Dedicated => self.dedicated = Some(key),
329 }
330 }
331
332 pub fn set_dedicated(&mut self, key: Key) {
334 self.dedicated = Some(key);
335 }
336
337 pub fn clear_dedicated(&mut self) {
340 self.dedicated = None;
341 }
342}
343
344#[must_use]
346pub const fn nonce(system_title: &SystemTitle, invocation_counter: u32) -> [u8; 12] {
347 let t = system_title.0;
348 let c = invocation_counter.to_be_bytes();
349 [t[0], t[1], t[2], t[3], t[4], t[5], t[6], t[7], c[0], c[1], c[2], c[3]]
350}
351
352#[cfg(test)]
353mod tests {
354 use super::*;
355
356 #[test]
361 fn only_the_two_ciphering_keys_have_a_key_id() {
362 assert_eq!(KeyUsage::GlobalUnicastEncryption.key_id(), Some(0));
363 assert_eq!(KeyUsage::GlobalBroadcastEncryption.key_id(), Some(1));
364 assert_eq!(KeyUsage::Authentication.key_id(), None);
365 assert_eq!(KeyUsage::KeyEncrypting.key_id(), None);
366 assert_eq!(KeyUsage::Dedicated.key_id(), None);
367 }
368
369 #[test]
370 fn a_nonce_is_the_title_then_the_counter() {
371 let st = SystemTitle::new([0x4D, 0x4D, 0x4D, 0x00, 0x00, 0xBC, 0x61, 0x4E]);
372 assert_eq!(
373 nonce(&st, 0x0000_0001),
374 [0x4D, 0x4D, 0x4D, 0x00, 0x00, 0xBC, 0x61, 0x4E, 0x00, 0x00, 0x00, 0x01]
375 );
376 }
377
378 #[test]
379 fn a_system_title_shows_its_manufacturer() {
380 let st = SystemTitle::new(*b"MMM\x00\x00\xbcaN");
381 assert_eq!(st.manufacturer(), Some("MMM"));
382 }
383
384 #[test]
385 fn a_secret_does_not_print_itself() {
386 #[cfg(feature = "std")]
387 {
388 use std::format;
389 let s = Key::new([0xAAu8; 16]);
390 assert_eq!(format!("{s:?}"), "[REDACTED]");
391 let ring = KeyRing::new([1; 16], [2; 16]);
392 let printed = format!("{ring:?}");
393 assert!(!printed.contains('1'), "no key bytes in a Debug rendering: {printed}");
394 }
395 }
396
397 #[test]
400 fn a_ring_holds_keys_of_both_suite_widths() {
401 let ring = KeyRing::new_256([7; 32], [8; 32]);
402 assert_eq!(ring.get(KeyUsage::GlobalUnicastEncryption).map(<[u8]>::len), Some(32));
403 let ring = KeyRing::new([7; 16], [8; 16]);
404 assert_eq!(ring.get(KeyUsage::Authentication).map(<[u8]>::len), Some(16));
405 assert!(Key::from_slice(&[0u8; 24]).is_err());
407 assert!(Key::from_slice(&[0u8; 32]).is_ok());
408 }
409
410 #[test]
411 fn a_dedicated_key_can_be_dropped_without_dropping_the_ring() {
412 let mut ring = KeyRing::new([1; 16], [2; 16]);
413 ring.set_dedicated(Key::new([3; 16]));
414 assert!(ring.get(KeyUsage::Dedicated).is_some());
415 ring.clear_dedicated();
416 assert!(ring.get(KeyUsage::Dedicated).is_none());
417 assert!(ring.get(KeyUsage::GlobalUnicastEncryption).is_some());
418 }
419}