Skip to main content

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