Skip to main content

bouncycastle_factory/
lib.rs

1//! Factory crate for creating instances of different types.
2//! Factory objects behave like other crypto providers in that they take an algorithm by string name and return an instance of the corresponding type.
3//! Generally, there is one factory for each trait in [bouncycastle_core_interface::traits].
4//!
5//! All factories are based on the rust enum factory pattern where, for example, the [hash_factory::HashFactory]
6//! can hold any Hash type in the library, and [hash_factory::HashFactory] itself impls [bouncycastle_core_interface::traits::Hash]
7//! and so can be called directly as if it is a hash.
8//!
9//! Example usage:
10//! ```
11//! use bouncycastle_core_interface::traits::Hash;
12//! use bouncycastle_factory::AlgorithmFactory;
13//! use bouncycastle_factory::hash_factory::HashFactory;
14//!
15//! let data: &[u8] = b"Hello, world!";
16//!
17//! let h = HashFactory::new("SHA3-256").unwrap();
18//! let output: Vec<u8> = h.hash(data);
19//! ```
20//!
21//! All other factory types similarly implement their underlying trait and thus behave the same way.
22//!
23//! Additionally, all factory types implement [AlgorithmFactory] which exposes functions to
24//! get the either the default algorithm or the default algorithm at the 128-bit or 256-bit security level.
25//! It also exposes [AlgorithmFactory::new] which can be used to create an instance of the algorithm
26//! by string name according to the string constants associated with the respective factory type.
27
28use bouncycastle_core_interface::errors::{MACError};
29
30pub mod hash_factory;
31pub mod kdf_factory;
32pub mod mac_factory;
33pub mod rng_factory;
34pub mod xof_factory;
35
36/*** String constants ***/
37pub const DEFAULT: &str = "Default";
38pub const DEFAULT_128_BIT: &str = "Default128Bit";
39pub const DEFAULT_256_BIT: &str = "Default256Bit";
40
41
42#[derive(Debug)]
43pub enum FactoryError {
44    MACError(MACError),
45    UnsupportedAlgorithm(String),
46}
47
48impl From<MACError> for FactoryError {
49    fn from(e: MACError) -> FactoryError {
50        Self::MACError(e)
51    }
52}
53
54pub trait AlgorithmFactory: Sized + Default {
55
56    // Get the default configured algorithm.
57    // Not implemented because all factories MUST impl Default.
58    // fn default() -> Self;
59
60    /// Get the default configured algorithm at the 128-bit security level.
61    fn default_128_bit() -> Self;
62
63    /// Get the default configured algorithm at the 256-bit security level.
64    fn default_256_bit() -> Self;
65
66    /// Create an instance of the algorithm by name.
67    fn new(alg_name: &str) -> Result<Self, FactoryError>;
68}