(dict: PdfDict)
| 204 | * @throws {EncryptionDictError} if the dictionary is invalid or unsupported |
| 205 | */ |
| 206 | export function parseEncryptionDict(dict: PdfDict): EncryptionDict { |
| 207 | // Check filter - must be "Standard" (we don't support other handlers) |
| 208 | const filter = dict.getName("Filter")?.value; |
| 209 | |
| 210 | if (filter !== "Standard") { |
| 211 | throw new EncryptionDictError( |
| 212 | filter |
| 213 | ? `Unsupported security handler: ${filter}` |
| 214 | : "Missing /Filter in encryption dictionary", |
| 215 | ); |
| 216 | } |
| 217 | |
| 218 | // Parse and validate version and revision using Zod |
| 219 | const version = parseVersion(dict); |
| 220 | const revision = parseRevision(dict); |
| 221 | |
| 222 | // Validate V/R compatibility |
| 223 | validateVersionRevision(version, revision); |
| 224 | |
| 225 | // Parse key length |
| 226 | let keyLengthBits = dict.getNumber("Length")?.value ?? 40; |
| 227 | |
| 228 | // V1 is always 40-bit |
| 229 | if (version === 1) { |
| 230 | keyLengthBits = 40; |
| 231 | } |
| 232 | // V5 (R5-R6) is always 256-bit |
| 233 | else if (version === 5) { |
| 234 | keyLengthBits = 256; |
| 235 | } |
| 236 | |
| 237 | // Validate key length |
| 238 | if (keyLengthBits < 40 || keyLengthBits > 256 || keyLengthBits % 8 !== 0) { |
| 239 | throw new EncryptionDictError(`Invalid key length: ${keyLengthBits} bits`); |
| 240 | } |
| 241 | |
| 242 | // Parse owner hash (O) |
| 243 | const ownerHash = dict.getString("O")?.bytes; |
| 244 | |
| 245 | if (!ownerHash) { |
| 246 | throw new EncryptionDictError("Missing /O (owner hash) in encryption dictionary"); |
| 247 | } |
| 248 | |
| 249 | // Validate O length based on revision |
| 250 | // R2-R4: exactly 32 bytes |
| 251 | // R5-R6: at least 48 bytes (32 hash + 8 validation salt + 8 key salt), may be padded |
| 252 | if (revision >= 5) { |
| 253 | if (ownerHash.length < 48) { |
| 254 | throw new EncryptionDictError( |
| 255 | `Invalid /O length: expected at least 48 bytes, got ${ownerHash.length}`, |
| 256 | ); |
| 257 | } |
| 258 | } else { |
| 259 | if (ownerHash.length !== 32) { |
| 260 | throw new EncryptionDictError( |
| 261 | `Invalid /O length: expected 32 bytes, got ${ownerHash.length}`, |
| 262 | ); |
| 263 | } |
no test coverage detected