Skip to main content

Mountain/IPC/Enhanced/SecureMessageChannel/
EncryptionKey.rs

1
2//! Wrapper around `ring::aead::LessSafeKey` plus metadata -
3//! creation timestamp, random key id, and a usage counter the
4//! channel bumps on each encrypt. Private constructors are
5//! exposed via `pub(super)` so the channel can manage rotation
6//! while keeping callers out of the raw key material.
7
8use std::time::{Duration, SystemTime};
9
10use ring::{
11	aead::{AES_256_GCM, LessSafeKey, UnboundKey},
12	rand::{SecureRandom, SystemRandom},
13};
14
15#[derive(Debug, Clone)]
16pub struct Struct {
17	pub(super) key:LessSafeKey,
18
19	pub(super) created_at:SystemTime,
20
21	pub(super) key_id:String,
22
23	pub(super) usage_count:usize,
24}
25
26impl Struct {
27	pub(super) fn new(key_bytes:&[u8]) -> Result<Self, String> {
28		let unbound_key =
29			UnboundKey::new(&AES_256_GCM, key_bytes).map_err(|e| format!("Failed to create unbound key: {}", e))?;
30
31		Ok(Self {
32			key:LessSafeKey::new(unbound_key),
33			created_at:SystemTime::now(),
34			key_id:Self::generate_key_id(),
35			usage_count:0,
36		})
37	}
38
39	fn generate_key_id() -> String {
40		let rng = SystemRandom::new();
41
42		let mut id_bytes = [0u8; 8];
43
44		rng.fill(&mut id_bytes).unwrap();
45
46		hex::encode(id_bytes)
47	}
48
49	pub(super) fn is_expired(&self, rotation_interval:Duration) -> bool {
50		self.created_at.elapsed().unwrap_or_default() > rotation_interval
51	}
52
53	pub(super) fn increment_usage(&mut self) { self.usage_count += 1; }
54}