dcrypt_api/traits/
symmetric.rs

1//! Trait definition for symmetric encryption algorithms with enhanced type safety
2
3use crate::Result;
4use rand::{CryptoRng, RngCore};
5use zeroize::Zeroize;
6
7/// Base trait for operations
8pub trait Operation<T> {
9    /// Execute the operation and produce a result
10    fn execute(self) -> Result<T>;
11}
12
13/// Base trait for encryption operations
14pub trait EncryptOperation<'a, C: SymmetricCipher>: Operation<C::Ciphertext> {
15    /// Set the nonce for encryption
16    fn with_nonce(self, nonce: &'a C::Nonce) -> Self;
17
18    /// Set associated data for authenticated encryption
19    fn with_aad(self, aad: &'a [u8]) -> Self;
20
21    /// Set plaintext and execute encryption
22    fn encrypt(self, plaintext: &'a [u8]) -> Result<C::Ciphertext>;
23}
24
25/// Base trait for decryption operations
26pub trait DecryptOperation<'a, C: SymmetricCipher>: Operation<Vec<u8>> {
27    /// Set the nonce for decryption
28    fn with_nonce(self, nonce: &'a C::Nonce) -> Self;
29
30    /// Set associated data for authenticated decryption
31    fn with_aad(self, aad: &'a [u8]) -> Self;
32
33    /// Set ciphertext and execute decryption
34    fn decrypt(self, ciphertext: &'a C::Ciphertext) -> Result<Vec<u8>>;
35}
36
37/// Trait for symmetric encryption algorithms with enhanced type safety
38pub trait SymmetricCipher: Sized {
39    /// Key type with appropriate algorithm binding
40    type Key: Zeroize + AsRef<[u8]> + AsMut<[u8]> + Clone;
41
42    /// Nonce type with appropriate size constraint
43    type Nonce: AsRef<[u8]> + AsMut<[u8]> + Clone;
44
45    /// Ciphertext output type
46    type Ciphertext: AsRef<[u8]> + AsMut<[u8]> + Clone;
47
48    /// Operation type for encryption operations
49    type EncryptOperation<'a>: EncryptOperation<'a, Self>
50    where
51        Self: 'a;
52
53    /// Operation type for decryption operations
54    type DecryptOperation<'a>: DecryptOperation<'a, Self>
55    where
56        Self: 'a;
57
58    /// Returns the symmetric cipher algorithm name
59    fn name() -> &'static str;
60
61    /// Begin encryption operation
62    fn encrypt(&self) -> Self::EncryptOperation<'_>;
63
64    /// Begin decryption operation
65    fn decrypt(&self) -> Self::DecryptOperation<'_>;
66
67    /// Generate a new random key
68    fn generate_key<R: RngCore + CryptoRng>(rng: &mut R) -> Result<Self::Key>;
69
70    /// Generate a new random nonce
71    fn generate_nonce<R: RngCore + CryptoRng>(rng: &mut R) -> Result<Self::Nonce>;
72
73    /// Derive a key from arbitrary bytes
74    fn derive_key_from_bytes(bytes: &[u8]) -> Result<Self::Key>;
75}