1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
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>();
}