dcrypt_api/traits/pke.rs
1//! Trait definition for Public Key Encryption (PKE) schemes.
2
3use crate::error::Result; // from api::error
4use rand::{CryptoRng, RngCore};
5use zeroize::Zeroize;
6
7// Ensure Vec is available for no_std + alloc, and other necessary imports
8#[cfg(all(not(feature = "std"), feature = "alloc"))]
9use alloc::vec::Vec;
10#[cfg(feature = "std")]
11use std::vec::Vec;
12
13/// Trait for Public Key Encryption schemes.
14pub trait Pke {
15 /// Public key type for the PKE scheme.
16 /// Expected to be a byte representation that can be deserialized.
17 type PublicKey: AsRef<[u8]> + Clone;
18
19 /// Secret key type for the PKE scheme.
20 /// Expected to be a byte representation that can be deserialized.
21 type SecretKey: Zeroize + AsRef<[u8]> + Clone;
22
23 /// Ciphertext type produced by the PKE scheme.
24 /// This is typically a `Vec<u8>` containing the serialized ciphertext components.
25 type Ciphertext: AsRef<[u8]> + Clone;
26
27 /// Returns the PKE algorithm name.
28 fn name() -> &'static str;
29
30 /// Generates a new key pair for the PKE scheme.
31 fn keypair<R: CryptoRng + RngCore>(rng: &mut R) -> Result<(Self::PublicKey, Self::SecretKey)>;
32
33 /// Encrypts a plaintext message using the recipient's public key.
34 ///
35 /// # Arguments
36 /// * `pk_recipient` - The recipient's public key.
37 /// * `plaintext` - The message to encrypt.
38 /// * `aad` - Optional Associated Additional Data to be authenticated.
39 /// * `rng` - A cryptographically secure random number generator.
40 ///
41 /// # Returns
42 /// The resulting ciphertext as a `Vec<u8>`.
43 fn encrypt<R: RngCore + CryptoRng>(
44 pk_recipient: &Self::PublicKey,
45 plaintext: &[u8],
46 aad: Option<&[u8]>,
47 rng: &mut R,
48 ) -> Result<Self::Ciphertext>;
49
50 /// Decrypts a ciphertext using the recipient's secret key.
51 ///
52 /// # Arguments
53 /// * `sk_recipient` - The recipient's secret key.
54 /// * `ciphertext` - The ciphertext to decrypt.
55 /// * `aad` - Optional Associated Additional Data that was authenticated.
56 ///
57 /// # Returns
58 /// The original plaintext as a `Vec<u8>` if decryption and authentication (if applicable) succeed.
59 fn decrypt(
60 sk_recipient: &Self::SecretKey,
61 ciphertext: &Self::Ciphertext,
62 aad: Option<&[u8]>,
63 ) -> Result<Vec<u8>>;
64}