use core::fmt;
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct SystemTitle(pub [u8; 8]);
impl SystemTitle {
#[must_use]
pub const fn new(bytes: [u8; 8]) -> Self {
Self(bytes)
}
pub fn from_slice(bytes: &[u8]) -> crate::codec::Result<Self> {
let arr: [u8; 8] = bytes
.try_into()
.map_err(|_| crate::codec::Error::new(crate::codec::ErrorKind::InvalidLength, 0))?;
Ok(Self(arr))
}
#[must_use]
pub const fn as_bytes(&self) -> &[u8; 8] {
&self.0
}
#[must_use]
pub fn manufacturer(&self) -> Option<&str> {
core::str::from_utf8(&self.0[..3]).ok().filter(|s| s.is_ascii())
}
}
impl fmt::Debug for SystemTitle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("SystemTitle(")?;
for b in &self.0 {
write!(f, "{b:02X}")?;
}
f.write_str(")")
}
}
impl fmt::Display for SystemTitle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for b in &self.0 {
write!(f, "{b:02X}")?;
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum KeyUsage {
GlobalUnicastEncryption,
GlobalBroadcastEncryption,
Authentication,
KeyEncrypting,
Dedicated,
}
impl KeyUsage {
#[must_use]
pub const fn key_id(self) -> Option<u8> {
match self {
Self::GlobalUnicastEncryption => Some(0),
Self::GlobalBroadcastEncryption => Some(1),
Self::Authentication | Self::KeyEncrypting | Self::Dedicated => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyRef<'a> {
Usage(KeyUsage),
Raw(&'a [u8]),
}
impl From<KeyUsage> for KeyRef<'_> {
fn from(u: KeyUsage) -> Self {
Self::Usage(u)
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct Key {
buf: [u8; Self::MAX_LEN],
len: u8,
}
impl Key {
pub const MAX_LEN: usize = 32;
#[must_use]
pub const fn new(bytes: [u8; 16]) -> Self {
let mut buf = [0u8; Self::MAX_LEN];
let mut i = 0;
while i < 16 {
buf[i] = bytes[i];
i += 1;
}
Self { buf, len: 16 }
}
#[must_use]
pub const fn new_256(bytes: [u8; 32]) -> Self {
Self { buf: bytes, len: 32 }
}
pub fn from_slice(bytes: &[u8]) -> crate::codec::Result<Self> {
if bytes.len() != 16 && bytes.len() != 32 {
return Err(crate::codec::Error::new(crate::codec::ErrorKind::InvalidLength, 0));
}
let mut buf = [0u8; Self::MAX_LEN];
buf.get_mut(..bytes.len())
.ok_or_else(|| crate::codec::Error::new(crate::codec::ErrorKind::InvalidLength, 0))?
.copy_from_slice(bytes);
Ok(Self { buf, len: bytes.len() as u8 })
}
#[must_use]
pub fn expose(&self) -> &[u8] {
self.buf.get(..usize::from(self.len)).unwrap_or(&[])
}
#[must_use]
pub const fn len(&self) -> usize {
self.len as usize
}
#[must_use]
pub const fn is_empty(&self) -> bool {
false
}
}
impl fmt::Debug for Key {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("[REDACTED]")
}
}
#[cfg(feature = "crypto")]
impl Drop for Key {
fn drop(&mut self) {
use zeroize::Zeroize;
self.buf.zeroize();
}
}
impl From<[u8; 16]> for Key {
fn from(v: [u8; 16]) -> Self {
Self::new(v)
}
}
impl From<[u8; 32]> for Key {
fn from(v: [u8; 32]) -> Self {
Self::new_256(v)
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct Secret {
buf: [u8; Self::MAX_LEN],
len: u8,
}
impl Secret {
pub const MAX_LEN: usize = 64;
pub fn new(bytes: &[u8]) -> crate::codec::Result<Self> {
if bytes.len() > Self::MAX_LEN {
return Err(crate::codec::Error::new(crate::codec::ErrorKind::InvalidLength, 0));
}
let mut buf = [0u8; Self::MAX_LEN];
buf[..bytes.len()].copy_from_slice(bytes);
Ok(Self { buf, len: bytes.len() as u8 })
}
#[must_use]
pub fn expose(&self) -> &[u8] {
&self.buf[..usize::from(self.len)]
}
}
impl fmt::Debug for Secret {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("[REDACTED]")
}
}
#[cfg(feature = "crypto")]
impl Drop for Secret {
fn drop(&mut self) {
use zeroize::Zeroize;
self.buf.zeroize();
}
}
#[derive(Debug, Clone, Default)]
pub struct KeyRing {
pub guek: Option<Key>,
pub gbek: Option<Key>,
pub gak: Option<Key>,
pub kek: Option<Key>,
pub dedicated: Option<Key>,
}
impl KeyRing {
#[must_use]
pub const fn new(guek: [u8; 16], gak: [u8; 16]) -> Self {
Self { guek: Some(Key::new(guek)), gak: Some(Key::new(gak)), gbek: None, kek: None, dedicated: None }
}
#[must_use]
pub const fn new_256(guek: [u8; 32], gak: [u8; 32]) -> Self {
Self {
guek: Some(Key::new_256(guek)),
gak: Some(Key::new_256(gak)),
gbek: None,
kek: None,
dedicated: None,
}
}
#[must_use]
pub fn get(&self, usage: KeyUsage) -> Option<&[u8]> {
let slot = match usage {
KeyUsage::GlobalUnicastEncryption => self.guek.as_ref(),
KeyUsage::GlobalBroadcastEncryption => self.gbek.as_ref(),
KeyUsage::Authentication => self.gak.as_ref(),
KeyUsage::KeyEncrypting => self.kek.as_ref(),
KeyUsage::Dedicated => self.dedicated.as_ref(),
};
slot.map(Key::expose)
}
pub fn set(&mut self, usage: KeyUsage, key: Key) {
match usage {
KeyUsage::GlobalUnicastEncryption => self.guek = Some(key),
KeyUsage::GlobalBroadcastEncryption => self.gbek = Some(key),
KeyUsage::Authentication => self.gak = Some(key),
KeyUsage::KeyEncrypting => self.kek = Some(key),
KeyUsage::Dedicated => self.dedicated = Some(key),
}
}
pub fn set_dedicated(&mut self, key: Key) {
self.dedicated = Some(key);
}
pub fn clear_dedicated(&mut self) {
self.dedicated = None;
}
}
#[must_use]
pub const fn nonce(system_title: &SystemTitle, invocation_counter: u32) -> [u8; 12] {
let t = system_title.0;
let c = invocation_counter.to_be_bytes();
[t[0], t[1], t[2], t[3], t[4], t[5], t[6], t[7], c[0], c[1], c[2], c[3]]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_the_two_ciphering_keys_have_a_key_id() {
assert_eq!(KeyUsage::GlobalUnicastEncryption.key_id(), Some(0));
assert_eq!(KeyUsage::GlobalBroadcastEncryption.key_id(), Some(1));
assert_eq!(KeyUsage::Authentication.key_id(), None);
assert_eq!(KeyUsage::KeyEncrypting.key_id(), None);
assert_eq!(KeyUsage::Dedicated.key_id(), None);
}
#[test]
fn a_nonce_is_the_title_then_the_counter() {
let st = SystemTitle::new([0x4D, 0x4D, 0x4D, 0x00, 0x00, 0xBC, 0x61, 0x4E]);
assert_eq!(
nonce(&st, 0x0000_0001),
[0x4D, 0x4D, 0x4D, 0x00, 0x00, 0xBC, 0x61, 0x4E, 0x00, 0x00, 0x00, 0x01]
);
}
#[test]
fn a_system_title_shows_its_manufacturer() {
let st = SystemTitle::new(*b"MMM\x00\x00\xbcaN");
assert_eq!(st.manufacturer(), Some("MMM"));
}
#[test]
fn a_secret_does_not_print_itself() {
#[cfg(feature = "std")]
{
use std::format;
let s = Key::new([0xAAu8; 16]);
assert_eq!(format!("{s:?}"), "[REDACTED]");
let ring = KeyRing::new([1; 16], [2; 16]);
let printed = format!("{ring:?}");
assert!(!printed.contains('1'), "no key bytes in a Debug rendering: {printed}");
}
}
#[test]
fn a_ring_holds_keys_of_both_suite_widths() {
let ring = KeyRing::new_256([7; 32], [8; 32]);
assert_eq!(ring.get(KeyUsage::GlobalUnicastEncryption).map(<[u8]>::len), Some(32));
let ring = KeyRing::new([7; 16], [8; 16]);
assert_eq!(ring.get(KeyUsage::Authentication).map(<[u8]>::len), Some(16));
assert!(Key::from_slice(&[0u8; 24]).is_err());
assert!(Key::from_slice(&[0u8; 32]).is_ok());
}
#[test]
fn a_dedicated_key_can_be_dropped_without_dropping_the_ring() {
let mut ring = KeyRing::new([1; 16], [2; 16]);
ring.set_dedicated(Key::new([3; 16]));
assert!(ring.get(KeyUsage::Dedicated).is_some());
ring.clear_dedicated();
assert!(ring.get(KeyUsage::Dedicated).is_none());
assert!(ring.get(KeyUsage::GlobalUnicastEncryption).is_some());
}
}