Skip to content

PDF の暗号化・復号 — Python / Rust / Go

バインディング対応状況。 パスワード付き PDF のオープン(復号)は 5 バインディングすべてで利用できます。暗号化 PDF の保存は Python、Rust、Go (DocumentEditor.SaveEncrypted)、WASM (saveEncryptedToBytes) で提供されます。C# の公開 API には PdfDocument.OpenWithPassword によるパスワード付きオープンはありますが、SaveEncrypted の公開ラッパーはまだ追加されていません。C# パイプラインから暗号化 PDF を出力したい場合は、Rust CLI か Go/Python バインディングを利用してください。

パスワードで PDF を暗号化します:

Python

from pdf_oxide import PdfDocument

doc = PdfDocument("report.pdf")
doc.save_encrypted("protected.pdf", "userpass", "ownerpass")

WASM

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

const doc = new WasmPdfDocument(bytes);
const encrypted = doc.saveEncryptedToBytes("userpass", "ownerpass", true, true, true, true);
// encrypted は Uint8Array です
doc.free();

Rust

use pdf_oxide::api::Pdf;

let mut doc = Pdf::open("report.pdf")?;
doc.save_encrypted("protected.pdf", "userpass", "ownerpass")?;

Go

package main

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

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

    if err := editor.SaveEncrypted("protected.pdf", "userpass", "ownerpass"); err != nil {
        log.Fatal(err)
    }
}

暗号化された PDF を開きます:

Python

from pdf_oxide import PdfDocument

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

WASM

const doc = new WasmPdfDocument(encryptedBytes);
doc.authenticate("userpass");
const text = doc.extractText(0);
console.log(text);
doc.free();

Rust

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

Go

doc, _ := pdfoxide.Open("protected.pdf")
defer doc.Close()

if _, err := doc.Authenticate("userpass"); err != nil { log.Fatal(err) }
text, _ := doc.ExtractText(0)
fmt.Println(text)

C#

using PdfOxide;

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

PDF Oxide は既定で AES-256 暗号化を使用します。MIT ライセンス、AGPL の制約はありません。

インストール

pip install pdf_oxide

PDF の暗号化

基本的な暗号化

Python

from pdf_oxide import PdfDocument

doc = PdfDocument("input.pdf")
doc.save_encrypted("output.pdf", "user123", "owner456")

WASM

const doc = new WasmPdfDocument(bytes);
const encrypted = doc.saveEncryptedToBytes("user123", "owner456", true, true, true, true);
doc.free();

Rust

let mut doc = Pdf::open("input.pdf")?;
doc.save_encrypted("output.pdf", "user123", "owner456")?;
  • ユーザーパスワード — ドキュメントを開いて表示するために必要
  • オーナーパスワード — フルアクセス(印刷、コピー、編集)に必要

開封パスワードのみ

制限を付けずにユーザーパスワードだけを設定します:

doc = PdfDocument("input.pdf")
doc.save_encrypted("locked.pdf", "viewpass", "adminpass")

開封パスワードなし、操作を制限

誰でも閲覧できますが、印刷とコピーを禁止します:

Python

doc = PdfDocument("input.pdf")
doc.save_encrypted(
    "restricted.pdf",
    "",            # 開封用パスワードなし
    "adminpass",   # フルアクセス用のオーナーパスワード
    allow_print=False,
    allow_copy=False,
    allow_modify=False,
    allow_annotate=False,
)

WASM

const doc = new WasmPdfDocument(bytes);
const restricted = doc.saveEncryptedToBytes(
    "",           // 開封用パスワードなし
    "adminpass",  // フルアクセス用のオーナーパスワード
    false,        // allowPrint
    false,        // allowCopy
    false,        // allowModify
    false         // allowAnnotate
);
doc.free();

Rust

let config = EncryptionConfig::new("", "adminpass")
    .with_permissions(Permissions::none());
doc.save_with_encryption("restricted.pdf", config)?;

印刷のみ許可

閲覧と印刷は許可し、コピーや編集は禁止します:

Python

doc = PdfDocument("input.pdf")
doc.save_encrypted(
    "print-only.pdf",
    "",
    "adminpass",
    allow_print=True,
    allow_copy=False,
    allow_modify=False,
)

WASM

const doc = new WasmPdfDocument(bytes);
const printOnly = doc.saveEncryptedToBytes(
    "",           // 開封用パスワードなし
    "adminpass",
    true,         // allowPrint
    false,        // allowCopy
    false,        // allowModify
    true          // allowAnnotate
);
doc.free();

Rust

let config = EncryptionConfig::new("", "adminpass")
    .with_permissions(Permissions::print_only());
doc.save_with_encryption("print-only.pdf", config)?;

権限オプション

パラメータ 既定値 説明
allow_print True ドキュメントの印刷を許可
allow_copy True テキストと画像のコピーを許可
allow_modify True コンテンツの編集を許可
allow_annotate True 注釈の追加を許可

PDF の復号

パスワードで開く

Python

from pdf_oxide import PdfDocument

doc = PdfDocument("encrypted.pdf", password="secret")
text = doc.extract_text(0)
print(f"Pages: {doc.page_count()}")

WASM

const doc = new WasmPdfDocument(encryptedBytes);
doc.authenticate("secret");
const text = doc.extractText(0);
console.log(`Pages: ${doc.pageCount()}`);
doc.free();

Rust

let mut doc = Pdf::open_with_password("encrypted.pdf", "secret")?;
let text = doc.extract_text(0)?;
println!("Pages: {}", doc.page_count()?);

暗号化せずに保存

暗号化 PDF を開き、暗号化なしのコピーを保存します:

Python

from pdf_oxide import PdfDocument

doc = PdfDocument("encrypted.pdf", password="secret")
doc.save("decrypted.pdf")

WASM

const doc = new WasmPdfDocument(encryptedBytes);
doc.authenticate("secret");
const decrypted = doc.save();
// decrypted は暗号化されていない Uint8Array です
doc.free();

Rust

let mut doc = Pdf::open_with_password("encrypted.pdf", "secret")?;
doc.save("decrypted.pdf")?;

別のパスワードで再暗号化

Python

from pdf_oxide import PdfDocument

doc = PdfDocument("old-protected.pdf", password="oldpass")
doc.save_encrypted("new-protected.pdf", "newuser", "newowner")

WASM

const doc = new WasmPdfDocument(encryptedBytes);
doc.authenticate("oldpass");
const reEncrypted = doc.saveEncryptedToBytes("newuser", "newowner", true, true, true, true);
doc.free();

Rust

let mut doc = Pdf::open_with_password("old-protected.pdf", "oldpass")?;
doc.save_encrypted("new-protected.pdf", "newuser", "newowner")?;

バッチ暗号化

ディレクトリ内のすべての PDF を暗号化します:

from pdf_oxide import PdfDocument, PdfError
from pathlib import Path

input_dir = Path("reports/")
output_dir = Path("protected/")
output_dir.mkdir(exist_ok=True)

for pdf_path in input_dir.glob("*.pdf"):
    try:
        doc = PdfDocument(str(pdf_path))
        out_path = output_dir / pdf_path.name
        doc.save_encrypted(
            str(out_path),
            "company2025",
            "admin2025",
            allow_print=True,
            allow_copy=False,
        )
        print(f"Encrypted: {pdf_path.name}")
    except PdfError as e:
        print(f"Failed: {pdf_path.name}: {e}")

バッチ復号

既知のパスワードですべての PDF を復号します:

from pdf_oxide import PdfDocument, PdfError
from pathlib import Path

input_dir = Path("protected/")
output_dir = Path("decrypted/")
output_dir.mkdir(exist_ok=True)

for pdf_path in input_dir.glob("*.pdf"):
    try:
        doc = PdfDocument(str(pdf_path), password="company2025")
        out_path = output_dir / pdf_path.name
        doc.save(str(out_path))
        print(f"Decrypted: {pdf_path.name}")
    except PdfError as e:
        print(f"Failed: {pdf_path.name}: {e}")

対応アルゴリズム

PDF Oxide は標準的な PDF 暗号化アルゴリズムをすべてサポートします:

アルゴリズム 鍵長 強度
AES-256 256 ビット 最強(既定)
AES-128 128 ビット 強い
RC4-128 128 ビット レガシー
RC4-40 40 ビット 弱い(互換性用途のみ)

save_encrypted() は既定で AES-256 を使用します。アルゴリズムを明示的に指定したい場合は、Rust API の EncryptionConfig を利用してください。

pdfplumber や pdfminer では不十分な理由

pdfplumber も pdfminer も暗号化 PDF を扱えません:

  • pdfplumber — パスワード保護された PDF ではエラーを発生させます。復号機能はありません。
  • pdfminer — 暗号化対応は限定的で、AES-256 暗号化ファイルでは失敗します。
  • pypdf — 復号には対応していますが、復号後のテキスト抽出では PDF Oxide より 15 倍遅くなります。

大規模に暗号化 PDF を扱うなら、PDF Oxide なら AES-128 と AES-256 の暗号化・復号をネイティブに処理できます。

関連ページ