1use std::fmt;
21use std::time::{Duration, SystemTime, UNIX_EPOCH};
22
23use rsa::pkcs8::{DecodePrivateKey, DecodePublicKey};
24use rsa::traits::PublicKeyParts;
25use rsa::{Pkcs1v15Sign, RsaPrivateKey, RsaPublicKey};
26use sha2::{Digest, Sha256};
27use thiserror::Error;
28use uuid::Uuid;
29
30const SHA256_PREFIX: [u8; 19] = [
32 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
33 0x00, 0x04, 0x20,
34];
35
36#[derive(Debug, Error)]
38#[non_exhaustive]
39pub enum ChatKeyError {
40 #[error("invalid private key: {0}")]
42 InvalidPrivateKey(String),
43 #[error("invalid public key: {0}")]
45 InvalidPublicKey(String),
46 #[error("the public key does not match the private key")]
48 KeyMismatch,
49 #[error("signing failed: {0}")]
51 Sign(#[source] rsa::Error),
52}
53
54#[derive(Clone)]
59pub struct ProfileKeys {
60 private: RsaPrivateKey,
61 public_der: Vec<u8>,
62 key_signature: Vec<u8>,
63 expires_at: SystemTime,
64 refreshed_after: SystemTime,
65}
66
67impl ProfileKeys {
68 pub fn from_der(
72 private_pkcs8: &[u8],
73 public_spki: &[u8],
74 key_signature: Vec<u8>,
75 expires_at: SystemTime,
76 refreshed_after: SystemTime,
77 ) -> Result<Self, ChatKeyError> {
78 let private = RsaPrivateKey::from_pkcs8_der(private_pkcs8)
79 .map_err(|e| ChatKeyError::InvalidPrivateKey(e.to_string()))?;
80 let public = RsaPublicKey::from_public_key_der(public_spki)
81 .map_err(|e| ChatKeyError::InvalidPublicKey(e.to_string()))?;
82 if public.n() != private.n() || public.e() != private.e() {
83 return Err(ChatKeyError::KeyMismatch);
84 }
85 Ok(Self {
86 private,
87 public_der: public_spki.to_vec(),
88 key_signature,
89 expires_at,
90 refreshed_after,
91 })
92 }
93
94 #[must_use]
96 pub fn public_key_der(&self) -> &[u8] {
97 &self.public_der
98 }
99
100 #[must_use]
102 pub fn key_signature(&self) -> &[u8] {
103 &self.key_signature
104 }
105
106 #[must_use]
108 pub fn expires_at(&self) -> SystemTime {
109 self.expires_at
110 }
111
112 #[must_use]
114 pub fn expires_at_millis(&self) -> i64 {
115 millis(self.expires_at)
116 }
117
118 #[must_use]
120 pub fn refreshed_after(&self) -> SystemTime {
121 self.refreshed_after
122 }
123
124 #[must_use]
126 pub fn due_refresh(&self) -> bool {
127 SystemTime::now() > self.refreshed_after
128 }
129
130 #[must_use]
132 pub fn expires_within(&self, margin: Duration) -> bool {
133 SystemTime::now()
134 .checked_add(margin)
135 .is_none_or(|t| t >= self.expires_at)
136 }
137
138 #[must_use]
140 pub fn signature_len(&self) -> usize {
141 self.private.size()
142 }
143
144 fn sign_with(&self, feed: impl FnOnce(&mut Sha256)) -> Result<Vec<u8>, ChatKeyError> {
146 let mut h = Sha256::new();
147 feed(&mut h);
148 let digest = h.finalize();
149 let scheme = Pkcs1v15Sign {
150 hash_len: Some(32),
151 prefix: Box::new(SHA256_PREFIX),
152 };
153 self.private
154 .sign(scheme, &digest[..])
155 .map_err(ChatKeyError::Sign)
156 }
157
158 pub fn sign(&self, data: &[u8]) -> Result<Vec<u8>, ChatKeyError> {
160 self.sign_with(|h| h.update(data))
161 }
162}
163
164impl fmt::Debug for ProfileKeys {
165 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166 f.debug_struct("ProfileKeys")
167 .field("bits", &(self.private.size() * 8))
168 .field("expires_at_ms", &self.expires_at_millis())
169 .finish_non_exhaustive()
170 }
171}
172
173fn millis(t: SystemTime) -> i64 {
174 match t.duration_since(UNIX_EPOCH) {
175 Ok(d) => i64::try_from(d.as_millis()).unwrap_or(i64::MAX),
176 Err(e) => -i64::try_from(e.duration().as_millis()).unwrap_or(i64::MAX),
177 }
178}
179
180#[derive(Debug, Clone)]
183pub struct SignedMessageChain {
184 profile_id: Uuid,
185 session_id: Uuid,
186 next: Option<i32>,
188}
189
190impl SignedMessageChain {
191 #[must_use]
193 pub fn new(profile_id: Uuid, session_id: Uuid) -> Self {
194 Self {
195 profile_id,
196 session_id,
197 next: Some(0),
198 }
199 }
200
201 #[must_use]
203 pub fn session_id(&self) -> Uuid {
204 self.session_id
205 }
206
207 #[must_use]
209 pub fn next_index(&self) -> Option<i32> {
210 self.next
211 }
212
213 pub fn sign<'a>(
218 &mut self,
219 keys: &ProfileKeys,
220 content: &str,
221 timestamp_millis: i64,
222 salt: i64,
223 last_seen: impl ExactSizeIterator<Item = &'a [u8]>,
224 ) -> Result<Option<Vec<u8>>, ChatKeyError> {
225 let Some(index) = self.next else {
226 return Ok(None);
227 };
228 self.next = index.checked_add(1);
229 let (profile, session) = (self.profile_id, self.session_id);
230 keys.sign_with(|h| {
231 h.update(1i32.to_be_bytes());
232 h.update(profile.as_bytes());
233 h.update(session.as_bytes());
234 h.update(index.to_be_bytes());
235 h.update(salt.to_be_bytes());
236 h.update(timestamp_millis.div_euclid(1000).to_be_bytes());
238 let bytes = content.as_bytes();
239 h.update((bytes.len() as i32).to_be_bytes());
240 h.update(bytes);
241 h.update((last_seen.len() as i32).to_be_bytes());
242 for sig in last_seen {
243 h.update(sig);
244 }
245 })
246 .map(Some)
247 }
248}
249
250#[must_use]
254pub fn profile_key_payload(
255 profile_id: Uuid,
256 expires_at_millis: i64,
257 public_spki: &[u8],
258) -> Vec<u8> {
259 let mut v = Vec::with_capacity(24 + public_spki.len());
260 v.extend_from_slice(profile_id.as_bytes());
261 v.extend_from_slice(&expires_at_millis.to_be_bytes());
262 v.extend_from_slice(public_spki);
263 v
264}
265
266pub fn pem_body(pem: &str) -> Option<Vec<u8>> {
269 let mut body = String::with_capacity(pem.len());
270 for line in pem.lines() {
271 let line = line.trim();
272 if line.starts_with("-----") || line.is_empty() {
273 continue;
274 }
275 body.push_str(line);
276 }
277 base64_decode(&body)
278}
279
280pub fn base64_decode(s: &str) -> Option<Vec<u8>> {
282 fn val(c: u8) -> Option<u32> {
283 Some(match c {
284 b'A'..=b'Z' => c - b'A',
285 b'a'..=b'z' => c - b'a' + 26,
286 b'0'..=b'9' => c - b'0' + 52,
287 b'+' => 62,
288 b'/' => 63,
289 _ => return None,
290 } as u32)
291 }
292 let s = s.trim_end_matches('=').as_bytes();
293 let mut out = Vec::with_capacity(s.len() * 3 / 4);
294 for chunk in s.chunks(4) {
295 let mut acc = 0u32;
296 for (i, &c) in chunk.iter().enumerate() {
297 acc |= val(c)? << (18 - 6 * i);
298 }
299 match chunk.len() {
300 4 => out.extend_from_slice(&[(acc >> 16) as u8, (acc >> 8) as u8, acc as u8]),
301 3 => out.extend_from_slice(&[(acc >> 16) as u8, (acc >> 8) as u8]),
302 2 => out.push((acc >> 16) as u8),
303 _ => return None,
304 }
305 }
306 Some(out)
307}
308
309#[cfg(test)]
310mod tests {
311 use super::*;
312
313 #[test]
314 fn base64_round_trips_known_values() {
315 assert_eq!(base64_decode("").unwrap(), b"");
316 assert_eq!(base64_decode("Zg==").unwrap(), b"f");
317 assert_eq!(base64_decode("Zm8").unwrap(), b"fo");
318 assert_eq!(base64_decode("Zm9vYmFy").unwrap(), b"foobar");
319 assert!(base64_decode("Zm9v!").is_none());
320 let pem = "-----BEGIN RSA PUBLIC KEY-----\nZm9v\nYmFy\n-----END RSA PUBLIC KEY-----\n";
321 assert_eq!(pem_body(pem).unwrap(), b"foobar");
322 }
323
324 #[test]
325 fn chain_stops_at_the_last_index() {
326 let mut c = SignedMessageChain::new(Uuid::nil(), Uuid::nil());
327 c.next = Some(i32::MAX);
328 assert_eq!(c.next_index(), Some(i32::MAX));
329 assert_eq!(i32::MAX.checked_add(1), None);
331 }
332}