Skip to main content

rskit_encryption/
traits.rs

1//! Core encryption traits and types.
2
3use rskit_errors::AppResult;
4
5/// Supported encryption algorithms.
6#[non_exhaustive]
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum Algorithm {
9    /// AES-256-GCM (default, widely supported with hardware acceleration)
10    AesGcm,
11    /// ChaCha20-Poly1305 (modern, performant on CPUs without AES-NI)
12    ChaCha20Poly1305,
13}
14
15impl Algorithm {
16    /// Returns the algorithm name as a string.
17    pub fn name(&self) -> &'static str {
18        match self {
19            Self::AesGcm => "aes-256-gcm",
20            Self::ChaCha20Poly1305 => "chacha20-poly1305",
21        }
22    }
23
24    pub(crate) const fn id(self) -> u8 {
25        match self {
26            Self::AesGcm => 1,
27            Self::ChaCha20Poly1305 => 2,
28        }
29    }
30
31    pub(crate) fn from_id(id: u8) -> Option<Self> {
32        match id {
33            1 => Some(Self::AesGcm),
34            2 => Some(Self::ChaCha20Poly1305),
35            _ => None,
36        }
37    }
38}
39
40impl std::fmt::Display for Algorithm {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        f.write_str(self.name())
43    }
44}
45
46/// Trait for symmetric encryption and decryption operations.
47///
48/// Implementations are thread-safe and can be shared across async boundaries.
49pub trait Encryptor: Send + Sync {
50    /// Encrypts plaintext and returns base64-encoded ciphertext.
51    ///
52    /// The ciphertext includes a random nonce prepended to the encrypted data,
53    /// so each call to encrypt with the same plaintext produces different output.
54    fn encrypt(&self, plaintext: &[u8]) -> AppResult<String>;
55
56    /// Decrypts base64-encoded ciphertext and returns the plaintext.
57    fn decrypt(&self, ciphertext: &str) -> AppResult<Vec<u8>>;
58
59    /// Returns the algorithm used by this encryptor.
60    fn algorithm(&self) -> Algorithm;
61}