(options: ProtectionOptions)
| 47 | * @returns Generated encryption data |
| 48 | */ |
| 49 | export function generateEncryption(options: ProtectionOptions): GeneratedEncryption { |
| 50 | // Only support AES-256 for new encryption |
| 51 | const algorithm = options.algorithm ?? "AES-256"; |
| 52 | |
| 53 | if (algorithm !== "AES-256") { |
| 54 | throw new Error(`Only AES-256 encryption is supported for new documents. Got: ${algorithm}`); |
| 55 | } |
| 56 | |
| 57 | // Encode passwords to UTF-8 |
| 58 | const userPassword = new TextEncoder().encode(options.userPassword ?? ""); |
| 59 | const ownerPassword = new TextEncoder().encode(options.ownerPassword ?? generateRandomPassword()); |
| 60 | |
| 61 | // Merge permissions with defaults (omitted = true) |
| 62 | const permissions: Permissions = { |
| 63 | ...DEFAULT_PERMISSIONS, |
| 64 | ...options.permissions, |
| 65 | }; |
| 66 | |
| 67 | // Encode permissions as /P value |
| 68 | const permissionsRaw = encodePermissions(permissions); |
| 69 | |
| 70 | const encryptMetadata = options.encryptMetadata ?? true; |
| 71 | |
| 72 | // Generate random 32-byte file encryption key |
| 73 | const fileEncryptionKey = randomBytes(32); |
| 74 | |
| 75 | // Generate user entries (/U and /UE) |
| 76 | const { u, ue } = generateUserEntries(userPassword, fileEncryptionKey, 6); |
| 77 | |
| 78 | // Generate owner entries (/O and /OE) - needs /U for hash |
| 79 | const { o, oe } = generateOwnerEntries(ownerPassword, fileEncryptionKey, u, 6); |
| 80 | |
| 81 | // Generate /Perms entry |
| 82 | const perms = generatePermsEntry(fileEncryptionKey, permissionsRaw, encryptMetadata); |
| 83 | |
| 84 | // Generate file ID (two random 16-byte values) |
| 85 | const id1 = randomBytes(16); |
| 86 | const id2 = randomBytes(16); |
| 87 | const fileId: [Uint8Array, Uint8Array] = [id1, id2]; |
| 88 | |
| 89 | // Build encryption dictionary |
| 90 | const encryptDict = PdfDict.of({ |
| 91 | Filter: PdfName.of("Standard"), |
| 92 | V: PdfNumber.of(5), |
| 93 | R: PdfNumber.of(6), |
| 94 | Length: PdfNumber.of(256), |
| 95 | O: PdfString.fromBytes(o), |
| 96 | U: PdfString.fromBytes(u), |
| 97 | OE: PdfString.fromBytes(oe), |
| 98 | UE: PdfString.fromBytes(ue), |
| 99 | P: PdfNumber.of(permissionsRaw), |
| 100 | Perms: PdfString.fromBytes(perms), |
| 101 | // Crypt filters for AES-256 |
| 102 | CF: PdfDict.of({ |
| 103 | StdCF: PdfDict.of({ |
| 104 | CFM: PdfName.of("AESV3"), |
| 105 | AuthEvent: PdfName.of("DocOpen"), |
| 106 | Length: PdfNumber.of(32), |
no test coverage detected