加密¶
NextPDF 實作 PDF 2.0 規範定義的最高等級加密標準:AES-256-CBC(AESV3,Revision 6)。此加密方案使用 SHA-256 進行金鑰推導,具備密碼驗證機制,防止暴力破解攻擊。
設定加密¶
use NextPDF\Security\EncryptionConfig;
use NextPDF\Security\Permission;
use NextPDF\Core\Configuration;
$config = Configuration::create(
encryption: EncryptionConfig::aes256(
userPassword: 's3cur3-user-p@ss', // 開啟文件的密碼(可空)
ownerPassword: 'str0ng-owner-p@ss!', // 管理員密碼(可修改設定)
permissions: Permission::PRINT | Permission::COPY,
),
);
$document = $process->factory()->create($config);
// ... 建立文件內容 ...
$encryptedPdf = $document->finalize(); // 輸出已加密的 PDF
加密演算法詳情¶
NextPDF 使用的 AESV3 Revision 6 符合 PDF 2.0(ISO 32000-2:2020)§7.6.5 的規格:
金鑰長度:256 位元(32 bytes)
加密演算法:AES-256-CBC
初始向量(IV):每個物件獨立隨機生成(16 bytes)
金鑰推導:SHA-256 + 隨機驗證字串(Validation Salt + Key Salt)
密碼驗證:儲存 SHA-256(password + Validation Salt) 用於驗證
加密範圍¶
// 控制加密範圍(預設加密所有內容)
$config = Configuration::create(
encryption: EncryptionConfig::aes256(
userPassword: 'user',
ownerPassword: 'owner',
permissions: Permission::PRINT,
encryptMetadata: true, // 是否加密 XMP 中繼資料(PDF 2.0 預設:true)
),
);
解密已加密的 PDF¶
use NextPDF\Security\PdfDecryptor;
$decryptor = PdfDecryptor::create();
// 解密以進行修改(需要擁有者密碼)
$decryptedBytes = $decryptor->decrypt(
pdf: file_get_contents('/path/to/encrypted.pdf'),
ownerPassword: 'str0ng-owner-p@ss!',
);
// 僅開啟(使用用戶密碼)
$decryptedBytes = $decryptor->decrypt(
pdf: $encryptedPdf,
userPassword: 's3cur3-user-p@ss',
);
舊版加密格式(向後相容)¶
// 注意:RC4 與 AES-128 為遺留格式,安全性不足,不建議使用
// 僅在需要相容舊系統時考慮
$config = Configuration::create(
encryption: EncryptionConfig::aes128(/* ... */), // PDF 1.6–1.7
);
硬體安全模組(HSM)整合¶
高安全性需求場景(例如:政府文件、金融報告)可透過 Enterprise 套件整合 HSM:
// HSM 整合透過 Enterprise 套件提供
// 詳見 Enterprise 文件
use NextPDF\Enterprise\Security\HsmEncryptionProvider;