[pdf] Redaction: rebuild redacted pages as one image, scrub hidden data, prune; reader and AES-256 protect/unlock
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
//! Password on and off. pdfium cannot write encryption, so lopdf does both: AES-256 (PDF 2.0, revision 6) to
|
||||
//! protect, and a decrypting load plus a plain save to unlock.
|
||||
use crate::{PdfError, lopdf_load, lopdf_save};
|
||||
use lopdf::encryption::crypt_filters::{Aes256CryptFilter, CryptFilter};
|
||||
use lopdf::{EncryptionState, EncryptionVersion, Permissions};
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Whether opening the document needs a password.
|
||||
pub fn is_encrypted(bytes: &[u8]) -> bool {
|
||||
matches!(lopdf_load(bytes, None), Err(PdfError::NeedsPassword))
|
||||
}
|
||||
|
||||
/// Protects a document with `user_password` (needed to open it). `owner_password` defaults to the same password.
|
||||
/// `current_password` opens an already protected document first. The result uses AES-256 and allows everything to
|
||||
/// whoever opens it (Pictor does not set permission restrictions: they are not a security boundary).
|
||||
pub fn protect(
|
||||
bytes: &[u8],
|
||||
current_password: Option<&str>,
|
||||
user_password: &str,
|
||||
owner_password: Option<&str>,
|
||||
) -> Result<Vec<u8>, PdfError> {
|
||||
if user_password.is_empty() {
|
||||
return Err(PdfError::Invalid("Choose a password.".into()));
|
||||
}
|
||||
let mut doc = lopdf_load(bytes, current_password)?;
|
||||
let mut key = [0u8; 32];
|
||||
getrandom::fill(&mut key).map_err(|e| PdfError::Write(format!("no random numbers from Windows: {e}")))?;
|
||||
let filter: Arc<dyn CryptFilter> = Arc::new(Aes256CryptFilter);
|
||||
let state = EncryptionState::try_from(EncryptionVersion::V5 {
|
||||
encrypt_metadata: true,
|
||||
crypt_filters: BTreeMap::from([(b"StdCF".to_vec(), filter)]),
|
||||
file_encryption_key: &key,
|
||||
stream_filter: b"StdCF".to_vec(),
|
||||
string_filter: b"StdCF".to_vec(),
|
||||
owner_password: owner_password.filter(|p| !p.is_empty()).unwrap_or(user_password),
|
||||
user_password,
|
||||
permissions: Permissions::all(),
|
||||
})
|
||||
.map_err(|e| PdfError::Write(e.to_string()))?;
|
||||
doc.encrypt(&state).map_err(|e| PdfError::Write(e.to_string()))?;
|
||||
key.fill(0);
|
||||
lopdf_save(&mut doc)
|
||||
}
|
||||
|
||||
/// Removes the password from a document (the password must be right).
|
||||
pub fn unlock(bytes: &[u8], password: &str) -> Result<Vec<u8>, PdfError> {
|
||||
let mut doc = lopdf_load(bytes, Some(password))?;
|
||||
doc.trailer.remove(b"Encrypt");
|
||||
lopdf_save(&mut doc)
|
||||
}
|
||||
Reference in New Issue
Block a user