1use base64::Engine;
2use zeroize::Zeroize;
3
4const KEY_SIZE: usize = 32;
5
6#[derive(Clone)]
8pub struct SyncKey([u8; KEY_SIZE]);
9
10impl SyncKey {
11 pub fn generate() -> Self {
13 use rand::RngCore;
14 let mut key = [0u8; KEY_SIZE];
15 rand::thread_rng().fill_bytes(&mut key);
16 Self(key)
17 }
18
19 pub fn from_bytes(bytes: [u8; KEY_SIZE]) -> Self {
21 Self(bytes)
22 }
23
24 pub fn from_base64(s: &str) -> Result<Self, SyncKeyError> {
26 let bytes = base64::engine::general_purpose::STANDARD
27 .decode(s)
28 .map_err(|e| SyncKeyError(e.to_string()))?;
29 if bytes.len() != KEY_SIZE {
30 return Err(SyncKeyError(format!(
31 "expected {} bytes, got {}",
32 KEY_SIZE,
33 bytes.len()
34 )));
35 }
36 let mut arr = [0u8; KEY_SIZE];
37 arr.copy_from_slice(&bytes);
38 Ok(Self(arr))
39 }
40
41 pub fn to_base64(&self) -> String {
43 base64::engine::general_purpose::STANDARD.encode(self.0)
44 }
45
46 pub fn as_bytes(&self) -> &[u8; KEY_SIZE] {
48 &self.0
49 }
50}
51
52impl Drop for SyncKey {
53 fn drop(&mut self) {
54 self.0.zeroize();
55 }
56}
57
58impl std::fmt::Debug for SyncKey {
59 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60 f.write_str("SyncKey([REDACTED])")
61 }
62}
63
64impl std::fmt::Display for SyncKey {
65 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66 f.write_str(&self.to_base64())
67 }
68}
69
70#[derive(Debug, Clone)]
72pub struct SyncKeyError(pub String);
73
74impl std::fmt::Display for SyncKeyError {
75 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76 write!(f, "invalid sync key: {}", self.0)
77 }
78}
79
80impl std::error::Error for SyncKeyError {}
81
82#[cfg(test)]
83#[path = "sync_key_tests.rs"]
84mod tests;