use core::mem::size_of;
use zerocopy::{AsBytes, FromBytes};
use zeroize::Zeroize;
#[cfg(all(feature = "dalek", not(feature = "force_sodium")))]
use crate::dalek::auth;
#[cfg(all(
feature = "sodium",
any(feature = "force_sodium", not(feature = "dalek"))
))]
use crate::sodium::auth;
#[derive(AsBytes, Clone, Debug, PartialEq, Zeroize)]
#[repr(C)]
#[zeroize(drop)]
pub struct NetworkKey(pub [u8; 32]); impl NetworkKey {
pub const SIZE: usize = size_of::<Self>();
pub const SSB_MAIN_NET: NetworkKey = NetworkKey([
0xd4, 0xa1, 0xcb, 0x88, 0xa6, 0x6f, 0x02, 0xf8, 0xdb, 0x63, 0x5c, 0xe2, 0x64, 0x41, 0xcc,
0x5d, 0xac, 0x1b, 0x08, 0x42, 0x0c, 0xea, 0xac, 0x23, 0x08, 0x39, 0xb7, 0x55, 0x84, 0x5a,
0x9f, 0xfb,
]);
pub fn from_slice(s: &[u8]) -> Option<Self> {
if s.len() == Self::SIZE {
let mut out = Self([0; Self::SIZE]);
out.0.copy_from_slice(s);
Some(out)
} else {
None
}
}
#[cfg(feature = "rand")]
pub fn generate_with_rng<R>(r: &mut R) -> NetworkKey
where
R: rand::CryptoRng + rand::RngCore,
{
let mut buf = [0; NetworkKey::SIZE];
r.fill_bytes(&mut buf);
NetworkKey(buf)
}
#[cfg(feature = "b64")]
pub fn from_base64(s: &str) -> Option<Self> {
let mut buf = [0; Self::SIZE];
if crate::b64::decode(s, &mut buf, None) {
Some(Self(buf))
} else {
None
}
}
}
#[cfg(any(feature = "sodium", feature = "dalek"))]
impl NetworkKey {
pub fn authenticate(&self, b: &[u8]) -> NetworkAuth {
auth::authenticate(self, b)
}
pub fn verify(&self, auth: &NetworkAuth, b: &[u8]) -> bool {
auth::verify(self, auth, b)
}
#[cfg(all(feature = "getrandom", not(feature = "sodium")))]
pub fn generate() -> NetworkKey {
NetworkKey::generate_with_rng(&mut rand::rngs::OsRng {})
}
#[allow(missing_docs)]
#[cfg(feature = "sodium")]
pub fn generate() -> NetworkKey {
crate::sodium::auth::generate_key()
}
}
#[derive(AsBytes, FromBytes)]
#[repr(C)]
pub struct NetworkAuth(pub [u8; 32]);
impl NetworkAuth {
pub const SIZE: usize = size_of::<Self>();
}