#[cfg(feature = "keyless")]
use crate::constants::HARDCODED_KEY_BYTES;
use crate::{format::IntoFormat, Encoding, Error, Format, MasterKey, ObtextCodec, Scheme};
pub struct Ob {
masterkey: MasterKey,
format: Format,
}
impl Ob {
pub fn new(format: impl IntoFormat, key: &str) -> Result<Self, Error> {
let format = format.into_format()?;
Ok(Self {
masterkey: MasterKey::from_base64(key)?,
format,
})
}
pub fn set_format(&mut self, format: impl IntoFormat) -> Result<(), Error> {
self.format = format.into_format()?;
Ok(())
}
pub fn set_scheme(&mut self, scheme: Scheme) -> Result<(), Error> {
self.format = Format::new(scheme, self.format.encoding());
Ok(())
}
pub fn set_encoding(&mut self, encoding: Encoding) -> Result<(), Error> {
self.format = Format::new(self.format.scheme(), encoding);
Ok(())
}
#[inline]
pub fn autodec(&self, obtext: &str) -> Result<String, Error> {
if let Ok(result) =
crate::dec_auto::dec_any_scheme(&self.masterkey, self.format.encoding(), obtext)
{
return Ok(result);
}
crate::dec_auto::dec_any_format(&self.masterkey, obtext)
}
#[cfg(feature = "keyless")]
pub fn new_keyless(format: impl IntoFormat) -> Result<Self, Error> {
let format = format.into_format()?;
Ok(Self {
masterkey: MasterKey::from_bytes(&HARDCODED_KEY_BYTES)?,
format,
})
}
#[cfg(feature = "hex-keys")]
pub fn from_hex_key(format: impl IntoFormat, key_hex: &str) -> Result<Self, Error> {
let format = format.into_format()?;
Ok(Self {
masterkey: MasterKey::from_hex(key_hex)?,
format,
})
}
#[cfg(feature = "bytes-keys")]
pub fn from_bytes(format: impl IntoFormat, key: &[u8; 64]) -> Result<Self, Error> {
let format = format.into_format()?;
Ok(Self {
masterkey: MasterKey::from_bytes(key)?,
format,
})
}
#[inline]
pub fn key(&self) -> String {
self.masterkey.key_base64()
}
#[cfg(feature = "hex-keys")]
#[inline]
pub fn key_hex(&self) -> String {
self.masterkey.key_hex()
}
#[cfg(feature = "bytes-keys")]
#[inline]
pub fn key_bytes(&self) -> &[u8; 64] {
self.masterkey.key_bytes()
}
}
impl ObtextCodec for Ob {
fn enc(&self, plaintext: &str) -> Result<String, Error> {
crate::enc::enc_to_format(plaintext, self.format, self.masterkey.key())
}
fn dec(&self, obtext: &str) -> Result<String, Error> {
crate::dec::dec_from_format(obtext, self.format, self.masterkey.key())
}
fn format(&self) -> Format {
self.format
}
fn scheme(&self) -> Scheme {
self.format.scheme()
}
fn encoding(&self) -> Encoding {
self.format.encoding()
}
}
impl Ob {
#[inline]
pub fn enc(&self, plaintext: &str) -> Result<String, Error> {
<Self as ObtextCodec>::enc(self, plaintext)
}
#[inline]
pub fn dec(&self, obtext: &str) -> Result<String, Error> {
<Self as ObtextCodec>::dec(self, obtext)
}
#[inline]
pub fn format(&self) -> Format {
<Self as ObtextCodec>::format(self)
}
#[inline]
pub fn scheme(&self) -> Scheme {
<Self as ObtextCodec>::scheme(self)
}
#[inline]
pub fn encoding(&self) -> Encoding {
<Self as ObtextCodec>::encoding(self)
}
}