mod stream;
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
use base64::engine::GeneralPurpose;
use base64::Engine;
use stream::{EncryptingIStream, EncryptingOStream};
use wildland_corex::dfs::interface::{IStream, OStream};
use crate::encryption::interface::{EncryptionModule, EncryptionModuleError};
const CIPHER_ENCRYPTION_EXPANSION_RATE: f64 = 4.0 / 3.0;
const CIPHER_DECRYPTION_SHRINKAGE_RATE: f64 = 3.0 / 4.0;
#[derive(Clone)]
pub struct Core {
engine: Arc<GeneralPurpose>,
}
impl Default for Core {
fn default() -> Self {
Self {
engine: Arc::new(base64::engine::general_purpose::STANDARD_NO_PAD),
}
}
}
impl EncryptionModule for Core {
fn wrap_istream(&self, istream: Box<dyn IStream>) -> Box<dyn IStream> {
Box::new(EncryptingIStream::new(istream, self.clone()))
}
fn wrap_ostream(&self, ostream: Box<dyn OStream>) -> Box<dyn OStream> {
Box::new(EncryptingOStream::new(ostream, self.clone()))
}
#[tracing::instrument(level = "debug", err(Debug), skip(input, self))]
fn encode_data(&self, input: &[u8]) -> Result<Vec<u8>, EncryptionModuleError> {
Ok(self.engine.encode(input).as_bytes().into())
}
#[tracing::instrument(level = "debug", err(Debug), skip(input, self))]
fn decode_data(&self, input: &[u8]) -> Result<Vec<u8>, EncryptionModuleError> {
Ok(self.engine.decode(input)?)
}
#[tracing::instrument(level = "debug", err(Debug), skip(input, self))]
fn encode_path(&self, input: &Path) -> Result<PathBuf, EncryptionModuleError> {
Ok(PathBuf::from(
input
.components()
.map(|c| match c {
Component::Normal(c) => self.engine.encode(c.to_string_lossy().as_bytes()),
v => v.as_os_str().to_string_lossy().to_string(),
})
.collect::<Vec<String>>()
.join("/"),
))
}
#[tracing::instrument(level = "debug", err(Debug), skip(input, self))]
fn decode_path(&self, input: &Path) -> Result<PathBuf, EncryptionModuleError> {
input
.components()
.map(|component| {
Ok(match component {
Component::Normal(c) => PathBuf::from(
String::from_utf8_lossy(
&self.engine.decode(c.to_string_lossy().as_bytes())?,
)
.to_string(),
),
v => PathBuf::from(v.as_os_str()),
})
})
.collect::<Result<PathBuf, EncryptionModuleError>>()
}
#[tracing::instrument(level = "debug", err(Debug), skip(input, self))]
fn decode_plain(&self, input: String) -> Result<String, EncryptionModuleError> {
let out = String::from_utf8_lossy(&self.engine.decode(input).unwrap()).to_string();
Ok(out)
}
}