Expand description
MAC factory for creating instances of algorithms that implement the MAC trait.
As with all Factory objects, this implements constructions from strings and defaults, and returns a MACFactory object which itself implements the MAC trait as a pass-through to the underlying algorithm.
Example usage: Generating and verifying a MAC value for a given piece of data:
use bouncycastle_core::key_material::{KeyMaterial256, KeyType};
use bouncycastle_core::traits::MAC;
use bouncycastle_hex as hex;
use bouncycastle_factory::AlgorithmFactory;
use bouncycastle_factory::mac_factory::MACFactory;
let data = b"Hi There!";
let key = KeyMaterial256::from_bytes_as_type(
// Note: This would be a bad key to use in a production application!
// But we'll hard-code a silly key for demonstration purposes.
&hex::decode("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b").unwrap(),
KeyType::MACKey,
).unwrap();
let hmac = MACFactory::new(bouncycastle_hmac::HMAC_SHA3_256_NAME, &key).unwrap();
// Generate the MAC value
let mac_value: Vec<u8> = hmac.mac(data);
// Verify the MAC value
let hmac = MACFactory::new(bouncycastle_hmac::HMAC_SHA3_256_NAME, &key).unwrap();
if hmac.verify(data, &mac_value,) {
println!("MAC verified successfully!")
} else {
println!("MAC verification failed")
}You can equivalently construct an instance of MACFactory by string instead of using the constant:
use bouncycastle_core::key_material::{KeyMaterial256, KeyType};
use bouncycastle_factory::AlgorithmFactory;
use bouncycastle_hex as hex;
use bouncycastle_factory::mac_factory::MACFactory;
let key = KeyMaterial256::from_bytes_as_type(
// Note: This would be a bad key to use in a production application!
// But we'll hard-code a silly key for demonstration purposes.
&hex::decode("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b").unwrap(),
KeyType::MACKey,
).unwrap();
let hmac = MACFactory::new("HMAC-SHA256", &key).unwrap();Or if you don’t particularly care which algorithm is used, you can use the built-in default:
use bouncycastle_core::key_material::{KeyMaterial256, KeyType};
use bouncycastle_factory::AlgorithmFactory;
use bouncycastle_hex as hex;
use bouncycastle_factory::mac_factory::MACFactory;
let key = KeyMaterial256::from_bytes_as_type(
// Note: This would be a bad key to use in a production application!
// But we'll hard-code a silly key for demonstration purposes.
&hex::decode("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b").unwrap(),
KeyType::MACKey,
).unwrap();
let hmac = MACFactory::default(&key);Enums§
- MACFactory
- MACFactory deviates from the usual AlgorithmFactory trait because MAC objects do not have a no-arg constructor; instead they have a constructor that takes a KeyMaterialTrait and can return an error.