ssb_crypto/
auth.rs

1use core::mem::size_of;
2use zerocopy::{AsBytes, FromBytes};
3use zeroize::Zeroize;
4
5#[cfg(all(feature = "dalek", not(feature = "force_sodium")))]
6use crate::dalek::auth;
7#[cfg(all(
8    feature = "sodium",
9    any(feature = "force_sodium", not(feature = "dalek"))
10))]
11use crate::sodium::auth;
12
13/// The network key, or network identifier, used during the secret handshake to prove
14/// that both parties are participating in the same ssb network.
15///
16/// The main ssb network uses a publicly-known key, which is
17/// available as `NetworkKey::SSB_MAIN_NET`.
18///
19/// This is an [HMAC](https://en.wikipedia.org/wiki/HMAC) key;
20/// specifically HMAC-SHA-512-256.
21#[derive(AsBytes, Clone, Debug, PartialEq, Zeroize)]
22#[repr(C)]
23#[zeroize(drop)]
24pub struct NetworkKey(pub [u8; 32]); // auth::hmacsha512256::Key
25impl NetworkKey {
26    /// The size of a NetworkKey, in bytes (32).
27    pub const SIZE: usize = size_of::<Self>();
28
29    /// The NetworkKey for the primary ssb network.
30    pub const SSB_MAIN_NET: NetworkKey = NetworkKey([
31        0xd4, 0xa1, 0xcb, 0x88, 0xa6, 0x6f, 0x02, 0xf8, 0xdb, 0x63, 0x5c, 0xe2, 0x64, 0x41, 0xcc,
32        0x5d, 0xac, 0x1b, 0x08, 0x42, 0x0c, 0xea, 0xac, 0x23, 0x08, 0x39, 0xb7, 0x55, 0x84, 0x5a,
33        0x9f, 0xfb,
34    ]);
35
36    /// Deserialize from a slice of bytes.
37    /// Returns `None` if the slice length isn't 32.
38    pub fn from_slice(s: &[u8]) -> Option<Self> {
39        if s.len() == Self::SIZE {
40            let mut out = Self([0; Self::SIZE]);
41            out.0.copy_from_slice(s);
42            Some(out)
43        } else {
44            None
45        }
46    }
47
48    /// Generate a random network key using the given cryptographically-secure
49    /// random number generator.
50    #[cfg(feature = "rand")]
51    pub fn generate_with_rng<R>(r: &mut R) -> NetworkKey
52    where
53        R: rand::CryptoRng + rand::RngCore,
54    {
55        let mut buf = [0; NetworkKey::SIZE];
56        r.fill_bytes(&mut buf);
57        NetworkKey(buf)
58    }
59
60    /// Deserialize from the base-64 representation.
61    #[cfg(feature = "b64")]
62    pub fn from_base64(s: &str) -> Option<Self> {
63        let mut buf = [0; Self::SIZE];
64        if crate::b64::decode(s, &mut buf, None) {
65            Some(Self(buf))
66        } else {
67            None
68        }
69    }
70}
71
72#[cfg(any(feature = "sodium", feature = "dalek"))]
73impl NetworkKey {
74    /// Generate an authentication code for the given byte slice.
75    ///
76    /// # Examples
77    /// ```
78    /// use ssb_crypto::NetworkKey;
79    /// let netkey = NetworkKey::SSB_MAIN_NET;
80    /// let bytes = [1, 2, 3, 4];
81    /// let auth = netkey.authenticate(&bytes);
82    /// assert!(netkey.verify(&auth, &bytes));
83    /// ```
84    pub fn authenticate(&self, b: &[u8]) -> NetworkAuth {
85        auth::authenticate(self, b)
86    }
87
88    /// Verify that an authentication code was generated
89    /// by this key, given the same byte slice.
90    pub fn verify(&self, auth: &NetworkAuth, b: &[u8]) -> bool {
91        auth::verify(self, auth, b)
92    }
93
94    /// Generate a random network key.
95    ///
96    /// # Examples
97    ///
98    /// ```rust
99    /// use ssb_crypto::NetworkKey;
100    /// let key = NetworkKey::generate();
101    /// assert_ne!(key, NetworkKey::SSB_MAIN_NET);
102    /// ```
103    #[cfg(all(feature = "getrandom", not(feature = "sodium")))]
104    pub fn generate() -> NetworkKey {
105        NetworkKey::generate_with_rng(&mut rand::rngs::OsRng {})
106    }
107
108    #[allow(missing_docs)]
109    #[cfg(feature = "sodium")]
110    pub fn generate() -> NetworkKey {
111        crate::sodium::auth::generate_key()
112    }
113}
114
115// auth::hmacsha512256::Tag
116/// An authentication code, produced by [`NetworkKey::authenticate`]
117/// and verified by [`NetworkKey::verify`].
118///
119/// [`NetworkKey::authenticate`]: ./struct.NetworkKey.html#method.authenticate
120/// [`NetworkKey::verify`]: ./struct.NetworkKey.html#method.verify
121#[derive(AsBytes, FromBytes)]
122#[repr(C)]
123pub struct NetworkAuth(pub [u8; 32]);
124impl NetworkAuth {
125    /// The size in bytes of a NetworkAuth (32).
126    pub const SIZE: usize = size_of::<Self>();
127}