use bytes::Bytes;
use krab_crypt::{Keyring, is_encrypted};
use krab_store::Codec;
pub struct SecretCodec(Option<Keyring>);
impl SecretCodec {
pub fn new(keyring: Option<Keyring>) -> Self {
Self(keyring)
}
}
impl Codec for SecretCodec {
fn applies(&self, key: &str) -> bool {
key.starts_with("secrets/")
}
fn seal(&self, key: &str, plain: &[u8]) -> Bytes {
match &self.0 {
Some(k) => Bytes::from(k.encrypt(plain, key.as_bytes())),
None => Bytes::copy_from_slice(plain),
}
}
fn open(&self, key: &str, stored: &Bytes) -> Option<Bytes> {
if !is_encrypted(stored) {
return Some(stored.clone());
}
self.0
.as_ref()?
.decrypt(stored, key.as_bytes())
.ok()
.map(Bytes::from)
}
fn sealed(&self, stored: &[u8]) -> bool {
is_encrypted(stored)
}
}