lum_ccc_rust/crates/ccc-crypto-core/src/provider.rs

200 lines
7.8 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! Provider traits that every crypto backend must implement.
//!
//! A concrete provider (e.g. `WolfSslProvider`) implements [`CryptoProvider`],
//! which in turn requires all five primitive traits: [`AeadProvider`],
//! [`KdfProvider`], [`MacProvider`], [`HashProvider`], and optionally
//! [`KemProvider`].
//!
//! The trait objects are `Send + Sync` so they can live in the global
//! [`ProviderRegistry`][crate::registry::ProviderRegistry] behind a
//! `Mutex`.
use zeroize::Zeroizing;
use crate::{
algorithms::{AeadAlgorithm, HashAlgorithm, KdfAlgorithm, KemAlgorithm, MacAlgorithm},
capabilities::ProviderCapabilities,
error::CryptoError,
types::{BenchmarkReport, KemEncapResult, KemKeyPair, SelfTestReport},
};
// ──────────────────────────────────────────────────────────────────────────────
// Primitive traits
// ──────────────────────────────────────────────────────────────────────────────
/// AEAD (Authenticated Encryption with Associated Data) operations.
pub trait AeadProvider {
/// Encrypt `plaintext` and return `ciphertext || tag`.
///
/// # Parameters
/// - `algo` – Which AEAD algorithm to use.
/// - `key` – Raw key bytes. Length must match [`AeadAlgorithm::key_len`].
/// - `nonce` – Nonce / IV bytes. Length must match [`AeadAlgorithm::nonce_len`].
/// - `plaintext` – Data to encrypt.
/// - `aad` – Additional associated data (authenticated but not encrypted).
///
/// # Returns
/// Concatenated ciphertext + authentication tag.
fn encrypt_aead(
&self,
algo: AeadAlgorithm,
key: &[u8],
nonce: &[u8],
plaintext: &[u8],
aad: &[u8],
) -> Result<Vec<u8>, CryptoError>;
/// Decrypt and authenticate `ciphertext || tag`, returning the plaintext.
///
/// Returns [`CryptoError::AuthenticationFailed`] if the tag does not verify.
fn decrypt_aead(
&self,
algo: AeadAlgorithm,
key: &[u8],
nonce: &[u8],
ciphertext_and_tag: &[u8],
aad: &[u8],
) -> Result<Vec<u8>, CryptoError>;
}
/// Key derivation function operations.
pub trait KdfProvider {
/// Derive a key of `length` bytes from input keying material.
///
/// # Parameters
/// - `algo` – Which KDF to use.
/// - `ikm` – Input keying material.
/// - `salt` – Optional salt (pass an empty slice to use the zero salt).
/// - `info` – Context / label bytes (HKDF `info` field or equivalent).
/// - `length` – Desired output byte length.
///
/// # Returns
/// A `Zeroizing<Vec<u8>>` that is zeroed automatically on drop.
fn derive_key(
&self,
algo: KdfAlgorithm,
ikm: &[u8],
salt: &[u8],
info: &[u8],
length: usize,
) -> Result<Zeroizing<Vec<u8>>, CryptoError>;
}
/// Message authentication code operations.
pub trait MacProvider {
/// Compute a MAC tag over `data` using `key`.
fn compute_mac(
&self,
algo: MacAlgorithm,
key: &[u8],
data: &[u8],
) -> Result<Vec<u8>, CryptoError>;
/// Verify that `mac` is the correct tag for `data` under `key`.
///
/// Implementations **must** use constant-time comparison to avoid timing
/// side-channels.
///
/// Returns `Ok(true)` if verification succeeds, `Ok(false)` if the tag
/// does not match (do not return an error for mismatches — the caller
/// decides how to handle false).
fn verify_mac(
&self,
algo: MacAlgorithm,
key: &[u8],
data: &[u8],
mac: &[u8],
) -> Result<bool, CryptoError>;
}
/// Cryptographic hash operations.
pub trait HashProvider {
/// Compute a digest of `data` using the specified algorithm.
fn hash(&self, algo: HashAlgorithm, data: &[u8]) -> Result<Vec<u8>, CryptoError>;
}
/// Key encapsulation mechanism operations.
///
/// Not required by [`CryptoProvider`] — providers that only implement symmetric
/// operations simply do not implement this trait. The bridge exposes KEM
/// functions separately and looks up a `KemProvider` from the registry.
pub trait KemProvider {
/// Generate a new KEM key pair.
fn generate_keypair(&self, algo: KemAlgorithm) -> Result<KemKeyPair, CryptoError>;
/// Encapsulate a shared secret for the holder of `public_key`.
///
/// Returns `(ciphertext, shared_secret)`. The caller sends `ciphertext`
/// to the peer and uses `shared_secret` locally.
fn encapsulate(
&self,
algo: KemAlgorithm,
public_key: &[u8],
) -> Result<KemEncapResult, CryptoError>;
/// Decapsulate a shared secret from `ciphertext` using `private_key`.
///
/// Returns the same `shared_secret` that the encapsulator obtained.
fn decapsulate(
&self,
algo: KemAlgorithm,
private_key: &[u8],
ciphertext: &[u8],
) -> Result<Zeroizing<Vec<u8>>, CryptoError>;
}
// ──────────────────────────────────────────────────────────────────────────────
// Umbrella trait
// ──────────────────────────────────────────────────────────────────────────────
/// The combined interface every full-featured crypto provider must satisfy.
///
/// Implementors are automatically usable as `Box<dyn CryptoProvider>` in the
/// [`ProviderRegistry`][crate::registry::ProviderRegistry].
///
/// # Implementing a new provider
///
/// 1. Create a new crate under `crates/ccc-crypto-<name>/`.
/// 2. Implement `AeadProvider`, `KdfProvider`, `MacProvider`, `HashProvider`
/// for your provider struct.
/// 3. Implement `CryptoProvider` (add `capabilities()`, `self_test()`,
/// `benchmark()`, `provider_name()`).
/// 4. In your `init()` function call
/// `ProviderRegistry::global().register(name, Box::new(provider))`.
/// 5. Call `ccc_crypto_<name>::init()` from `ccc-flutter-bridge/src/lib.rs`.
/// 6. Add NIST test vectors for every algorithm you expose.
pub trait CryptoProvider:
AeadProvider + KdfProvider + MacProvider + HashProvider + Send + Sync
{
/// The provider's canonical name (e.g. `"wolfssl"`).
///
/// Must be lowercase, no spaces, match the `CccCryptoProvider` enum value
/// in `ccc_provider_spec.dart`.
fn provider_name(&self) -> &'static str;
/// Whether this provider runs as a FIPS 140-3 validated module in FIPS
/// mode. Release policy requires the vetted layer of every suite to come
/// from such a provider (D-26). Defaults to `false`.
fn fips_mode(&self) -> bool {
false
}
/// Return the full runtime capability matrix for this provider.
///
/// Called once at startup after [`CryptoProvider::self_test`] and
/// [`CryptoProvider::benchmark`] have completed.
fn capabilities(&self) -> ProviderCapabilities;
/// Run embedded NIST/RFC test vectors for every implemented algorithm.
///
/// This must be a deterministic, side-effect-free operation that can be
/// called at any time (including in CI without native hardware).
fn self_test(&self) -> SelfTestReport;
/// Measure throughput for every implemented AEAD algorithm.
///
/// Encrypt 1 MB of random data × 100 iterations and normalise the
/// result into `efficiency_score: u8` (0–100).
fn benchmark(&self) -> BenchmarkReport;
}