跳轉到

加密指南

先決條件

composer require nextpdf/core

加密基本概念

兩種密碼角色

密碼類型 用途 權限
使用者密碼(User Password) 開啟文件所需 依擁有者設定的權限
擁有者密碼(Owner Password) 管理文件權限 完整權限

基本加密

use NextPDF\Core\Security\Aes256Encryptor;
use NextPDF\Core\Security\ValueObjects\EncryptionOptions;
use NextPDF\Core\Security\ValueObjects\Permissions;

$encryptor = Aes256Encryptor::create();

$encrypted = $encryptor->encrypt(
    document: $document,
    options:  EncryptionOptions::create(
        userPassword:  $_ENV['PDF_USER_PASSWORD'],
        ownerPassword: $_ENV['PDF_OWNER_PASSWORD'],
    ),
);

$encrypted->save('/output/encrypted.pdf');

權限控制

$permissions = Permissions::create()
    ->allowPrinting(highResolution: true)
    ->denyModification()
    ->denyContentCopying()
    ->denyAnnotation()
    ->denyFormFilling()
    ->denyExtraction();

$options = EncryptionOptions::create(
    userPassword:  $_ENV['PDF_USER_PASSWORD'],
    ownerPassword: $_ENV['PDF_OWNER_PASSWORD'],
    permissions:   $permissions,
);

僅限擁有者密碼(無使用者密碼)

$options = EncryptionOptions::create(
    userPassword:  null, // 不需密碼即可開啟
    ownerPassword: $_ENV['PDF_OWNER_PASSWORD'],
    permissions:   $permissions,
);

搭配數位簽章使用

// 正確順序:先簽章,後加密
$signed    = $orchestrator->sign(document: $document);
$encrypted = $encryptor->encrypt(
    document: $signed,
    options:  $options,
);
$encrypted->save('/output/signed-encrypted.pdf');

解密與驗證

安全性注意事項

警告:PDF 加密保護文件存取,但並非萬無一失的 DRM 解決方案。請結合存取控制、稽核日誌等額外安全措施。

延伸閱讀