network_protocol/utils/
crypto.rs

1use chacha20poly1305::{
2    // OsRng and generic_array::GenericArray are unused
3    aead::{Aead, KeyInit}, 
4    XChaCha20Poly1305, Key, XNonce,
5};
6use getrandom::fill;
7
8use crate::error::{Result, ProtocolError};
9
10
11pub struct Crypto {
12    cipher: XChaCha20Poly1305,
13}
14
15impl Crypto {
16    pub fn new(key_bytes: &[u8; 32]) -> Self {
17        let key = Key::from_slice(key_bytes);
18        let cipher = XChaCha20Poly1305::new(key);
19        Self { cipher }
20    }
21
22    pub fn encrypt(&self, plaintext: &[u8], nonce: &[u8; 24]) -> Result<Vec<u8>> {
23        let nonce = XNonce::from_slice(nonce);
24        self.cipher.encrypt(nonce, plaintext)
25            .map_err(|_| ProtocolError::EncryptionFailure)
26    }
27
28    pub fn decrypt(&self, ciphertext: &[u8], nonce: &[u8; 24]) -> Result<Vec<u8>> {
29        let nonce = XNonce::from_slice(nonce);
30        self.cipher.decrypt(nonce, ciphertext)
31            .map_err(|_| ProtocolError::DecryptionFailure)
32    }
33
34    /// Generates a secure random 24-byte nonce
35    pub fn generate_nonce() -> [u8; 24] {
36        let mut nonce = [0u8; 24];
37        fill(&mut nonce).expect("Failed to fill nonce");
38        nonce
39    }
40}