use crate::object::ObjectId;
mod aes;
mod md5;
mod rc4;
mod sha2;
mod standard;
pub use md5::{Md5, md5};
pub use rc4::rc4_in_place;
pub use standard::{Cipher, EncryptDict, PasswordRole, StandardHandler};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EncryptionScheme {
None,
Rc4 { key_bits: u16 },
Aes128,
Aes256,
}
#[derive(Debug, Clone, Copy)]
pub struct Permissions(pub u32);
#[derive(Debug)]
pub struct SecurityContext {
pub scheme: EncryptionScheme,
pub permissions: Permissions,
handler: Option<StandardHandler>,
password_role: Option<PasswordRole>,
}
impl SecurityContext {
pub fn unencrypted() -> Self {
Self {
scheme: EncryptionScheme::None,
permissions: Permissions(0xFFFF_FFFF),
handler: None,
password_role: None,
}
}
pub fn standard(
scheme: EncryptionScheme,
permissions: Permissions,
handler: StandardHandler,
) -> Self {
Self {
scheme,
permissions,
handler: Some(handler),
password_role: None,
}
}
pub fn with_password_role(mut self, role: PasswordRole) -> Self {
self.password_role = Some(role);
self
}
pub fn password_role(&self) -> Option<PasswordRole> {
self.password_role
}
pub fn is_encrypted(&self) -> bool {
self.handler.is_some()
}
pub fn decrypt_in_place(&self, id: ObjectId, buf: &mut Vec<u8>) -> Result<(), SecurityError> {
match &self.handler {
None => Ok(()),
Some(h) => {
h.decrypt(id.number, id.generation, buf);
Ok(())
}
}
}
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum SecurityError {
#[error("unsupported encryption scheme {0:?}")]
UnsupportedScheme(EncryptionScheme),
#[error("password required")]
PasswordRequired,
#[error("incorrect password")]
IncorrectPassword,
#[error("malformed /Encrypt dictionary: {0}")]
MalformedEncryptDict(&'static str),
}