PHP code example of tecnickcom / tc-lib-pdf-encrypt

1. Go to this page and download the library: Download tecnickcom/tc-lib-pdf-encrypt library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tecnickcom / tc-lib-pdf-encrypt example snippets




S-256 R6 (mode 4, recommended)
$encrypt = new \Com\Tecnick\Pdf\Encrypt\Encrypt(
    enabled: true,
    file_id: md5('unique-file-id'),
    mode: 4,
    // permissions lists what to BLOCK: this document cannot be printed or copied
    permissions: ['print', 'copy'],
    user_pass: 'userpassword',
    owner_pass: 'ownerpassword',
);

$cipher = $encrypt->encryptString('secret payload', $objectNumber = 1);
echo bin2hex($cipher);

// The first element of the trailer /ID array must carry this value:
// revisions 2 to 4 derive the key from it.
echo $encrypt->getFileId();



ss the encryption dictionary produced by the Encrypt instance.
$decrypt = new \Com\Tecnick\Pdf\Encrypt\Decrypt($encrypt->getEncryptionData());

if ($decrypt->authenticate('userpassword')) {
    echo $decrypt->getAuthenticatedRole(); // 'user', 'owner' or 'recipient'

    // For AES modes the PKCS#7 padding is stripped, so the exact original
    // plaintext is returned; RC4 modes are symmetric. Throws when called
    // without a successful authenticate() or on malformed data.
    $plain = $decrypt->decryptString($cipher, $objectNumber = 1, $generationNumber = 0);
    echo $plain;
}

$decrypt = \Com\Tecnick\Pdf\Encrypt\Decrypt::fromEncryptionDictionary([
    'V' => 5,
    'R' => 6,
    'O' => $oBytes,      // raw binary, not hexadecimal
    'U' => $uBytes,
    'OE' => $oeBytes,
    'UE' => $ueBytes,
    'Perms' => $permsBytes,
    'P' => -3904,
    'fileid' => $firstTrailerIdElement,
]);