interplane.Get Omega
Read in your language

open-humanity

Privacy-first peer assistance network for sovereign autonomous agents

Brought by drakestapleton

branch main Branches Tags History

open-humanity / crates / beacon-core / src / crypto.rs

186 lines · 5363 bytes Raw Blame History
1//! Cryptographic primitives for Open Humanity nanobeacons and capsules.
2//!
3//! Provides Ed25519 node authentication and X25519-ChaCha20-Poly1305
4//! end-to-end authenticated payload encryption.
5
6use crate::schema::BeaconError;
7use chacha20poly1305::aead::{Aead, KeyInit};
8use chacha20poly1305::{ChaCha20Poly1305, Key, Nonce};
9use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
10use rand::rngs::OsRng;
11use rand::RngCore;
12use std::collections::HashSet;
13use uuid::Uuid;
14use x25519_dalek::{PublicKey as X25519PublicKey, StaticSecret};
15
16pub const MAX_TIMESTAMP_DRIFT_SECS: u64 = 300;
17
18pub struct Keypair {
19 pub signing_key: SigningKey,
20 pub verifying_key: VerifyingKey,
21}
22
23impl Keypair {
24 pub fn generate() -> Self {
25 let signing_key = SigningKey::generate(&mut OsRng);
26 let verifying_key = signing_key.verifying_key();
27 Self {
28 signing_key,
29 verifying_key,
30 }
31 }
32
33 /// The key for a 32-byte seed. The same seed gives the same key on every run.
34 pub fn from_seed(seed: &[u8; 32]) -> Self {
35 let signing_key = SigningKey::from_bytes(seed);
36 let verifying_key = signing_key.verifying_key();
37 Self {
38 signing_key,
39 verifying_key,
40 }
41 }
42
43 /// The key for a seed written as 64 hex characters (white space around it is
44 /// ignored), or None when the text is anything else.
45 pub fn from_hex_seed(text: &str) -> Option<Self> {
46 let text = text.trim();
47 if text.len() != 64 || !text.bytes().all(|b| b.is_ascii_hexdigit()) {
48 return None;
49 }
50 let mut seed = [0u8; 32];
51 for (i, byte) in seed.iter_mut().enumerate() {
52 *byte = u8::from_str_radix(&text[2 * i..2 * i + 2], 16).ok()?;
53 }
54 Some(Self::from_seed(&seed))
55 }
56
57 pub fn pubkey_bytes(&self) -> [u8; 32] {
58 self.verifying_key.to_bytes()
59 }
60
61 pub fn sign(&self, message: &[u8]) -> [u8; 64] {
62 self.signing_key.sign(message).to_bytes()
63 }
64}
65
66pub fn verify_signature(
67 pubkey: &[u8; 32],
68 message: &[u8],
69 signature: &[u8; 64],
70) -> Result<(), BeaconError> {
71 let verifying_key = VerifyingKey::from_bytes(pubkey)
72 .map_err(|_| BeaconError::SignatureVerificationFailed)?;
73 let sig = Signature::from_bytes(signature);
74 verifying_key
75 .verify(message, &sig)
76 .map_err(|_| BeaconError::SignatureVerificationFailed)
77}
78
79pub struct EncryptedPayload {
80 pub ephemeral_pubkey: [u8; 32],
81 pub nonce: [u8; 12],
82 pub ciphertext: Vec<u8>,
83}
84
85pub fn encrypt_to_peer(
86 peer_x25519_pubkey: &[u8; 32],
87 plaintext: &[u8],
88) -> Result<EncryptedPayload, BeaconError> {
89 let ephemeral_secret = StaticSecret::random_from_rng(OsRng);
90 let ephemeral_pubkey = X25519PublicKey::from(&ephemeral_secret);
91
92 let peer_public = X25519PublicKey::from(*peer_x25519_pubkey);
93 let shared_secret = ephemeral_secret.diffie_hellman(&peer_public);
94
95 let key = Key::from_slice(shared_secret.as_bytes());
96 let cipher = ChaCha20Poly1305::new(key);
97
98 let mut nonce_bytes = [0u8; 12];
99 OsRng.fill_bytes(&mut nonce_bytes);
100 let nonce = Nonce::from_slice(&nonce_bytes);
101
102 let ciphertext = cipher
103 .encrypt(nonce, plaintext)
104 .map_err(|_| BeaconError::Serialization("Encryption failed".into()))?;
105
106 Ok(EncryptedPayload {
107 ephemeral_pubkey: *ephemeral_pubkey.as_bytes(),
108 nonce: nonce_bytes,
109 ciphertext,
110 })
111}
112
113pub fn decrypt_from_peer(
114 my_x25519_secret: &StaticSecret,
115 sender_ephemeral_pubkey: &[u8; 32],
116 nonce: &[u8; 12],
117 ciphertext: &[u8],
118) -> Result<Vec<u8>, BeaconError> {
119 let sender_public = X25519PublicKey::from(*sender_ephemeral_pubkey);
120 let shared_secret = my_x25519_secret.diffie_hellman(&sender_public);
121
122 let key = Key::from_slice(shared_secret.as_bytes());
123 let cipher = ChaCha20Poly1305::new(key);
124 let nonce = Nonce::from_slice(nonce);
125
126 cipher
127 .decrypt(nonce, ciphertext)
128 .map_err(|_| BeaconError::DecryptionFailed)
129}
130
131pub fn verify_timestamp_drift(
132 timestamp: u64,
133 current_time: u64,
134 max_drift_secs: u64,
135) -> Result<(), BeaconError> {
136 let diff = if timestamp >= current_time {
137 timestamp - current_time
138 } else {
139 current_time - timestamp
140 };
141 if diff > max_drift_secs {
142 return Err(BeaconError::TimestampDrift {
143 drift_secs: diff,
144 max_allowed: max_drift_secs,
145 });
146 }
147 Ok(())
148}
149
150#[derive(Debug, Clone)]
151pub struct ReplayProtector {
152 seen: HashSet<Uuid>,
153 max_capacity: usize,
154}
155
156impl ReplayProtector {
157 pub fn new(max_capacity: usize) -> Self {
158 Self {
159 seen: HashSet::new(),
160 max_capacity,
161 }
162 }
163
164 pub fn check_and_record(&mut self, packet_id: &Uuid) -> Result<(), BeaconError> {
165 if self.seen.contains(packet_id) {
166 return Err(BeaconError::ReplayDetected(*packet_id));
167 }
168 if self.seen.len() >= self.max_capacity {
169 self.seen.clear();
170 }
171 self.seen.insert(*packet_id);
172 Ok(())
173 }
174
175 pub fn is_seen(&self, packet_id: &Uuid) -> bool {
176 self.seen.contains(packet_id)
177 }
178
179 pub fn len(&self) -> usize {
180 self.seen.len()
181 }
182
183 pub fn is_empty(&self) -> bool {
184 self.seen.is_empty()
185 }
186}