diff --git a/rust/Cargo.lock b/rust/Cargo.lock index eccb998f..8ec16c3e 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -205,6 +205,18 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "enum_dispatch" +version = "0.3.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa18ce2bc66555b3218614519ac839ddb759a7d6720732f979ef8d13be147ecd" +dependencies = [ + "once_cell", + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "errno" version = "0.3.1" @@ -561,6 +573,7 @@ version = "0.10.0" dependencies = [ "byteorder", "curl", + "enum_dispatch", "foreign-types", "log", "openssl", diff --git a/rust/pv/Cargo.toml b/rust/pv/Cargo.toml index 5cd8b44d..b04f65f6 100644 --- a/rust/pv/Cargo.toml +++ b/rust/pv/Cargo.toml @@ -13,6 +13,7 @@ readme = "README.md" [dependencies] byteorder = "1.3" curl = "0.4.44" +enum_dispatch = "0.3.13" foreign-types = "0.3.1" log = { version = "0.4.6", features = ["std", "release_max_level_debug"] } openssl = "0.10.57" diff --git a/rust/pv/src/crypto.rs b/rust/pv/src/crypto.rs index 2639448c..bf37b650 100644 --- a/rust/pv/src/crypto.rs +++ b/rust/pv/src/crypto.rs @@ -2,6 +2,7 @@ // // Copyright IBM Corp. 2023, 2024 +use enum_dispatch::enum_dispatch; use openssl::{ derive::Deriver, ec::{EcGroup, EcKey}, @@ -50,8 +51,14 @@ impl From for Nid { } } +/// The `enum_dispatch` macros needs at least one local trait to be implemented. +#[allow(unused)] +#[enum_dispatch(SymKey)] +trait SymKeyTrait {} + /// Types of symmetric keys #[non_exhaustive] +#[enum_dispatch()] #[derive(Debug, Clone, PartialEq, Eq)] pub enum SymKey { /// AES 256 GCM key (32 bytes) @@ -92,12 +99,6 @@ impl SymKey { } } -impl From for SymKey { - fn from(value: Aes256Key) -> Self { - Self::Aes256(value) - } -} - /// Performs an hkdf according to RFC 5869. /// See [`OpenSSL HKDF`]() /// @@ -532,4 +533,13 @@ mod tests { SymKeyType::Aes256Xts ); } + + #[test] + fn try_from_and_into() { + let data = [0x1u8; 32]; + let key: SymKey = Aes256Key::new(data).into(); + assert_eq!(key.value(), &data); + let key_aes: Aes256Key = key.try_into().expect("should not fail"); + assert_eq!(key_aes.value(), &data); + } }