smart_locker/utils/config.rs
1use aes_gcm::aead::consts::U12;
2use aes_gcm::aead::KeyInit;
3use aes_gcm::{Aes256Gcm, Key, Nonce};
4use flate2::write::GzEncoder;
5use flate2::Compression;
6
7pub const SIGNATURE: &[u8; 8] = b"SMARTLKR"; // Signature fixe pour identifier le format
8pub const FORMAT_VERSION: u8 = 1; // Version actuelle du format
9pub const NONCE_SIZE: usize = 12; // Taille du nonce (12 octets pour AES-GCM)
10pub const KEY_SIZE: usize = 32; // Taille de la clé symétrique (32 octets pour AES-256)
11
12/// Configuration structure for encryption settings.
13/// This structure defines the parameters used for AES-GCM encryption,
14/// including the signature, format version, nonce size, key size, and compression settings.
15pub struct EncryptionConfig {
16 /// Fixed signature to identify the format.
17 pub signature: &'static [u8; 8],
18 /// Current version of the format.
19 pub format_version: u8,
20 /// Size of the nonce (12 bytes for AES-GCM).
21 pub nonce_size: usize,
22 /// Size of the symmetric key (32 bytes for AES-256).
23 pub key_size: usize,
24 /// Compression level for Gzip.
25 pub compression: Compression,
26}
27
28impl Default for EncryptionConfig {
29 fn default() -> Self {
30 Self::new()
31 }
32}
33
34impl EncryptionConfig {
35 /// Creates a new instance of the encryption configuration with default values.
36 pub fn new() -> Self {
37 Self {
38 signature: SIGNATURE,
39 format_version: FORMAT_VERSION,
40 nonce_size: NONCE_SIZE,
41 key_size: KEY_SIZE,
42 compression: Compression::default(),
43 }
44 }
45
46 /// Initializes the AES-GCM cipher with the provided key.
47 ///
48 /// # Arguments
49 /// * `key_data` - A byte slice containing the encryption key.
50 ///
51 /// # Returns
52 /// * `Ok(Aes256Gcm)` - The initialized AES-GCM cipher.
53 /// * `Err(String)` - An error message if the key size is invalid.
54 pub fn init_cipher(&self, key_data: &[u8]) -> Result<Aes256Gcm, String> {
55 if key_data.len() != self.key_size {
56 return Err(format!(
57 "Invalid key size: expected {} bytes, got {} bytes",
58 self.key_size,
59 key_data.len()
60 ));
61 }
62 let key = Key::<Aes256Gcm>::from_slice(key_data);
63 Ok(Aes256Gcm::new(key))
64 }
65
66 /// Generates a random nonce for AES-GCM encryption.
67 ///
68 /// # Returns
69 /// * `Nonce<U12>` - A randomly generated nonce of 12 bytes.
70 pub fn generate_nonce(&self) -> Nonce<U12> {
71 let random_bytes = rand::random::<[u8; NONCE_SIZE]>();
72 *Nonce::<U12>::from_slice(&random_bytes)
73 }
74
75 /// Initializes a Gzip compressor with the specified compression level.
76 ///
77 /// # Returns
78 /// * `GzEncoder<Vec<u8>>` - A Gzip encoder for compressing data.
79 pub fn init_compressor(&self) -> GzEncoder<Vec<u8>> {
80 GzEncoder::new(Vec::new(), self.compression)
81 }
82}