Skip to main content

sentc_crypto_std_keys/core/sym/
mod.rs

1use alloc::vec::Vec;
2
3use sentc_crypto_core::cryptomat::{CryptoAlg, SymKey, SymKeyComposer, SymKeyGen};
4use sentc_crypto_core::Error;
5
6use crate::core::sym::aes_gcm::Aes256GcmKey;
7
8pub(crate) mod aes_gcm;
9
10macro_rules! deref_macro {
11    ($self:expr, $method:ident $(, $args:expr)*) => {
12        match $self {
13           	Self::Aes(inner) => inner.$method($($args),*),
14        }
15    };
16}
17
18pub enum SymmetricKey
19{
20	Aes(Aes256GcmKey),
21}
22
23impl SymmetricKey
24{
25	pub fn aes_key_from_bytes_owned(bytes: Vec<u8>) -> Result<Self, Error>
26	{
27		Ok(Self::Aes(bytes.try_into()?))
28	}
29}
30
31impl SymKeyComposer for SymmetricKey
32{
33	type SymmetricKey = Self;
34
35	fn from_bytes_owned(bytes: Vec<u8>, alg_str: &str) -> Result<Self::SymmetricKey, Error>
36	{
37		match alg_str {
38			aes_gcm::AES_GCM_OUTPUT => Ok(Self::Aes(bytes.try_into()?)),
39			_ => Err(Error::AlgNotFound),
40		}
41	}
42}
43
44impl SymKeyGen for SymmetricKey
45{
46	type SymmetricKey = Self;
47
48	fn generate() -> Result<Self::SymmetricKey, Error>
49	{
50		#[cfg(feature = "aes")]
51		Ok(Aes256GcmKey::generate()?.into())
52	}
53}
54
55impl CryptoAlg for SymmetricKey
56{
57	fn get_alg_str(&self) -> &'static str
58	{
59		deref_macro!(self, get_alg_str)
60	}
61}
62
63impl AsRef<[u8]> for SymmetricKey
64{
65	fn as_ref(&self) -> &[u8]
66	{
67		deref_macro!(self, as_ref)
68	}
69}
70
71impl SymKey for SymmetricKey
72{
73	fn encrypt(&self, data: &[u8]) -> Result<Vec<u8>, Error>
74	{
75		deref_macro!(self, encrypt, data)
76	}
77
78	fn decrypt(&self, ciphertext: &[u8]) -> Result<Vec<u8>, Error>
79	{
80		deref_macro!(self, decrypt, ciphertext)
81	}
82
83	fn encrypt_with_aad(&self, data: &[u8], aad: &[u8]) -> Result<Vec<u8>, Error>
84	{
85		deref_macro!(self, encrypt_with_aad, data, aad)
86	}
87
88	fn decrypt_with_aad(&self, ciphertext: &[u8], aad: &[u8]) -> Result<Vec<u8>, Error>
89	{
90		deref_macro!(self, decrypt_with_aad, ciphertext, aad)
91	}
92}