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::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::traits::Hash`]
7//! and so can be called directly as if it is a hash.
8//!
9//! Example usage:
10//! ```
11//! use bouncycastle_core::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//!
28//! This crate compiles with STD; ie it is explicitly not tagged as `no_std` and it makes use of `Vec` and other
29//! dynamically-sized nice things.
30
31#![forbid(unsafe_code)]
32#![forbid(missing_docs)]
33
34use bouncycastle_core::errors::MACError;
35
36pub mod hash_factory;
37pub mod kdf_factory;
38pub mod mac_factory;
39pub mod rng_factory;
40pub mod xof_factory;
41
42/*** String constants ***/
43///
44pub const DEFAULT: &str = "Default";
45///
46pub const DEFAULT_128_BIT: &str = "Default128Bit";
47///
48pub const DEFAULT_256_BIT: &str = "Default256Bit";
49
50/// Top-level error type for Factories.
51#[derive(Debug)]
52pub enum FactoryError {
53    ///
54    MACError(MACError),
55    ///
56    UnsupportedAlgorithm(String),
57}
58
59impl From<MACError> for FactoryError {
60    fn from(e: MACError) -> FactoryError {
61        Self::MACError(e)
62    }
63}
64
65///
66pub trait AlgorithmFactory: Sized + Default {
67    /// Get the default configured algorithm at the 128-bit security level.
68    fn default_128_bit() -> Self;
69
70    /// Get the default configured algorithm at the 256-bit security level.
71    fn default_256_bit() -> Self;
72
73    /// Get an instance of the algorithm by name.
74    fn new(alg_name: &str) -> Result<Self, FactoryError>;
75}