Skip to content

Шифрування та безпека

PDF Oxide підтримує шифрування PDF з паролями та правами доступу за галузевими стандартами. Ви можете задати пароль користувача (потрібний для відкриття документа), пароль власника (потрібний для повного доступу), а також детальні права, що керують друком, копіюванням і редагуванням.

Підтримка прив’язок. Відкриття зашифрованих PDF працює в усіх прив’язках (password= у Python, PdfDocument.open_with_password у Rust, authenticate() у WASM, Authenticate у PdfDocument Go/C#, OpenWithPassword у C#). Генерування зашифрованих виводів (save_encrypted / saveEncryptedToBytes) доступне в Python, Rust, WASM і Go (DocumentEditor.SaveEncrypted). DocumentEditor у C# наразі не надає SaveEncrypted — для створення зашифрованого виводу в C#-робочих процесах використовуйте CLI Rust (pdf-oxide encrypt) або крок на Go/Python.

Підтримка алгоритмів

Алгоритм Читання Запис Примітки
RC4 (40/128 біт) Так Так Застарілий; використовуйте лише для сумісності
AES-128 (V=4, R=4) Так Так Стандарт для PDF 1.6+
AES-256 (V=5, R=6) Так Так PDF 2.0; включає розшифрування рядків у нестиснутих об’єктах, підписи кнопок-віджетів /MK /CA і правильне завершення Algorithm 2.B

Підтримка AES-256 повна від початку до кінця: відкриття, автентифікація, зчитування значень форм і збереження зашифрованого виводу. Потоки ObjStm / XRef не шифруються відповідно до ISO 32000-2 §7.6.3. Після запізнілого виклику authenticate() кеш об’єктів правильно анулюється, тому будь-який вміст, прочитаний до автентифікації, повторно розбирається з правильним ключем.

Швидкий старт: збереження з шифруванням

Python

from pdf_oxide import PdfDocument

doc = PdfDocument("input.pdf")
doc.set_title("Confidential Report")

# Encrypt with user and owner passwords
doc.save_encrypted("protected.pdf", "user123", "owner456")

WASM

import { WasmPdfDocument } from "pdf-oxide-wasm";

const doc = new WasmPdfDocument(bytes);
doc.setTitle("Confidential Report");

// Encrypt with user and owner passwords (all permissions enabled)
const output = doc.saveEncryptedToBytes(
  "user123", "owner456", true, true, true, true
);
doc.free();

Rust

use pdf_oxide::api::Pdf;

let mut doc = Pdf::open("input.pdf")?;

// Simple encryption with user and owner passwords
doc.save_encrypted("protected.pdf", "user123", "owner456")?;

Go

package main

import (
    "log"
    pdfoxide "github.com/yfedoseev/pdf_oxide/go"
)

func main() {
    editor, err := pdfoxide.OpenEditor("input.pdf")
    if err != nil { log.Fatal(err) }
    defer editor.Close()

    _ = editor.SetTitle("Confidential Report")

    // Encrypt with user and owner passwords (AES-256)
    if err := editor.SaveEncrypted("protected.pdf", "user123", "owner456"); err != nil {
        log.Fatal(err)
    }
}

C++

#include <pdf_oxide/pdf_oxide.hpp>

auto editor = pdf_oxide::DocumentEditor::open("input.pdf");

// Encrypt with user and owner passwords (AES-256)
editor.save_encrypted("protected.pdf", "user123", "owner456");

Swift

import PdfOxide

let editor = try DocumentEditor.openEditor("input.pdf")

// Encrypt with user and owner passwords (AES-256)
try editor.saveEncrypted("protected.pdf", userPassword: "user123", ownerPassword: "owner456")

Dart

import 'package:pdf_oxide/pdf_oxide.dart';

final editor = DocumentEditor.open('input.pdf');

// Encrypt with user and owner passwords (AES-256)
editor.saveEncrypted('protected.pdf', 'user123', 'owner456');
editor.close();

R

library(pdfoxide)

editor <- pdf_editor_open("input.pdf")

# Encrypt with user and owner passwords (AES-256)
pdf_editor_save_encrypted(editor, "protected.pdf", "user123", "owner456")

Julia

using PdfOxide

editor = open_editor("input.pdf")

# Encrypt with user and owner passwords (AES-256)
save_encrypted(editor, "protected.pdf", "user123", "owner456")

Zig

const pdf_oxide = @import("pdf_oxide");

var editor = try pdf_oxide.DocumentEditor.openEditor("input.pdf");
defer editor.deinit();

// Encrypt with user and owner passwords (AES-256)
try editor.saveEncrypted("protected.pdf", "user123", "owner456");

Objective-C

#import "POXPdfOxide.h"
NSError *err = nil;

POXDocumentEditor *editor = [POXDocumentEditor openEditor:@"input.pdf" error:&err];

// Encrypt with user and owner passwords (AES-256)
[editor saveEncryptedToPath:@"protected.pdf"
               userPassword:@"user123"
              ownerPassword:@"owner456"
                      error:&err];

Elixir

{:ok, editor} = PdfOxide.open_editor("input.pdf")

# Encrypt with user and owner passwords (AES-256)
:ok = PdfOxide.editor_save_encrypted(editor, "protected.pdf", "user123", "owner456")

Шифрування з користувацькими правами

Python

Метод save_encrypted приймає прапорці прав як іменовані аргументи.

from pdf_oxide import PdfDocument

doc = PdfDocument("input.pdf")

# View-only: no printing, copying, or modifying
doc.save_encrypted(
    "readonly.pdf",
    "viewpass",
    "adminpass",
    allow_print=False,
    allow_copy=False,
    allow_modify=False,
    allow_annotate=False,
)

# Allow only printing
doc.save_encrypted(
    "print-only.pdf",
    "",            # No open password required
    "adminpass",
    allow_print=True,
    allow_copy=False,
    allow_modify=False,
    allow_annotate=False,
)

Параметри Python save_encrypted

Параметр Тип За замовчуванням Опис
path str обов’язковий Шлях до вихідного файлу
user_password str обов’язковий Пароль для відкриття (порожній рядок = без пароля)
owner_password str None Пароль повного доступу (за замовчуванням = пароль користувача)
allow_print bool True Дозволити друк
allow_copy bool True Дозволити копіювання тексту/графіки
allow_modify bool True Дозволити змінення документа
allow_annotate bool True Дозволити додавання анотацій

WASM

import { WasmPdfDocument } from "pdf-oxide-wasm";

const doc = new WasmPdfDocument(bytes);

// View-only: no printing, copying, or modifying
const readonly = doc.saveEncryptedToBytes(
  "viewpass", "adminpass", false, false, false, false
);

// Allow only printing (empty user password = no open password)
const printOnly = doc.saveEncryptedToBytes(
  "", "adminpass", true, false, false, false
);
doc.free();

Rust

Для повного контролю над параметрами шифрування використовуйте EncryptionConfig і SaveOptions.

use pdf_oxide::api::Pdf;
use pdf_oxide::editor::{
    EncryptionConfig, EncryptionAlgorithm, Permissions, SaveOptions,
};

let mut doc = Pdf::open("input.pdf")?;

// Build permissions
let mut perms = Permissions::read_only();
perms.print = true;  // Allow printing only

// Build encryption config
let config = EncryptionConfig::new("user123", "owner456")
    .with_algorithm(EncryptionAlgorithm::Aes256)
    .with_permissions(perms);

// Save with encryption
doc.save_with_encryption("protected.pdf", config)?;

EncryptionConfig

Структура EncryptionConfig керує всіма параметрами шифрування.

use pdf_oxide::editor::{EncryptionConfig, EncryptionAlgorithm, Permissions};

let config = EncryptionConfig {
    user_password: "user123".to_string(),
    owner_password: "owner456".to_string(),
    algorithm: EncryptionAlgorithm::Aes256,
    permissions: Permissions::all(),
};

Або з використанням паттерну будівника:

let config = EncryptionConfig::new("user123", "owner456")
    .with_algorithm(EncryptionAlgorithm::Aes128)
    .with_permissions(Permissions::read_only());

Поля EncryptionConfig

Поле Тип Опис
user_password String Пароль для відкриття документа
owner_password String Пароль для повного доступу та зміни параметрів безпеки
algorithm EncryptionAlgorithm Алгоритм шифрування, що використовується
permissions Permissions Прапорці контролю доступу

Алгоритми шифрування

Алгоритм Опис
EncryptionAlgorithm::Aes256 AES-256 (найнадійніший, рекомендований)
EncryptionAlgorithm::Aes128 AES-128
EncryptionAlgorithm::Rc4_128 RC4 128 біт (сумісність із застарілими системами)
EncryptionAlgorithm::Rc4_40 RC4 40 біт (застарілий, слабкий)

При використанні save_encrypted() у Python або API Pdf за замовчуванням застосовується AES-256.

Права доступу (Permissions)

Структура Permissions керує операціями, що дозволені при відкритті документа з паролем користувача.

use pdf_oxide::editor::Permissions;

// Allow everything
let all = Permissions::all();

// Restrict everything
let readonly = Permissions::read_only();

Поля Permissions

Поле Тип За замовчуванням (all) За замовчуванням (read_only) Опис
print bool true false Дозволити друк
print_high_quality bool true false Дозволити друк високої якості
modify bool true false Дозволити змінення вмісту
copy bool true false Дозволити копіювання тексту/графіки
annotate bool true false Дозволити додавання анотацій
fill_forms bool true false Дозволити заповнення полів форм
accessibility bool true true Дозволити вилучення для доступності
assemble bool true false Дозволити операції складання сторінок

Користувацькі права

let mut perms = Permissions::read_only();
perms.print = true;          // Allow printing
perms.fill_forms = true;     // Allow filling forms
perms.accessibility = true;  // Always allow for compliance

SaveOptions

Використовуйте SaveOptions для повного контролю над тим, як записується документ.

use pdf_oxide::editor::{SaveOptions, EncryptionConfig};

// Full rewrite (default)
let opts = SaveOptions::full_rewrite();

// Incremental update (faster, preserves structure)
let opts = SaveOptions::incremental();

// With encryption
let config = EncryptionConfig::new("user", "owner");
let opts = SaveOptions::with_encryption(config);

Відкриття зашифрованих PDF

Python

Передайте пароль при відкритті документа.

from pdf_oxide import PdfDocument

doc = PdfDocument("protected.pdf", password="user123")
text = doc.extract_text(0)
print(text)

Rust

use pdf_oxide::PdfDocument;

let doc = PdfDocument::open_with_password("protected.pdf", "user123")?;
let text = doc.extract_text(0)?;
println!("{}", text);

Go

doc, _ := pdfoxide.Open("protected.pdf")
defer doc.Close()
if _, err := doc.Authenticate("user123"); err != nil { log.Fatal(err) }
text, _ := doc.ExtractText(0)
fmt.Println(text)

C#

using var doc = PdfDocument.OpenWithPassword("protected.pdf", "user123");
Console.WriteLine(doc.ExtractText(0));

C++

#include <pdf_oxide/pdf_oxide.hpp>
#include <iostream>

auto doc = pdf_oxide::Document::open_with_password("protected.pdf", "user123");
std::cout << doc.extract_text(0) << std::endl;

Swift

import PdfOxide

let doc = try Document.openWithPassword("protected.pdf", password: "user123")
print(try doc.extractText(0))

Dart

import 'package:pdf_oxide/pdf_oxide.dart';

final doc = PdfDocument.openWithPassword('protected.pdf', 'user123');
print(doc.extractText(0));
doc.close();

R

library(pdfoxide)

doc <- pdf_open_with_password("protected.pdf", "user123")
cat(pdf_extract_text(doc, 0))

Julia

using PdfOxide

doc = open_with_password("protected.pdf", "user123")
println(extract_text(doc, 0))

Zig

const std = @import("std");
const pdf_oxide = @import("pdf_oxide");
const a = std.heap.page_allocator;

var doc = try pdf_oxide.Document.openWithPassword("protected.pdf", "user123");
defer doc.deinit();
const text = try doc.extractText(a, 0);
std.debug.print("{s}\n", .{text});

Objective-C

#import "POXPdfOxide.h"
NSError *err = nil;

POXDocument *doc = [POXDocument openWithPassword:@"protected.pdf" password:@"user123" error:&err];
NSLog(@"%@", [doc extractText:0 error:&err]);

Elixir

{:ok, doc} = PdfOxide.open_with_password("protected.pdf", "user123")
{:ok, text} = PdfOxide.extract_text(doc, 0)
IO.puts(text)

Повний робочий процес шифрування

Python

from pdf_oxide import PdfDocument

# Open and modify
doc = PdfDocument("report.pdf")
doc.set_title("Confidential Report")
doc.set_author("Finance Team")

# Save with view-only restrictions
doc.save_encrypted(
    "report-protected.pdf",
    "",            # No password to open
    "admin2025",   # Owner password for full access
    allow_print=True,
    allow_copy=False,
    allow_modify=False,
)

WASM

import { WasmPdfDocument } from "pdf-oxide-wasm";

const doc = new WasmPdfDocument(bytes);
doc.setTitle("Confidential Report");
doc.setAuthor("Finance Team");

// Save with view-only restrictions (no open password, print allowed)
const output = doc.saveEncryptedToBytes(
  "", "admin2025", true, false, false, false
);
doc.free();

Rust

use pdf_oxide::api::Pdf;
use pdf_oxide::editor::{
    DocumentEditor, EditableDocument,
    EncryptionConfig, EncryptionAlgorithm, Permissions, SaveOptions,
};

// Open and modify
let mut doc = Pdf::open("report.pdf")?;
{
    let editor = doc.editor().unwrap();
    editor.set_title("Confidential Report");
    editor.set_author("Finance Team");
}

// Configure encryption
let permissions = Permissions {
    print: true,
    print_high_quality: true,
    modify: false,
    copy: false,
    annotate: false,
    fill_forms: true,
    accessibility: true,
    assemble: false,
};

let config = EncryptionConfig::new("", "admin2025")
    .with_algorithm(EncryptionAlgorithm::Aes256)
    .with_permissions(permissions);

doc.save_with_encryption("report-protected.pdf", config)?;

Повноповерхневі прив’язки нижче зберігають вивід із шифруванням AES-256 і повними правами; вони не надають поелементного контролю прав, доступного в Python/WASM/Rust. Задайте метадані /Info через set_producer редактора перед збереженням.

C++

#include <pdf_oxide/pdf_oxide.hpp>

auto editor = pdf_oxide::DocumentEditor::open("report.pdf");
editor.set_producer("Finance Team");

// Save with AES-256 encryption (no open password, owner password for full access)
editor.save_encrypted("report-protected.pdf", "", "admin2025");

Swift

import PdfOxide

let editor = try DocumentEditor.openEditor("report.pdf")
try editor.setProducer("Finance Team")

// Save with AES-256 encryption (no open password, owner password for full access)
try editor.saveEncrypted("report-protected.pdf", userPassword: "", ownerPassword: "admin2025")

Dart

import 'package:pdf_oxide/pdf_oxide.dart';

final editor = DocumentEditor.open('report.pdf');
editor.setProducer('Finance Team');

// Save with AES-256 encryption (no open password, owner password for full access)
editor.saveEncrypted('report-protected.pdf', '', 'admin2025');
editor.close();

R

library(pdfoxide)

editor <- pdf_editor_open("report.pdf")
pdf_editor_set_producer(editor, "Finance Team")

# Save with AES-256 encryption (no open password, owner password for full access)
pdf_editor_save_encrypted(editor, "report-protected.pdf", "", "admin2025")

Julia

using PdfOxide

editor = open_editor("report.pdf")
set_producer(editor, "Finance Team")

# Save with AES-256 encryption (no open password, owner password for full access)
save_encrypted(editor, "report-protected.pdf", "", "admin2025")

Zig

const pdf_oxide = @import("pdf_oxide");

var editor = try pdf_oxide.DocumentEditor.openEditor("report.pdf");
defer editor.deinit();
try editor.setProducer("Finance Team");

// Save with AES-256 encryption (no open password, owner password for full access)
try editor.saveEncrypted("report-protected.pdf", "", "admin2025");

Objective-C

#import "POXPdfOxide.h"
NSError *err = nil;

POXDocumentEditor *editor = [POXDocumentEditor openEditor:@"report.pdf" error:&err];
[editor setProducer:@"Finance Team" error:&err];

// Save with AES-256 encryption (no open password, owner password for full access)
[editor saveEncryptedToPath:@"report-protected.pdf"
               userPassword:@""
              ownerPassword:@"admin2025"
                      error:&err];

Elixir

{:ok, editor} = PdfOxide.open_editor("report.pdf")
:ok = PdfOxide.set_producer(editor, "Finance Team")

# Save with AES-256 encryption (no open password, owner password for full access)
:ok = PdfOxide.editor_save_encrypted(editor, "report-protected.pdf", "", "admin2025")

Повторне шифрування з іншими налаштуваннями

Rust

use pdf_oxide::editor::{DocumentEditor, EditableDocument, EncryptionConfig, SaveOptions};

// Open with current password
let mut editor = DocumentEditor::open("old-protected.pdf")?;

// Save with new encryption
let config = EncryptionConfig::new("newuser", "newowner");
let options = SaveOptions::with_encryption(config);
editor.save_with_options("re-encrypted.pdf", options)?;

Повний довідник API

Методи Pdf

Метод Повертає Опис
save_encrypted(path, user_pw, owner_pw) Result<()> Зберегти з AES-256 і повними правами
save_with_encryption(path, config) Result<()> Зберегти з користувацькою конфігурацією шифрування

Методи DocumentEditor / EditableDocument

Метод Повертає Опис
save(path) Result<()> Зберегти з повним перезаписом (без шифрування)
save_with_options(path, options) Result<()> Зберегти з користувацькими параметрами

Типи конфігурації

Тип Опис
EncryptionConfig Паролі користувача/власника, алгоритм, права
EncryptionAlgorithm Aes256, Aes128, Rc4_128, Rc4_40
Permissions Детальні прапорці контролю доступу
SaveOptions Повний перезапис, інкрементне оновлення або зашифроване збереження

Пов’язані сторінки