Sign PDF files with valid x509 certificate
Sign PDF files with valid x509 certificate
Sign PDF files with an A1 certificate
Digital signatures for Laravel, from PKCS#12 or PEM, with PAdES profiles, long-term validation
and cryptographic verification of signatures a document already carries.
The signing engine is signet-pdf. This package is the Laravel half: the container, the config,
Storage disks as a signing source, and everything faked with the framework's own tools.
Documentation · Release notes · Upgrading · The engine
composer require lsnepomuceno/laravel-a1-pdf-signNothing else to register: the service provider is discovered, and the A1PdfSign facade is available immediately.
openssl on PATH is not required to sign; it is used only for verifying a signature and for reading a legacy
PFX file. Where it is needed it is needed properly: ext-openssl being loaded is a different thing from the binary
being installed, and a minimal container commonly has the first without the second. Validating without it raises
MissingBinaryException, and an environment where proc_open is disabled raises ProcessUnavailableException.
Neither is reported as a signature that failed to verify.
Every exception this package raises implements Exceptions\SignetException, so an application can handle them
as a group rather than by name:
use LSNepomuceno\Signet\Exceptions\SignetException;
$exceptions->report(function (SignetException $e) { … });The classes stay granular beneath it. InvalidCertificatePasswordException is the one worth catching on its own,
since a wrong password is the failure a production application meets most, and it extends
InvalidCertificateContentException so the general catch still works.
php artisan vendor:publish --tag=a1-pdf-sign-configuse LSNepomuceno\LaravelA1PdfSign\Facades\A1PdfSign;
$signed = A1PdfSign::newSignature()
->certificate($pfxPath, $password)
->pdf($pdfPath)
->info(name: 'Lucas', reason: 'Contract')
->seal() // omit for an invisible signature
->sign();
$signed->contents; // string
$signed->save($path); // path
$signed->download('contract.pdf'); // BinaryFileResponse[!IMPORTANT] Signing appends a revision rather than rebuilding the document. The original bytes survive byte for byte, so annotations, form fields and every earlier signature are preserved, and a document can carry as many signatures as it needs. That is TCPDF#430, open since 2021, and it is the single most important behaviour in this package.
An application keeping contracts on s3, minio or any Flysystem disk does not have to download one first, and the signed result does not have to come back through one either:
A1PdfSign::newSignature()
->certificate($pfx, $password)
->from(A1PdfSign::fromDisk('s3', 'contracts/deal.pdf'))
->sign()
->writeTo(A1PdfSign::toDisk('s3', 'contracts/deal-signed.pdf'));fromUpload() does the same for a document that arrived in a request, reading it where it already is rather than copying it to a temporary file. toDisk() with no path keeps the name the document carries, which is the original with _signed appended.
// or hand over the bytes yourself, from anywhere at all
->pdfContents($bytes, 'deal.pdf')All of these hold the whole document in memory. For one too large for that, the engine takes a stream: see signet-pdf.
| PKCS#12 and PEM | .pfx, .p12, or a PEM certificate with the key beside it or in its own file |
| PAdES profiles | legacy through pades-b-lta, with RFC 3161 timestamps and long-term validation |
| Visible seals | rendered from the certificate or drawn from your own artwork, on the page you name |
| Template fields | fills a signature field a contract already carries, instead of appending beside it |
| Certification | ISO 32000-1 §12.8.2.2 DocMDP, plus field locks that later signatures honour |
| Encrypted documents | AES-128 and AES-256, signed and re-encrypted under the document's own key |
| Archive maintenance | refresh a B-LTA archive with no certificate and no key material involved |
| Verification | the CMS is actually verified, with the timestamp, the profile and revocation reported |
| ICP-Brasil identity | CPF, CNPJ and the rest, read from the certificate rather than parsed out of a name |
| PDF/A | a signed document stays conformant, measured with veraPDF rather than assumed |
| PDF/UA | measured too: an invisible signature keeps an accessible document conformant, a visible seal does not |
The seal is drawn by Contracts\SealRenderer, bound in the container, so replacing it is one line in your own
service provider:
$this->app->bind(SealRenderer::class, QrCodeSealRenderer::class);That is the route for a corporate logo, a QR code linking to a validation page, or any layout of your own. The
contract has two methods: render() builds a seal from the certificate, and fromImage() embeds artwork you
already have.
fromImage() is also the answer to "can I draw the seal with Blade". Render your view to an image however you
like and hand the result over; the package stays out of the business of turning HTML into pixels, which would be a
large dependency for a signing library.
Your own suite should not need a PKCS#12 bundle, nor should it build a real CMS for a test that merely passes through the signing call:
$signing = A1PdfSign::fake();
// … the application runs …
$signing->assertSigned();
$signing->assertSignedTimes(1);
$signing->assertSignedWithProfile(SignatureProfile::PadesBLT);
$signing->assertCertified(CertificationLevel::NoChanges);
$signing->assertSealed();
$signing->assertNothingSigned();It replaces the engine in the container, not just one binding, so certificate() accepts any path and nothing is
parsed, rendered or signed. The result is still a SignedPdf, so code calling ->contents, ->size() or
->save() keeps working. Two-phase signing records too: assertPrepared() and assertCompleted().
The fake covers signing. The rest of what the package touches is replaced with Laravel's own tools, which is most of the reason this package exists rather than just signet-pdf:
Process::fake(); // the openssl shell-out, for validation and legacy PFX files
Http::fake(); // the timestamp authority, OCSP and CRL
Http::preventStrayRequests(); // proves a pades-b-b signature reaches no network at all
Storage::fake('s3'); // signing from a disk and writing back to oneFor the profiles above pades-b-b, substituting the transport with Signet\Testing\LocalTimestampAuthority gates
them offline with real RFC 3161 tokens, rather than reporting them against a live authority:
app()->instance(SignatureTransport::class, new LocalTimestampAuthority(app(ProcessRunner::class)));// PKCS#12
A1PdfSign::newSignature()->certificate($pfxPath, $password);
// PEM, key in the same file or in its own
A1PdfSign::newSignature()->certificatePem($certificatePath, $keyPath, $password);
// From an upload or a secret store
A1PdfSign::newSignature()->certificateFromPem($bytes);The encoding is decided by content, not by extension, since PEM ships as .pem, .crt, .cer, .key and .txt.
Pass an empty password when the private key is unencrypted: PEM permits that and PKCS#12 does not, and an
unprotected key on disk is readable by anything that can read the file.
The builder exists for the cases that need it. When none of them apply, there is a one-shot form for each source:
A1PdfSign::signFromFile($pfxPath, $password, $pdfPath);
A1PdfSign::signFromPem($pemPath, $password, $pdfPath, $keyPath);
A1PdfSign::signFromUpload($request->file('certificate'), $password, $pdfPath);A certificate and its password can be encrypted for storage and read back later, so an application that signs on a schedule does not keep either in plaintext:
$stored = A1PdfSign::encryptCertificate($uploadedOrPath, $password);
$stored->hash; // the key both values were encrypted with. Required to read them back
$stored->certificate;
$stored->password;
$certificate = A1PdfSign::decryptCertificate($stored->hash, $stored->certificate, $stored->password);The hash is the key, so keep it somewhere other than the ciphertext it opens. Without it the pair cannot be read back, by you or by anyone else.
| Profile | Adds |
|---|---|
legacy |
ISO 32000-1 detached CMS. Widest reader support |
pades-b-b |
CAdES signed attributes, with ESS signing-certificate-v2. Default |
pades-b-t |
plus an RFC 3161 timestamp, so the signing time is attested by a third party |
pades-b-lt |
plus a Document Security Store, so it still verifies after the certificate expires |
pades-b-lta |
plus an archive timestamp over the whole file |
A1PdfSign::newSignature()
->certificate($pfx, $password)
->pdf($path)
->profile('pades-b-lt') // needs A1_TSA_URL configured
->sign();An archive is a chain rather than a state, so it can be extended before the algorithms behind it weaken. No certificate is involved: a DocTimeStamp is signed by the authority, not by the signer, so a scheduled job can do this with no key material anywhere near it.
A1PdfSign::extendArchive($path);A contract laid out by someone else arrives with its signature fields already placed. intoField() fills the one you
name instead of appending another beside it:
foreach (A1PdfSign::signatureFields($template) as $field) {
$field->name; // 'SignatureManager'
$field->isSigned; // false
$field->rectangle; // [30.0, 200.0, 200.0, 250.0]
}
A1PdfSign::newSignature()
->certificate($pfx, $password)
->pdf($template)
->intoField('SignatureManager')
->seal() // drawn into the field's own rectangle
->sign();A field that is missing or already signed raises rather than falling back to appending. That fallback is the failure this prevents: a signature that is valid and in the wrong place, with the template's field still empty.
addSignatureField() is the other half, for when nobody has laid the template out for you:
A1PdfSign::addSignatureField($pdf, 'Manager') // invisible
A1PdfSign::addSignatureField($pdf, 'Manager', new SealPlacement(60, 400, 120, 40)); // placedFor a private key that never enters the process, in an HSM, a remote service or a smartcard, signing splits in two:
$prepared = A1PdfSign::newSignature()
->certificatePublic($certificatePem) // the public half is enough to reserve the space
->pdf($contract)
->prepare();
$cms = $yourHsm->sign($prepared->digestValue); // the only step that touches the key
$signed = A1PdfSign::complete($prepared, $cms);$prepared carries no key and no secret, so it survives a queue. That is usually the point: the digest goes to a
worker with access to the signing device, and the document comes back finished.
A1PdfSign::newSignature()->certificate($pfx, $password)No open issues yet, or sync has not completed.