mirror of
https://github.com/ibm-s390-linux/s390-tools.git
synced 2026-08-05 02:14:52 +00:00
rust/crypto: Replace From<Aes256Key> for SymKey with enum_dispatch macro
Use the `enum_dispatch` macro for providing the `From` and `TryInto` functionalities. In addition, it makes dynamic dispatching using enums much easier. Reviewed-by: Steffen Eiden <seiden@linux.ibm.com> Signed-off-by: Marc Hartmayer <mhartmay@linux.ibm.com> Signed-off-by: Steffen Eiden <seiden@linux.ibm.com>
This commit is contained in:
committed by
Steffen Eiden
parent
050441922b
commit
385ba6b51f
+16
-6
@@ -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<SymKeyType> 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<Aes256Key> 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);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user