sal/vault/src/key.rs
Mahmoud-Emad 6e5d9b35e8 feat: Update SAL Vault examples and documentation
- Renamed examples directory to `_archive` to reflect legacy status.
- Updated README.md to reflect current status of vault module,
  including migration from Sameh's implementation to Lee's.
- Temporarily disabled Rhai scripting integration for the vault.
- Added notes regarding current and future development steps.
2025-07-10 14:03:43 +03:00

84 lines
2.1 KiB
Rust

use asymmetric::AsymmetricKeypair;
use serde::{Deserialize, Serialize};
use signature::SigningKeypair;
use symmetric::SymmetricKey;
pub mod asymmetric;
pub mod signature;
pub mod symmetric;
#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize)]
pub enum KeyType {
/// The key can be used for symmetric key encryption
Symmetric,
/// The key can be used for asymmetric encryption
Asymmetric,
/// The key can be used for digital signatures
Signature,
}
/// Key holds generic information about a key
#[derive(Clone, Deserialize, Serialize)]
pub struct Key {
/// The mode of the key
mode: KeyType,
/// Raw bytes of the key
raw_key: Vec<u8>,
}
impl Key {
/// Try to downcast this `Key` to a [`SymmetricKey`]
pub fn as_symmetric(&self) -> Option<SymmetricKey> {
if matches!(self.mode, KeyType::Symmetric) {
SymmetricKey::from_bytes(&self.raw_key).ok()
} else {
None
}
}
/// Try to downcast this `Key` to an [`AsymmetricKeypair`]
pub fn as_asymmetric(&self) -> Option<AsymmetricKeypair> {
if matches!(self.mode, KeyType::Asymmetric) {
AsymmetricKeypair::from_bytes(&self.raw_key).ok()
} else {
None
}
}
/// Try to downcast this `Key` to a [`SigningKeypair`]
pub fn as_signing(&self) -> Option<SigningKeypair> {
if matches!(self.mode, KeyType::Signature) {
SigningKeypair::from_bytes(&self.raw_key).ok()
} else {
None
}
}
}
impl From<SymmetricKey> for Key {
fn from(value: SymmetricKey) -> Self {
Self {
mode: KeyType::Symmetric,
raw_key: Vec::from(value.as_raw_bytes()),
}
}
}
impl From<AsymmetricKeypair> for Key {
fn from(value: AsymmetricKeypair) -> Self {
Self {
mode: KeyType::Asymmetric,
raw_key: value.as_raw_private_key(),
}
}
}
impl From<SigningKeypair> for Key {
fn from(value: SigningKeypair) -> Self {
Self {
mode: KeyType::Signature,
raw_key: value.as_raw_private_key(),
}
}
}