#![allow(dead_code)]
pub(crate) use super::keys::ObjectKeyAlg;
use crate::encryption::primitives::md5;
use crate::encryption::rc4::Rc4;
use crate::error::{EncryptedError, Result};
use crate::pipeline::aes::PlAesPdf;
use crate::pipeline::sha2::PlSha2;
use crate::pipeline::Pipeline;
use crate::ObjectHandle;
pub(crate) const PASSWORD_PADDING: [u8; 32] = [
0x28, 0xBF, 0x4E, 0x5E, 0x4E, 0x75, 0x8A, 0x41, 0x64, 0x00, 0x4E, 0x56, 0xFF, 0xFA, 0x01, 0x08,
0x2E, 0x2E, 0x00, 0xB6, 0xD0, 0x68, 0x3E, 0x80, 0x2F, 0x0C, 0xA9, 0xFE, 0x64, 0x53, 0x69, 0x7A,
];
pub(crate) struct StandardHandlerInputs<'a> {
pub v: i64,
pub r: i64,
pub length_bits: i64,
pub p: i32,
pub id0: &'a [u8],
pub u: &'a [u8; 32],
pub o: &'a [u8; 32],
pub encrypt_metadata: bool,
}
pub(crate) struct StandardHandlerR5Inputs<'a> {
pub u: &'a [u8; 48],
pub o: &'a [u8; 48],
pub ue: &'a [u8; 32],
pub oe: &'a [u8; 32],
}
fn pad_password(password: &[u8]) -> [u8; 32] {
let mut out = [0u8; 32];
let pw_len = password.len().min(32);
out[..pw_len].copy_from_slice(&password[..pw_len]);
if pw_len < 32 {
let pad_needed = 32 - pw_len;
out[pw_len..].copy_from_slice(&PASSWORD_PADDING[..pad_needed]);
}
out
}
pub(crate) fn v_lt_5_32_byte_parameter(bytes: &[u8]) -> [u8; 32] {
let mut out = [0u8; 32];
let len = bytes.len().min(32);
out[..len].copy_from_slice(&bytes[..len]);
out
}
fn truncate_password_v5(password: &[u8]) -> &[u8] {
&password[..password.len().min(127)]
}
fn validate_inputs(inputs: &StandardHandlerInputs<'_>) -> Result<usize> {
if !matches!(inputs.v, 1 | 2 | 4) {
return Err(EncryptedError::UnsupportedHandler {
filter: "Standard".into(),
v: inputs.v,
r: inputs.r,
cfm: None,
}
.into());
}
if !(2..=6).contains(&inputs.r) {
return Err(EncryptedError::UnsupportedHandler {
filter: "Standard".into(),
v: inputs.v,
r: inputs.r,
cfm: None,
}
.into());
}
if inputs.v == 1 && inputs.length_bits != 40 {
return Err(EncryptedError::UnsupportedHandler {
filter: "Standard".into(),
v: inputs.v,
r: inputs.r,
cfm: None,
}
.into());
}
if inputs.length_bits < 40 || inputs.length_bits > 128 || inputs.length_bits % 8 != 0 {
return Err(EncryptedError::Malformed {
reason: format!(
"/Length {} is invalid; must be a multiple of 8 between 40 and 128",
inputs.length_bits
),
}
.into());
}
Ok((inputs.length_bits / 8) as usize)
}
fn validate_v4_inputs(inputs: &StandardHandlerInputs<'_>) -> Result<usize> {
if inputs.v != 4 || inputs.r != 4 || inputs.length_bits != 128 {
return Err(EncryptedError::UnsupportedHandler {
filter: "Standard".into(),
v: inputs.v,
r: inputs.r,
cfm: None,
}
.into());
}
Ok(16)
}
fn r5_salted_hash(password: &[u8], salt: &[u8], extra: &[u8]) -> Result<[u8; 32]> {
let mut hash = PlSha2::new("sha2", None, 256)?;
hash.write(password)?;
hash.write(salt)?;
hash.write(extra)?;
hash.finish()?;
let mut key = [0u8; 32];
key.copy_from_slice(hash.get_raw_digest()?);
Ok(key)
}
fn aes256_cbc_zero_iv_unwrap(encrypted_key: &[u8; 32], aes_key: &[u8; 32]) -> Result<Vec<u8>> {
PlAesPdf::process_to_vec_without_padding(
"AES V=5 file-key unwrap",
false,
encrypted_key,
aes_key,
1,
None,
)
.map_err(|_| EncryptedError::Malformed {
reason: "invalid V=5 encrypted file-key entry".into(),
})
.map_err(Into::into)
}
fn decrypt_r5_file_key(
password: &[u8],
entry: &[u8; 48],
encrypted_key: &[u8; 32],
extra: &[u8],
) -> Result<Vec<u8>> {
let validation_salt = &entry[32..40];
let key_salt = &entry[40..48];
let validation_hash = r5_salted_hash(password, validation_salt, extra)?;
if validation_hash[..] != entry[..32] {
return Err(EncryptedError::BadPassword.into());
}
let aes_key = r5_salted_hash(password, key_salt, extra)?;
aes256_cbc_zero_iv_unwrap(encrypted_key, &aes_key)
}
fn r6_password_hash(password: &[u8], salt: &[u8], extra: &[u8]) -> Result<[u8; 32]> {
let mut key = r5_salted_hash(password, salt, extra)?.to_vec();
let mut round_number = 0usize;
loop {
round_number += 1;
let mut k1 = Vec::with_capacity(password.len() + key.len() + extra.len());
k1.extend_from_slice(password);
k1.extend_from_slice(&key);
k1.extend_from_slice(extra);
let mut aes_key = [0u8; 16];
aes_key.copy_from_slice(&key[..16]);
let mut iv = [0u8; 16];
iv.copy_from_slice(&key[16..32]);
let e = PlAesPdf::process_to_vec_without_padding(
"AES R=6 hash",
true,
&k1,
&aes_key,
64,
Some(&iv),
)?;
let e_mod_3 = e[..16]
.iter()
.fold(0u16, |acc, byte| acc + u16::from(*byte))
% 3;
let next_hash = match e_mod_3 {
0 => 256,
1 => 384,
_ => 512,
};
let mut sha2 = PlSha2::new("sha2", None, next_hash)?;
sha2.write(&e)?;
sha2.finish()?;
key = sha2.get_raw_digest()?.to_vec();
if round_number >= 64
&& usize::from(*e.last().expect("R=6 E is non-empty")) <= round_number - 32
{
let mut out = [0u8; 32];
out.copy_from_slice(&key[..32]);
return Ok(out);
}
}
}
fn decrypt_r6_file_key(
password: &[u8],
entry: &[u8; 48],
encrypted_key: &[u8; 32],
extra: &[u8],
) -> Result<Vec<u8>> {
let validation_salt = &entry[32..40];
let key_salt = &entry[40..48];
let validation_hash = r6_password_hash(password, validation_salt, extra)?;
if validation_hash[..] != entry[..32] {
return Err(EncryptedError::BadPassword.into());
}
let aes_key = r6_password_hash(password, key_salt, extra)?;
aes256_cbc_zero_iv_unwrap(encrypted_key, &aes_key)
}
pub(crate) fn compute_encryption_key_from_password(
password: &[u8],
inputs: &StandardHandlerInputs<'_>,
) -> Result<Vec<u8>> {
let padded = pad_password(password);
let p_le = inputs.p.to_le_bytes();
let mut md5_input = Vec::with_capacity(32 + 32 + 4 + inputs.id0.len() + 4);
md5_input.extend_from_slice(&padded);
md5_input.extend_from_slice(inputs.o);
md5_input.extend_from_slice(&p_le);
md5_input.extend_from_slice(inputs.id0);
if inputs.r >= 4 && !inputs.encrypt_metadata {
md5_input.extend_from_slice(&[0xFF, 0xFF, 0xFF, 0xFF]);
}
let key_len = usize::try_from((inputs.length_bits / 8).min(16)).map_err(|_| {
crate::Error::System(format!(
"/Length {} is negative; encryption key length is out of range",
inputs.length_bits
))
})?;
let mut digest = md5(&md5_input);
if inputs.r >= 3 {
for _ in 0..50 {
digest = md5(&digest[..key_len]);
}
}
Ok(digest[..key_len].to_vec())
}
pub(crate) fn compute_file_key(
password: &[u8],
inputs: &StandardHandlerInputs<'_>,
) -> Result<Vec<u8>> {
let _n = validate_inputs(inputs)?;
compute_encryption_key_from_password(password, inputs)
}
pub(crate) fn compute_file_key_v4(
password: &[u8],
inputs: &StandardHandlerInputs<'_>,
) -> Result<Vec<u8>> {
let _n = validate_v4_inputs(inputs)?;
compute_encryption_key_from_password(password, inputs)
}
pub(crate) fn check_user_password_r5(
password: &[u8],
inputs: &StandardHandlerR5Inputs<'_>,
) -> Result<Vec<u8>> {
decrypt_r5_file_key(truncate_password_v5(password), inputs.u, inputs.ue, &[])
}
pub(crate) fn check_owner_password_r5(
password: &[u8],
inputs: &StandardHandlerR5Inputs<'_>,
) -> Result<Vec<u8>> {
decrypt_r5_file_key(
truncate_password_v5(password),
inputs.o,
inputs.oe,
inputs.u,
)
}
pub(crate) fn check_user_password_r6(
password: &[u8],
inputs: &StandardHandlerR5Inputs<'_>,
) -> Result<Vec<u8>> {
decrypt_r6_file_key(truncate_password_v5(password), inputs.u, inputs.ue, &[])
}
pub(crate) fn check_owner_password_r6(
password: &[u8],
inputs: &StandardHandlerR5Inputs<'_>,
) -> Result<Vec<u8>> {
decrypt_r6_file_key(
truncate_password_v5(password),
inputs.o,
inputs.oe,
inputs.u,
)
}
pub(crate) fn check_user_password(
password: &[u8],
inputs: &StandardHandlerInputs<'_>,
) -> Result<Vec<u8>> {
let file_key = compute_file_key(password, inputs)?;
if inputs.r == 2 {
let mut encrypted = PASSWORD_PADDING;
let mut cipher = Rc4::new(&file_key)?;
cipher.process_in_place(&mut encrypted);
if encrypted[..] != inputs.u[..] {
return Err(EncryptedError::BadPassword.into());
}
} else {
let mut md5_input = Vec::with_capacity(32 + inputs.id0.len());
md5_input.extend_from_slice(&PASSWORD_PADDING);
md5_input.extend_from_slice(inputs.id0);
let digest = md5(&md5_input);
let mut data = digest;
let mut cipher = Rc4::new(&file_key)?;
cipher.process_in_place(&mut data);
for i in 1_u8..=19 {
let xor_key: Vec<u8> = file_key.iter().map(|&byte| byte ^ i).collect();
let mut cipher = Rc4::new(&xor_key)?;
cipher.process_in_place(&mut data);
}
if data[..] != inputs.u[..16] {
return Err(EncryptedError::BadPassword.into());
}
}
Ok(file_key)
}
pub(crate) fn check_user_password_v4(
password: &[u8],
inputs: &StandardHandlerInputs<'_>,
) -> Result<Vec<u8>> {
let file_key = compute_file_key_v4(password, inputs)?;
let mut md5_input = Vec::with_capacity(32 + inputs.id0.len());
md5_input.extend_from_slice(&PASSWORD_PADDING);
md5_input.extend_from_slice(inputs.id0);
let digest = md5(&md5_input);
let mut data = digest;
let mut cipher = Rc4::new(&file_key)?;
cipher.process_in_place(&mut data);
for i in 1_u8..=19 {
let xor_key: Vec<u8> = file_key.iter().map(|&byte| byte ^ i).collect();
let mut cipher = Rc4::new(&xor_key)?;
cipher.process_in_place(&mut data);
}
if data[..] != inputs.u[..16] {
return Err(EncryptedError::BadPassword.into());
}
Ok(file_key)
}
pub(crate) fn check_owner_password(
password: &[u8],
inputs: &StandardHandlerInputs<'_>,
) -> Result<Vec<u8>> {
check_owner_password_with_user_password(password, inputs).map(|(file_key, _)| file_key)
}
pub(crate) fn check_owner_password_with_user_password(
password: &[u8],
inputs: &StandardHandlerInputs<'_>,
) -> Result<(Vec<u8>, Vec<u8>)> {
let n = validate_inputs(inputs)?;
let rc4_key = derive_owner_password_rc4_key(password, inputs.r, n);
let mut candidate = *inputs.o;
if inputs.r == 2 {
let mut cipher = Rc4::new(&rc4_key)?;
cipher.process_in_place(&mut candidate);
} else {
for i in (0_u8..=19).rev() {
let xor_key: Vec<u8> = rc4_key.iter().map(|&byte| byte ^ i).collect();
let mut cipher = Rc4::new(&xor_key)?;
cipher.process_in_place(&mut candidate);
}
}
let file_key = check_user_password(&candidate, inputs)?;
Ok((file_key, candidate.to_vec()))
}
pub(crate) fn check_owner_password_v4(
password: &[u8],
inputs: &StandardHandlerInputs<'_>,
) -> Result<Vec<u8>> {
check_owner_password_v4_with_user_password(password, inputs).map(|(file_key, _)| file_key)
}
pub(crate) fn check_owner_password_v4_with_user_password(
password: &[u8],
inputs: &StandardHandlerInputs<'_>,
) -> Result<(Vec<u8>, Vec<u8>)> {
let n = validate_v4_inputs(inputs)?;
let padded_owner = pad_password(password);
let mut digest = md5(&padded_owner);
for _ in 0..50 {
digest = md5(&digest);
}
let rc4_key = &digest[..n];
let mut candidate = *inputs.o;
for i in (0_u8..=19).rev() {
let xor_key: Vec<u8> = rc4_key.iter().map(|&byte| byte ^ i).collect();
let mut cipher = Rc4::new(&xor_key)?;
cipher.process_in_place(&mut candidate);
}
let file_key = check_user_password_v4(&candidate, inputs)?;
Ok((file_key, candidate.to_vec()))
}
pub(crate) fn trim_user_password(password: &[u8]) -> Vec<u8> {
if password.len() < PASSWORD_PADDING.len() {
return password.to_vec();
}
for index in 0..password.len() {
if password[index] == PASSWORD_PADDING[0]
&& password.len() - index <= PASSWORD_PADDING.len()
&& password[index..] == PASSWORD_PADDING[..password.len() - index]
{
return password[..index].to_vec();
}
}
password.to_vec()
}
pub(crate) struct V1V2EncryptParams<'a> {
pub v: i64,
pub r: i64,
pub length_bits: i64,
pub user_password: &'a [u8],
pub owner_password: &'a [u8],
pub p: i32,
pub id0: &'a [u8],
}
fn derive_owner_password_rc4_key(password: &[u8], r: i64, n: usize) -> Vec<u8> {
let padded = pad_password(password);
let mut digest = md5(&padded);
if r >= 3 {
for _ in 0..50 {
digest = md5(&digest);
}
}
digest[..n].to_vec()
}
fn compute_u_first_16_r3plus(file_key: &[u8], id0: &[u8]) -> Result<[u8; 16]> {
let mut md5_input = Vec::with_capacity(32 + id0.len());
md5_input.extend_from_slice(&PASSWORD_PADDING);
md5_input.extend_from_slice(id0);
let mut data = md5(&md5_input);
let mut cipher = Rc4::new(file_key)?;
cipher.process_in_place(&mut data);
for i in 1_u8..=19 {
let xor_key: Vec<u8> = file_key.iter().map(|&byte| byte ^ i).collect();
let mut cipher = Rc4::new(&xor_key)?;
cipher.process_in_place(&mut data);
}
Ok(data)
}
fn validate_v1_v2_params(params: &V1V2EncryptParams<'_>) -> Result<usize> {
let unsupported = || -> crate::error::Error {
EncryptedError::UnsupportedHandler {
filter: "Standard".into(),
v: params.v,
r: params.r,
cfm: None,
}
.into()
};
if params.v != 1 && params.v != 2 {
return Err(unsupported());
}
if params.r != 2 && params.r != 3 {
return Err(unsupported());
}
if params.v == 1 && (params.r != 2 || params.length_bits != 40) {
return Err(unsupported());
}
if params.r == 2 && params.length_bits != 40 {
return Err(unsupported());
}
if params.length_bits < 40 || params.length_bits > 128 || params.length_bits % 8 != 0 {
return Err(EncryptedError::Malformed {
reason: format!(
"/Length {} is invalid; must be a multiple of 8 between 40 and 128",
params.length_bits
),
}
.into());
}
Ok((params.length_bits / 8) as usize)
}
fn ensure_v_lt_5_revision(r: i64, entry: &str) -> Result<()> {
if matches!(r, 2..=4) {
Ok(())
} else {
Err(EncryptedError::Malformed {
reason: format!(
"/R {r} is unsupported for {entry} computation; expected one of 2, 3, 4"
),
}
.into())
}
}
pub(crate) fn compute_o_entry(
user_password: &[u8],
owner_password: &[u8],
r: i64,
n: usize,
) -> Result<[u8; 32]> {
ensure_v_lt_5_revision(r, "/O")?;
let effective_owner: &[u8] = if owner_password.is_empty() {
user_password
} else {
owner_password
};
let rc4_key = derive_owner_password_rc4_key(effective_owner, r, n);
let mut buf: [u8; 32] = pad_password(user_password);
if r == 2 {
let mut cipher = Rc4::new(&rc4_key)?;
cipher.process_in_place(&mut buf);
} else {
for i in 0_u8..=19 {
let xor_key: Vec<u8> = rc4_key.iter().map(|&byte| byte ^ i).collect();
let mut cipher = Rc4::new(&xor_key)?;
cipher.process_in_place(&mut buf);
}
}
Ok(buf)
}
pub(crate) fn compute_u_entry(file_key: &[u8], id0: &[u8], r: i64) -> Result<[u8; 32]> {
ensure_v_lt_5_revision(r, "/U")?;
if r == 2 {
let mut buf = PASSWORD_PADDING;
let mut cipher = Rc4::new(file_key)?;
cipher.process_in_place(&mut buf);
Ok(buf)
} else {
let first16 = compute_u_first_16_r3plus(file_key, id0)?;
let mut u = [0u8; 32];
u[..16].copy_from_slice(&first16);
for (i, byte) in u.iter_mut().enumerate().skip(16) {
*byte = u8::try_from((i * i) % 0xff).expect("(i * i) % 255 < 256");
}
Ok(u)
}
}
pub(crate) fn build_v1_v2_encrypt_dict(
params: &V1V2EncryptParams<'_>,
) -> Result<(ObjectHandle, Vec<u8>)> {
let n = validate_v1_v2_params(params)?;
let o_entry = compute_o_entry(params.user_password, params.owner_password, params.r, n)?;
let dummy_u = [0u8; 32];
let inputs = StandardHandlerInputs {
v: params.v,
r: params.r,
length_bits: params.length_bits,
p: params.p,
id0: params.id0,
u: &dummy_u,
o: &o_entry,
encrypt_metadata: true,
};
let file_key = compute_file_key(params.user_password, &inputs)?;
let u_entry = compute_u_entry(&file_key, params.id0, params.r)?;
let dict = ObjectHandle::dictionary(vec![
(b"Filter".to_vec(), ObjectHandle::name(b"Standard".to_vec())),
(b"V".to_vec(), ObjectHandle::integer(params.v)),
(b"R".to_vec(), ObjectHandle::integer(params.r)),
(
b"Length".to_vec(),
ObjectHandle::integer(params.length_bits),
),
(b"P".to_vec(), ObjectHandle::integer(i64::from(params.p))),
(b"U".to_vec(), ObjectHandle::string(u_entry.to_vec())),
(b"O".to_vec(), ObjectHandle::string(o_entry.to_vec())),
]);
Ok((dict, file_key))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum V4CryptMethod {
Rc4,
Aes,
}
impl V4CryptMethod {
fn cfm_name(self) -> &'static [u8] {
match self {
V4CryptMethod::Rc4 => b"V2",
V4CryptMethod::Aes => b"AESV2",
}
}
}
pub(crate) struct V4EncryptParams<'a> {
pub method: V4CryptMethod,
pub user_password: &'a [u8],
pub owner_password: &'a [u8],
pub p: i32,
pub id0: &'a [u8],
pub encrypt_metadata: bool,
}
pub(crate) fn build_v4_encrypt_dict(
params: &V4EncryptParams<'_>,
) -> Result<(ObjectHandle, Vec<u8>)> {
let n: usize = 16;
let o_entry = compute_o_entry(params.user_password, params.owner_password, 4, n)?;
let dummy_u = [0u8; 32];
let inputs = StandardHandlerInputs {
v: 4,
r: 4,
length_bits: 128,
p: params.p,
id0: params.id0,
u: &dummy_u,
o: &o_entry,
encrypt_metadata: params.encrypt_metadata,
};
let file_key = compute_file_key_v4(params.user_password, &inputs)?;
let u_entry = compute_u_entry(&file_key, params.id0, 4)?;
let std_cf = ObjectHandle::dictionary(vec![
(
b"AuthEvent".to_vec(),
ObjectHandle::name(b"DocOpen".to_vec()),
),
(
b"CFM".to_vec(),
ObjectHandle::name(params.method.cfm_name().to_vec()),
),
(b"Length".to_vec(), ObjectHandle::integer(16)),
]);
let cf = ObjectHandle::dictionary(vec![(b"StdCF".to_vec(), std_cf)]);
let mut entries = vec![
(b"CF".to_vec(), cf),
(b"Filter".to_vec(), ObjectHandle::name(b"Standard".to_vec())),
(b"Length".to_vec(), ObjectHandle::integer(128)),
(b"O".to_vec(), ObjectHandle::string(o_entry.to_vec())),
(b"P".to_vec(), ObjectHandle::integer(i64::from(params.p))),
(b"R".to_vec(), ObjectHandle::integer(4)),
(b"StmF".to_vec(), ObjectHandle::name(b"StdCF".to_vec())),
(b"StrF".to_vec(), ObjectHandle::name(b"StdCF".to_vec())),
(b"U".to_vec(), ObjectHandle::string(u_entry.to_vec())),
(b"V".to_vec(), ObjectHandle::integer(4)),
];
if !params.encrypt_metadata {
entries.push((b"EncryptMetadata".to_vec(), ObjectHandle::boolean(false)));
}
let dict = ObjectHandle::dictionary(entries);
Ok((dict, file_key))
}
pub(crate) fn compute_perms_blob(
p: i32,
encrypt_metadata: bool,
random_tail: &[u8; 4],
file_key: &[u8; 32],
) -> Result<[u8; 16]> {
let mut block = [0u8; 16];
block[0..4].copy_from_slice(&p.to_le_bytes());
block[4..8].copy_from_slice(&[0xFF; 4]);
block[8] = if encrypt_metadata { b'T' } else { b'F' };
block[9..12].copy_from_slice(b"adb");
block[12..16].copy_from_slice(random_tail);
let encrypted = PlAesPdf::process_to_vec_without_padding(
"AES /Perms encryption",
true,
&block,
file_key,
1,
None,
)?; Ok(encrypted
.try_into()
.expect("qpdf AES /Perms processing returns one encrypted block"))
}
fn aes256_cbc_zero_iv_wrap(file_key: &[u8; 32], aes_key: &[u8; 32]) -> Result<[u8; 32]> {
let ciphertext = PlAesPdf::process_to_vec_without_padding(
"AES V=5 file-key wrap",
true,
file_key,
aes_key,
1,
None,
)?; Ok(ciphertext
.try_into()
.expect("qpdf AES file-key wrapping returns two encrypted blocks"))
}
pub(crate) fn compute_u_ue_r6(
user_password: &[u8],
file_key: &[u8; 32],
validation_salt: &[u8; 8],
key_salt: &[u8; 8],
) -> Result<([u8; 48], [u8; 32])> {
let validation_hash = r6_password_hash(user_password, validation_salt, &[])?;
let aes_key = r6_password_hash(user_password, key_salt, &[])?;
let ue_entry = aes256_cbc_zero_iv_wrap(file_key, &aes_key)?;
let mut u_entry = [0u8; 48];
u_entry[0..32].copy_from_slice(&validation_hash);
u_entry[32..40].copy_from_slice(validation_salt);
u_entry[40..48].copy_from_slice(key_salt);
Ok((u_entry, ue_entry))
}
pub(crate) fn compute_o_oe_r6(
owner_password: &[u8],
user_entry: &[u8; 48],
file_key: &[u8; 32],
validation_salt: &[u8; 8],
key_salt: &[u8; 8],
) -> Result<([u8; 48], [u8; 32])> {
let validation_hash = r6_password_hash(owner_password, validation_salt, user_entry)?;
let aes_key = r6_password_hash(owner_password, key_salt, user_entry)?;
let oe_entry = aes256_cbc_zero_iv_wrap(file_key, &aes_key)?;
let mut o_entry = [0u8; 48];
o_entry[0..32].copy_from_slice(&validation_hash);
o_entry[32..40].copy_from_slice(validation_salt);
o_entry[40..48].copy_from_slice(key_salt);
Ok((o_entry, oe_entry))
}
pub(crate) struct V5R6EncryptParams<'a> {
pub user_password: &'a [u8],
pub owner_password: &'a [u8],
pub p: i32,
pub encrypt_metadata: bool,
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct V5R6Secrets {
pub file_key: [u8; 32],
pub user_validation_salt: [u8; 8],
pub user_key_salt: [u8; 8],
pub owner_validation_salt: [u8; 8],
pub owner_key_salt: [u8; 8],
pub perms_random_tail: [u8; 4],
}
pub(crate) fn build_v5_r6_encrypt_dict(
params: &V5R6EncryptParams<'_>,
secrets: &V5R6Secrets,
) -> Result<ObjectHandle> {
let (u_entry, ue_entry) = compute_u_ue_r6(
params.user_password,
&secrets.file_key,
&secrets.user_validation_salt,
&secrets.user_key_salt,
)?;
let (o_entry, oe_entry) = compute_o_oe_r6(
params.owner_password,
&u_entry,
&secrets.file_key,
&secrets.owner_validation_salt,
&secrets.owner_key_salt,
)?;
let perms = compute_perms_blob(
params.p,
params.encrypt_metadata,
&secrets.perms_random_tail,
&secrets.file_key,
)?;
let std_cf = ObjectHandle::dictionary(vec![
(
b"AuthEvent".to_vec(),
ObjectHandle::name(b"DocOpen".to_vec()),
),
(b"CFM".to_vec(), ObjectHandle::name(b"AESV3".to_vec())),
(b"Length".to_vec(), ObjectHandle::integer(32)),
]);
let cf = ObjectHandle::dictionary(vec![(b"StdCF".to_vec(), std_cf)]);
let mut entries = vec![
(b"CF".to_vec(), cf),
(b"Filter".to_vec(), ObjectHandle::name(b"Standard".to_vec())),
(b"Length".to_vec(), ObjectHandle::integer(256)),
(b"O".to_vec(), ObjectHandle::string(o_entry.to_vec())),
(b"OE".to_vec(), ObjectHandle::string(oe_entry.to_vec())),
(b"P".to_vec(), ObjectHandle::integer(i64::from(params.p))),
(b"Perms".to_vec(), ObjectHandle::string(perms.to_vec())),
(b"R".to_vec(), ObjectHandle::integer(6)),
(b"StmF".to_vec(), ObjectHandle::name(b"StdCF".to_vec())),
(b"StrF".to_vec(), ObjectHandle::name(b"StdCF".to_vec())),
(b"U".to_vec(), ObjectHandle::string(u_entry.to_vec())),
(b"UE".to_vec(), ObjectHandle::string(ue_entry.to_vec())),
(b"V".to_vec(), ObjectHandle::integer(5)),
];
if !params.encrypt_metadata {
entries.push((b"EncryptMetadata".to_vec(), ObjectHandle::boolean(false)));
}
Ok(ObjectHandle::dictionary(entries))
}
pub(crate) type V5R5Secrets = V5R6Secrets;
pub(crate) fn compute_u_ue_r5(
user_password: &[u8],
file_key: &[u8; 32],
validation_salt: &[u8; 8],
key_salt: &[u8; 8],
) -> Result<([u8; 48], [u8; 32])> {
let validation_hash = r5_salted_hash(user_password, validation_salt, &[])?;
let aes_key = r5_salted_hash(user_password, key_salt, &[])?;
let ue_entry = aes256_cbc_zero_iv_wrap(file_key, &aes_key)?;
let mut u_entry = [0u8; 48];
u_entry[0..32].copy_from_slice(&validation_hash);
u_entry[32..40].copy_from_slice(validation_salt);
u_entry[40..48].copy_from_slice(key_salt);
Ok((u_entry, ue_entry))
}
pub(crate) fn compute_o_oe_r5(
owner_password: &[u8],
user_entry: &[u8; 48],
file_key: &[u8; 32],
validation_salt: &[u8; 8],
key_salt: &[u8; 8],
) -> Result<([u8; 48], [u8; 32])> {
let validation_hash = r5_salted_hash(owner_password, validation_salt, user_entry)?;
let aes_key = r5_salted_hash(owner_password, key_salt, user_entry)?;
let oe_entry = aes256_cbc_zero_iv_wrap(file_key, &aes_key)?;
let mut o_entry = [0u8; 48];
o_entry[0..32].copy_from_slice(&validation_hash);
o_entry[32..40].copy_from_slice(validation_salt);
o_entry[40..48].copy_from_slice(key_salt);
Ok((o_entry, oe_entry))
}
pub(crate) fn build_v5_r5_encrypt_dict(
params: &V5R6EncryptParams<'_>,
secrets: &V5R5Secrets,
) -> Result<ObjectHandle> {
let (u_entry, ue_entry) = compute_u_ue_r5(
params.user_password,
&secrets.file_key,
&secrets.user_validation_salt,
&secrets.user_key_salt,
)?;
let (o_entry, oe_entry) = compute_o_oe_r5(
params.owner_password,
&u_entry,
&secrets.file_key,
&secrets.owner_validation_salt,
&secrets.owner_key_salt,
)?;
let std_cf = ObjectHandle::dictionary(vec![
(
b"AuthEvent".to_vec(),
ObjectHandle::name(b"DocOpen".to_vec()),
),
(b"CFM".to_vec(), ObjectHandle::name(b"AESV3".to_vec())),
(b"Length".to_vec(), ObjectHandle::integer(32)),
]);
let cf = ObjectHandle::dictionary(vec![(b"StdCF".to_vec(), std_cf)]);
let perms = compute_perms_blob(
params.p,
params.encrypt_metadata,
&secrets.perms_random_tail,
&secrets.file_key,
)?;
let mut entries = vec![
(b"CF".to_vec(), cf),
(b"Filter".to_vec(), ObjectHandle::name(b"Standard".to_vec())),
(b"Length".to_vec(), ObjectHandle::integer(256)),
(b"O".to_vec(), ObjectHandle::string(o_entry.to_vec())),
(b"OE".to_vec(), ObjectHandle::string(oe_entry.to_vec())),
(b"P".to_vec(), ObjectHandle::integer(i64::from(params.p))),
(b"Perms".to_vec(), ObjectHandle::string(perms.to_vec())),
(b"R".to_vec(), ObjectHandle::integer(5)),
(b"StmF".to_vec(), ObjectHandle::name(b"StdCF".to_vec())),
(b"StrF".to_vec(), ObjectHandle::name(b"StdCF".to_vec())),
(b"U".to_vec(), ObjectHandle::string(u_entry.to_vec())),
(b"UE".to_vec(), ObjectHandle::string(ue_entry.to_vec())),
(b"V".to_vec(), ObjectHandle::integer(5)),
];
if !params.encrypt_metadata {
entries.push((b"EncryptMetadata".to_vec(), ObjectHandle::boolean(false)));
}
Ok(ObjectHandle::dictionary(entries))
}
#[derive(Debug, Clone, Copy)]
pub(crate) enum StringCipher<'a> {
Identity,
Rc4 { key: &'a [u8] },
Aes128 { key: &'a [u8; 16] },
Aes192 { key: &'a [u8; 24] },
Aes256 { key: &'a [u8; 32] },
}
pub(crate) fn decrypt_cipher_bytes(bytes: &mut Vec<u8>, cipher: StringCipher<'_>) -> Result<()> {
match cipher {
StringCipher::Identity => Ok(()),
StringCipher::Rc4 { key } => {
let mut cipher = Rc4::new(key)?;
cipher.process_in_place(bytes);
Ok(())
}
StringCipher::Aes128 { key } => {
*bytes = PlAesPdf::decrypt_to_vec("AES string decryption", bytes, key)?;
Ok(())
}
StringCipher::Aes192 { key } => {
*bytes = PlAesPdf::decrypt_to_vec("AES string decryption", bytes, key)?;
Ok(())
}
StringCipher::Aes256 { key } => {
*bytes = PlAesPdf::decrypt_to_vec("AES string decryption", bytes, key)?;
Ok(())
}
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) enum StringEncryptCipher<'a> {
Identity,
Rc4 { key: &'a [u8] },
Aes128 { key: &'a [u8; 16] },
Aes256 { key: &'a [u8; 32] },
}
pub(crate) fn encrypt_cipher_bytes(
bytes: &mut Vec<u8>,
cipher: StringEncryptCipher<'_>,
iv: &[u8; 16],
) -> Result<()> {
match cipher {
StringEncryptCipher::Identity => Ok(()),
StringEncryptCipher::Rc4 { key } => {
let mut cipher = Rc4::new(key)?;
cipher.process_in_place(bytes);
Ok(())
}
StringEncryptCipher::Aes128 { key } => {
let encrypted =
PlAesPdf::encrypt_to_vec_with_iv("AES-128 string encryption", bytes, key, iv)?;
bytes.clear();
bytes.extend_from_slice(iv);
bytes.extend_from_slice(&encrypted);
Ok(())
}
StringEncryptCipher::Aes256 { key } => {
let encrypted =
PlAesPdf::encrypt_to_vec_with_iv("AES-256 string encryption", bytes, key, iv)?;
bytes.clear();
bytes.extend_from_slice(iv);
bytes.extend_from_slice(&encrypted);
Ok(())
}
}
}
#[cfg(test)]
mod v5_dictionary_tests {
use super::{build_v5_r5_encrypt_dict, V5R5Secrets, V5R6EncryptParams};
#[test]
fn v5_r5_dictionary_emits_encrypt_metadata_false() {
let secrets = V5R5Secrets {
file_key: [1; 32],
user_validation_salt: [2; 8],
user_key_salt: [3; 8],
owner_validation_salt: [4; 8],
owner_key_salt: [5; 8],
perms_random_tail: [6; 4],
};
let params = V5R6EncryptParams {
user_password: b"user",
owner_password: b"owner",
p: -4,
encrypt_metadata: false,
};
let dictionary = build_v5_r5_encrypt_dict(¶ms, &secrets).expect("valid V=5 R=5 data");
assert_eq!(
dictionary
.try_get_key(b"/EncryptMetadata")
.expect("dictionary lookup")
.as_boolean(),
Some(false)
);
}
}
#[cfg(test)]
mod v1_v2_reader_tests {
use super::{check_user_password, StandardHandlerInputs};
#[test]
fn v1_r3_uses_qpdf_r3_key_derivation_with_a_40_bit_key() {
let id0 = [
0xdd, 0x22, 0x11, 0x51, 0x71, 0xe3, 0x2b, 0x2c, 0x97, 0x7f, 0x0d, 0x40, 0xd4, 0x5c,
0x99, 0x72,
];
let o = [
0xd8, 0x03, 0xdb, 0xa0, 0x8a, 0xc8, 0xe1, 0x91, 0xd7, 0x89, 0x88, 0xa6, 0x74, 0xbd,
0x14, 0xb8, 0x18, 0x01, 0xc4, 0xa2, 0xac, 0x82, 0xde, 0x11, 0x52, 0x5b, 0x69, 0xac,
0x42, 0xf0, 0x45, 0x89,
];
let u = [
0x16, 0xa5, 0xf5, 0xd4, 0xa6, 0x3a, 0x2c, 0xd3, 0x26, 0x55, 0x24, 0xfa, 0x22, 0x48,
0x46, 0x60, 0x28, 0xbf, 0x4e, 0x5e, 0x4e, 0x75, 0x8a, 0x41, 0x64, 0x00, 0x4e, 0x56,
0xff, 0xfa, 0x01, 0x08,
];
let inputs = StandardHandlerInputs {
v: 1,
r: 3,
length_bits: 40,
p: -12,
id0: &id0,
u: &u,
o: &o,
encrypt_metadata: true,
};
let file_key = check_user_password(b"623", &inputs)
.expect("qpdf accepts Standard V=1/R=3 with a 40-bit key");
assert_eq!(file_key, [0xe3, 0x90, 0xe2, 0x20, 0xda]);
}
#[test]
fn v1_rejects_an_inconsistent_non_40_bit_internal_projection() {
let id0 = [0xdd; 16];
let o = [0xd8; 32];
let u = [0x16; 32];
let inputs = StandardHandlerInputs {
v: 1,
r: 3,
length_bits: 128,
p: -12,
id0: &id0,
u: &u,
o: &o,
encrypt_metadata: true,
};
let error = check_user_password(b"623", &inputs)
.expect_err("V=1 must retain qpdf's fixed 40-bit effective length");
assert!(matches!(
error,
crate::Error::Encrypted(crate::error::EncryptedError::UnsupportedHandler {
v: 1,
r: 3,
..
})
));
}
}
#[cfg(test)]
mod copy_writer_key_derivation_tests {
use super::{
compute_encryption_key_from_password, v_lt_5_32_byte_parameter, StandardHandlerInputs,
};
const DONOR_O: [u8; 32] = [
0x2a, 0x2f, 0x0a, 0x19, 0x90, 0x19, 0x2c, 0x60, 0x11, 0x47, 0x30, 0xbd, 0xcd, 0x39, 0xf3,
0x78, 0x28, 0xa5, 0x3c, 0x89, 0xa3, 0x40, 0xdd, 0x47, 0x3c, 0x85, 0x29, 0x9d, 0xc5, 0x25,
0x8e, 0x1c,
];
const STATIC_ID0: [u8; 16] = [
0x31, 0x41, 0x59, 0x26, 0x53, 0x58, 0x97, 0x93, 0x23, 0x84, 0x62, 0x64, 0x33, 0x83, 0x27,
0x95,
];
fn inputs(r: i64, length_bits: i64, encrypt_metadata: bool) -> StandardHandlerInputs<'static> {
static U: [u8; 32] = [0; 32];
StandardHandlerInputs {
v: 4,
r,
length_bits,
p: -4,
id0: &STATIC_ID0,
u: &U,
o: &DONOR_O,
encrypt_metadata,
}
}
#[test]
fn short_length_matches_the_qpdf_derived_key() {
let key = compute_encryption_key_from_password(b"u", &inputs(4, 40, true))
.expect("a positive /Length derives a key");
assert_eq!(key, [0x46, 0x07, 0x82, 0xd6, 0x66]);
}
#[test]
fn oversized_length_is_clamped_to_the_digest_size() {
let clamped = compute_encryption_key_from_password(b"u", &inputs(3, 240, true))
.expect("an oversized /Length is clamped");
let digest_sized = compute_encryption_key_from_password(b"u", &inputs(3, 128, true))
.expect("a 128-bit /Length derives a key");
assert_eq!(clamped.len(), 16);
assert_eq!(clamped, digest_sized);
}
#[test]
fn zero_length_derives_an_empty_key() {
let key = compute_encryption_key_from_password(b"u", &inputs(3, 0, true))
.expect("a zero /Length derives an empty key");
assert!(key.is_empty());
}
#[test]
fn revision_two_skips_the_iteration_loop() {
let r2 = compute_encryption_key_from_password(b"u", &inputs(2, 40, true))
.expect("R=2 derives a key");
let r3 = compute_encryption_key_from_password(b"u", &inputs(3, 40, true))
.expect("R=3 derives a key");
assert_eq!(r2.len(), 5);
assert_ne!(r2, r3);
}
#[test]
fn cleartext_metadata_changes_the_key_from_revision_four() {
let encrypted = compute_encryption_key_from_password(b"u", &inputs(4, 128, true))
.expect("R=4 derives a key");
let cleartext = compute_encryption_key_from_password(b"u", &inputs(4, 128, false))
.expect("R=4 derives a key");
assert_ne!(encrypted, cleartext);
assert_eq!(
compute_encryption_key_from_password(b"u", &inputs(3, 128, true))
.expect("R=3 derives a key"),
compute_encryption_key_from_password(b"u", &inputs(3, 128, false))
.expect("R=3 derives a key")
);
}
#[test]
fn negative_length_is_out_of_range() {
let error = compute_encryption_key_from_password(b"u", &inputs(3, -8, true))
.expect_err("a negative /Length has no key length");
assert!(
matches!(&error, crate::Error::System(message) if message.contains("-8")),
"unexpected error: {error}"
);
}
#[test]
fn parameter_projection_truncates_and_pads() {
assert_eq!(v_lt_5_32_byte_parameter(&[0xab; 40]), [0xab; 32]);
let short = v_lt_5_32_byte_parameter(&[0xcd; 3]);
assert_eq!(&short[..3], &[0xcd; 3]);
assert_eq!(&short[3..], &[0; 29]);
}
}