diff --git a/wg-event-gen/src/model.rs b/wg-event-gen/src/model.rs index 9c87f64..b263a4a 100644 --- a/wg-event-gen/src/model.rs +++ b/wg-event-gen/src/model.rs @@ -1,4 +1,4 @@ -use base64::decode; +use base64::{decode, encode}; use std::error::Error; use std::io; use std::net::{IpAddr, SocketAddr}; @@ -11,8 +11,13 @@ pub enum ECCKey { PrivateKey([u8; 32]), } -impl ECCKey { - pub fn from_base64>(key: I) -> io::Result { +pub trait Base64Backed { + fn from_bytes(bytes: [u8; 32]) -> Self; + fn bytes(&self) -> &[u8; 32]; + fn from_base64>(key: I) -> io::Result + where + Self: Sized, + { let key = match decode(key.as_ref()) { Ok(key) => key, _ => { @@ -29,12 +34,45 @@ impl ECCKey { return Err(io::Error::new(io::ErrorKind::Other, "Mismatched key size")); } bytes.copy_from_slice(&key); - Ok(ECCKey::PublicKey(bytes)) + Ok(Self::from_bytes(bytes)) + } + + fn as_base64(&self) -> io::Result { + Ok(encode(self.bytes())) + } +} + +impl Base64Backed for ECCKey { + fn bytes(&self) -> &[u8; 32] { + match self { + ECCKey::PublicKey(bytes) => &bytes, + ECCKey::PrivateKey(bytes) => &bytes, + } + } + + fn from_bytes(bytes: [u8; 32]) -> ECCKey { + ECCKey::PublicKey(bytes) + } +} + +impl ECCKey { + pub fn extract_public_key(&self) -> Option { + //TODO: Determine whether Self is a private key and only the return public part + Some(self.clone()) } } #[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)] -struct SharedKey([u8; 32]); +pub struct SharedKey([u8; 32]); + +impl Base64Backed for SharedKey { + fn bytes(&self) -> &[u8; 32] { + &self.0 + } + fn from_bytes(bytes: [u8; 32]) -> SharedKey { + SharedKey(bytes) + } +} #[derive(Debug, Builder, PartialEq, Eq, Hash, Clone)] pub struct Peer {