use crate::error::EncryptError;
pub trait KeyProvider: Send + Sync {
fn get_key(&self) -> Result<&[u8], EncryptError>;
fn key32(&self) -> Result<&[u8; 32], EncryptError> {
let raw = self.get_key()?;
raw.try_into()
.map_err(|_| EncryptError::InvalidKeyLength { got: raw.len() })
}
}
#[derive(Clone)]
pub struct StaticKey(Vec<u8>);
impl StaticKey {
pub fn new(bytes: Vec<u8>) -> Self {
Self(bytes)
}
pub fn from_array(key: [u8; 32]) -> Self {
Self(key.to_vec())
}
}
impl core::fmt::Debug for StaticKey {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("StaticKey")
.field("len", &self.0.len())
.finish()
}
}
impl KeyProvider for StaticKey {
fn get_key(&self) -> Result<&[u8], EncryptError> {
if self.0.len() == 32 {
Ok(&self.0)
} else {
Err(EncryptError::InvalidKeyLength { got: self.0.len() })
}
}
}
#[derive(Debug, Clone)]
pub struct KeyringKey {
label: String,
}
impl KeyringKey {
pub fn new(label: impl Into<String>) -> Self {
Self {
label: label.into(),
}
}
pub fn label(&self) -> &str {
&self.label
}
}
impl KeyProvider for KeyringKey {
fn get_key(&self) -> Result<&[u8], EncryptError> {
Err(EncryptError::KeyringUnavailable {
label: self.label.clone(),
})
}
}