...
This commit is contained in:
83
packages/crypt/vault/src/key.rs
Normal file
83
packages/crypt/vault/src/key.rs
Normal file
@@ -0,0 +1,83 @@
|
||||
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(),
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user