use sha2::{Digest, Sha256, Sha384, Sha512};
use super::aes::{BLOCK_LEN, encrypt_cbc_128_nopad};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum A13Reading {
#[default]
PerformThenTest,
TestThenPerform,
}
#[must_use]
pub fn hash_2b(
input_string: &[u8],
password: &[u8],
u: Option<&[u8]>,
reading: A13Reading,
) -> [u8; 32] {
let mut k: Vec<u8> = Sha256::digest(input_string).to_vec();
let u = u.unwrap_or(&[]);
let mut round: u64 = 0;
loop {
let k0_len = password.len() + k.len() + u.len();
let mut k1 = Vec::with_capacity(64 * k0_len);
for _ in 0..64 {
k1.extend_from_slice(password);
k1.extend_from_slice(&k);
k1.extend_from_slice(u);
}
let key: [u8; BLOCK_LEN] = k
.get(0..BLOCK_LEN)
.and_then(|s| s.try_into().ok())
.unwrap_or([0u8; BLOCK_LEN]);
let iv: [u8; BLOCK_LEN] = k
.get(BLOCK_LEN..2 * BLOCK_LEN)
.and_then(|s| s.try_into().ok())
.unwrap_or([0u8; BLOCK_LEN]);
let e = encrypt_cbc_128_nopad(&key, &iv, &k1);
let selector = e
.get(0..BLOCK_LEN)
.unwrap_or(&[])
.iter()
.map(|&b| u32::from(b))
.sum::<u32>()
% 3;
k = match selector {
0 => Sha256::digest(&e).to_vec(),
1 => Sha384::digest(&e).to_vec(),
_ => Sha512::digest(&e).to_vec(),
};
round += 1;
if round < 64 {
continue;
}
let last = e.last().copied().map_or(0u64, u64::from);
match reading {
A13Reading::PerformThenTest => {
if round >= 64 && last <= round.saturating_sub(32) {
break;
}
}
A13Reading::TestThenPerform => {
if last <= round.saturating_sub(32) {
break;
}
}
}
}
k.get(0..32)
.and_then(|s| s.try_into().ok())
.unwrap_or([0u8; 32])
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
use super::*;
#[test]
fn matches_pypdf_u_hash() {
const UVS: [u8; 8] = [0x01, 0x97, 0x09, 0x8a, 0x4a, 0xd9, 0x3b, 0x0f];
const U32: [u8; 32] = [
0xcb, 0xd1, 0xd9, 0x07, 0xe3, 0x92, 0x37, 0xfd, 0xb0, 0x0f, 0xdf, 0xc8, 0x57, 0x8c,
0xd8, 0xe9, 0x02, 0x96, 0xd5, 0xbb, 0xef, 0xb9, 0x70, 0xc9, 0xd8, 0x35, 0xf1, 0xd3,
0x36, 0x89, 0xe1, 0x01,
];
let pw = b"user";
let mut input = pw.to_vec();
input.extend_from_slice(&UVS);
let got = hash_2b(&input, pw, None, A13Reading::PerformThenTest);
assert_eq!(got, U32, "PerformThenTest");
}
#[test]
fn the_two_readings_can_differ_and_are_each_deterministic() {
let a = hash_2b(
b"password\x00\x01salt",
b"password",
None,
A13Reading::PerformThenTest,
);
let b = hash_2b(
b"password\x00\x01salt",
b"password",
None,
A13Reading::PerformThenTest,
);
assert_eq!(a, b);
assert_ne!(a, [0u8; 32]);
}
#[test]
fn the_owner_u_string_changes_the_result() {
let no_u = hash_2b(b"pw" as &[u8], b"pw", None, A13Reading::default());
let with_u = hash_2b(
b"pw" as &[u8],
b"pw",
Some(&[7u8; 48]),
A13Reading::default(),
);
assert_ne!(no_u, with_u, "U on the owner path must feed K0");
}
}