Initial commit

This commit is contained in:
2026-08-20 11:41:17 +00:00
commit 6949695eac
2334 changed files with 646393 additions and 0 deletions
+20
View File
@@ -0,0 +1,20 @@
# Ref: https://EditorConfig.org
# top-most EditorConfig file
root = true
# Unix-style end of lines and a blank line at the end of the file
[*]
indent_style = tab
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.php]
indent_style = space
indent_size = 4
[*.{js,json,scss,css,yml,vue}]
indent_style = space
indent_size = 2
@@ -0,0 +1,22 @@
# Normalize text sources to LF in the repository and on checkout everywhere.
# Critical for a byte-level library: keeps source and fixtures byte-identical
# across Windows/macOS/Linux checkouts regardless of core.autocrlf.
*.php text eol=lf
*.md text eol=lf
*.xml text eol=lf
*.xml.dist text eol=lf
*.json text eol=lf
*.toml text eol=lf
*.yml text eol=lf
*.yaml text eol=lf
*.txt text eol=lf
Makefile text eol=lf
# Byte-exact fixtures must never be transformed (CRLF/auto-detection off).
test/**/*.bin -text
*.png binary
*.jpg binary
*.gif binary
*.pdf binary
*.ttf binary
*.otf binary
@@ -0,0 +1,29 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. ...
**Expected behavior**
A clear and concise description of what you expected to happen.
**Logs**
If applicable, copy the relevant logs to help explain your problem.
**Environment:**
- OS:
- PHP version:
- Version:
**Additional context**
Add any other context about the problem here.
@@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
@@ -0,0 +1,25 @@
# Description
Please include a summary of the change and include relevant motivation and context.
...
## Checklist:
- [ ] The `make buildall` command has been run successfully without any error or warning.
- [ ] Any new code line is covered by unit tests and the coverage has not dropped.
- [ ] Any new code follows the style guidelines of this project.
- [ ] The code changes have been self-reviewed.
- [ ] Corresponding changes to the documentation have been made.
- [ ] The version has been updated in the VERSION file.
## Type of change:
- [ ] Bug fix (non-breaking change which fixes an issue) → The patch number in the VERSION file has been increased.
- [ ] New feature (non-breaking change which adds functionality) → The minor number in the VERSION file has been increased.
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) → The major number in the VERSION file has been increased.
- [ ] Automation.
- [ ] Documentation.
- [ ] Example.
- [ ] Testing.
@@ -0,0 +1,59 @@
name: check
env:
XDEBUG_MODE: coverage
permissions:
contents: read
on:
push:
branches:
- 'main'
pull_request:
types: [opened, synchronize, reopened]
branches:
- main
workflow_dispatch:
jobs:
test-php:
name: Test on php ${{ matrix.php-version }} and ${{ matrix.os }}
runs-on: ${{ matrix.os }}
continue-on-error: ${{ matrix.experimental }}
strategy:
fail-fast: false
matrix:
php-version: ["8.2", "8.3", "8.4", "8.5"]
experimental: [false]
os: [ubuntu-latest]
coverage-extension: [pcov]
steps:
- uses: actions/checkout@v7
- name: Use php ${{ matrix.php-version }}
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php-version }}
coverage: ${{ matrix.coverage-extension }}
extensions: bcmath, curl, date, gd, hash, imagick, json, mbstring, openssl, pcre, zlib
ini-values: display_errors=on, error_reporting=-1, zend.assertions=1
- name: List php modules
run: php -m
- name: List php modules using "no php ini" mode
run: php -m -n
- name: Cache module
uses: actions/cache@v6
with:
path: ~/.composer/cache/
key: composer-cache
- name: Install dependencies
env:
GH_TOKEN: ${{ github.token }}
run: make deps
- name: Run all tests
run: make qa
- name: Send coverage
uses: codecov/codecov-action@v7
with:
flags: php-${{ matrix.php-version }}-${{ matrix.os }}
name: php-${{ matrix.php-version }}-${{ matrix.os }}
@@ -0,0 +1,21 @@
**/*.bak
**/*.tmp
**/.#*
**/.DS_Store
**/._*
**/.idea
**/.vagrant
**/auth.json
**/nbproject
**/temp.php
**/test.php
.phpdoc
.phpunit.cache
.phpunit.result.cache
composer.lock
ecs.php
phpunit.xml
rector.php
target
vendor
PLAN_*
+1
View File
@@ -0,0 +1 @@
* @nicolaasuni
+128
View File
@@ -0,0 +1,128 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.
+194
View File
@@ -0,0 +1,194 @@
# Contributing to tc-lib-pdf-sign
Thank you for your interest in contributing to **tc-lib-pdf-sign**.
Contributions of all kinds are welcome: bug reports, bug fixes, documentation improvements, new features, and refactors.
Please take a moment to read this guide before opening an issue or pull request.
---
## Table of Contents
- [Code of Conduct](#code-of-conduct)
- [Security Vulnerabilities](#security-vulnerabilities)
- [Getting Started](#getting-started)
- [Reporting a Bug](#reporting-a-bug)
- [Submitting a Bug Fix](#submitting-a-bug-fix)
- [Proposing a New Feature](#proposing-a-new-feature)
- [Development Workflow](#development-workflow)
- [Coding Standards](#coding-standards)
- [Testing](#testing)
- [Pull Request Guidelines](#pull-request-guidelines)
- [Commit Message Guidelines](#commit-message-guidelines)
---
## Code of Conduct
This project follows the [Contributor Covenant Code of Conduct](CODE_OF_CONDUCT.md). By participating you agree to abide by its terms. Please report unacceptable behaviour to [info@tecnick.com](mailto:info@tecnick.com).
---
## Security Vulnerabilities
**Do not open a public GitHub issue for security vulnerabilities.**
Please follow the [Security Policy](SECURITY.md) and report them privately.
---
## Getting Started
### Requirements
- PHP **≥ 8.2**
- [Composer](https://getcomposer.org/) v2
- `make`, `git`
- Optional: `rpmbuild` (RPM packaging), `dpkg-buildpackage` (DEB packaging)
### Local setup
```bash
git clone https://github.com/tecnickcom/tc-lib-pdf-sign.git
cd tc-lib-pdf-sign
make buildall
```
To verify everything is working after a change:
```bash
make qa
```
This runs linting, static analysis, and the full unit-test suite with coverage.
---
## Reporting a Bug
Before opening an issue:
1. **Check the [Security Policy](SECURITY.md)** — if the bug is a security vulnerability, do not file a public issue.
2. **Search [existing issues](https://github.com/tecnickcom/tc-lib-pdf-sign/issues)** to avoid duplicates.
If no existing issue matches, [open a new one](https://github.com/tecnickcom/tc-lib-pdf-sign/issues/new) and include:
- A **clear title and description** of the problem.
- The **library version** (`composer show tecnickcom/tc-lib-pdf-sign`) and PHP version.
- A **minimal, self-contained reproduction** — a short PHP script or a failing PHPUnit test case is ideal.
- **Expected vs. actual behaviour** — what you expected to happen and what actually happened.
- Any relevant **stack trace or error output**.
The more precise and reproducible the report, the faster it can be triaged and fixed.
---
## Submitting a Bug Fix
1. [Fork the repository](https://github.com/tecnickcom/tc-lib-pdf-sign/fork) and create a branch from `main`:
```bash
git checkout -b fix/short-description-of-bug
```
2. Make your changes, following the [Coding Standards](#coding-standards) below.
3. Add or update unit tests to cover the changes.
4. Run the full quality-assurance suite locally and ensure it passes:
```bash
make qa
```
5. Commit your changes (see [Commit Message Guidelines](#commit-message-guidelines)).
6. Open a pull request against `main` and fill in the PR template:
- Describe the problem and your solution.
- Reference the related issue number (e.g. `Fixes #123`).
---
## Proposing a New Feature
Before writing any code:
1. **Open a Feature Request** on [GitHub Issues](https://github.com/tecnickcom/tc-lib-pdf-sign/issues/new) describing the use case and proposed API.
2. Wait for feedback from the maintainer. This avoids investing time in a direction that may not be accepted.
Once the feature is agreed upon, follow the same branch → code → test → PR workflow as for bug fixes, using a branch named `feature/short-description`.
---
## Development Workflow
The `Makefile` exposes all common development tasks:
| Command | Description |
|---------|-------------|
| `make qa` | Run linting, static analysis, tests, and reports |
| `make test` | Run PHPUnit with code coverage |
| `make lint` | Check coding standards |
| `make format` | Auto-format the code |
| `make buildall` | Install dependencies, fix style, run QA, and build packages |
| `make clean` | Remove `vendor/` and `target/` directories |
| `make server` | Start the built-in PHP development server for the examples |
Run `make help` to see the full list of available targets.
---
## Coding Standards
- The codebase follows **PSR-12** for formatting.
- Run `make format` to auto-format the code.
- Run `make lint` to catch remaining issues.
- All source files live under `src/`, all tests under `test/`.
- Use strict types and explicit visibility on all class members.
- Avoid introducing new external dependencies without prior discussion.
---
## Testing
Tests are written with [PHPUnit](https://phpunit.de/) and live in `test/`.
```bash
# Run the full test suite with coverage
make test
# Run a specific test file
XDEBUG_MODE=coverage ./vendor/bin/phpunit test/HTMLTest.php
```
Requirements for contributions:
- Every bug fix must be accompanied by a regression test that fails before the fix and passes after.
- Every new feature must be accompanied by tests that cover both the happy path and edge cases.
Coverage reports are generated in `target/coverage/`.
---
## Pull Request Guidelines
- Target the `main` branch.
- Keep PRs focused — one fix or feature per PR.
- Ensure `make qa` passes locally before opening the PR.
- Do not bump the version number in your PR; that is handled by the maintainer at release time.
- Be responsive to review feedback; stale PRs may be closed after an extended period of inactivity.
---
## Commit Message Guidelines
Use concise, imperative-mood commit messages:
```
fix: correct path traversal in font loader
feat: add support for XYZ
test: add regression test for #123
docs: update CONTRIBUTING workflow
refactor: extract text measurement into helper
```
Prefix tags: `fix`, `feat`, `test`, `docs`, `refactor`, `chore`, `ci`.
Reference issues where relevant: `fix: correct X (closes #42)`.
---
## Questions?
If you have a question that is not covered here, feel free to open a [GitHub Discussion](https://github.com/tecnickcom/tc-lib-pdf-sign/discussions) or contact the maintainer at [info@tecnick.com](mailto:info@tecnick.com).
+862
View File
@@ -0,0 +1,862 @@
**********************************************************************
* LICENSE
*
* SOFTWARE : tc-lib-pdf-sign
* AUTHOR : Nicola Asuni <info@tecnick.com>
* COPYRIGHT : 2011-2026 Nicola Asuni - Tecnick.com LTD
**********************************************************************
This is free software: you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
**********************************************************************
**********************************************************************
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://www.fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
**********************************************************************
**********************************************************************
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://www.fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/philosophy/why-not-lgpl.html>.
**********************************************************************
**********************************************************************
+285
View File
@@ -0,0 +1,285 @@
# makefile
#
# @since 2026-07-16
# @category Library
# @package PdfSign
# @author Nicola Asuni <info@tecnick.com>
# @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
# @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
# @link https://github.com/tecnickcom/tc-lib-pdf-sign
#
# This file is part of tc-lib-pdf-sign software library.
# ----------------------------------------------------------------------------------------------------------------------
SHELL=/bin/bash
.SHELLFLAGS=-o pipefail -c
# Project owner
OWNER=tecnickcom
# Project vendor
VENDOR=${OWNER}
# Project name
PROJECT=tc-lib-pdf-sign
# Project version
VERSION=$(shell cat VERSION)
# Project release number (packaging build number)
RELEASE=$(shell cat RELEASE)
# Name of RPM or DEB package
PKGNAME=php-${OWNER}-${PROJECT}
# Data dir
DATADIR=usr/share
# PHP home folder
PHPHOME=${DATADIR}/php/Com/Tecnick
# Default installation path for code
LIBPATH=${PHPHOME}/Pdf/Sign/
# Path for configuration files (etc/$(PKGNAME)/)
CONFIGPATH=
# Default installation path for documentation
DOCPATH=${DATADIR}/doc/$(PKGNAME)/
# Installation path for the code
PATHINSTBIN=$(DESTDIR)/$(LIBPATH)
# Installation path for the configuration files
PATHINSTCFG=$(DESTDIR)/$(CONFIGPATH)
# Installation path for documentation
PATHINSTDOC=$(DESTDIR)/$(DOCPATH)
# Current directory
CURRENTDIR=$(CURDIR)/
# Target directory
TARGETDIR=target
# RPM Packaging path (where RPMs will be stored)
PATHRPMPKG=$(TARGETDIR)/RPM
# RPM local database path (avoid host rpmdb permission issues)
RPMDBPATH=$(PATHRPMPKG)/.rpmdb
# DEB Packaging path (where DEBs will be stored)
PATHDEBPKG=$(TARGETDIR)/DEB
# BZ2 Packaging path (where BZ2s will be stored)
PATHBZ2PKG=$(TARGETDIR)/BZ2
# sed argument for in-place substitutions
SEDINPLACE=-i
ifeq ($(shell uname -s),Darwin)
SEDINPLACE=-i ''
endif
# Default port number for the example server
PORT?=8000
# PHP binary
PHP=$(shell which php)
# Composer executable (disable APC to as a work-around of a bug)
COMPOSER=$(PHP) -d "apc.enable_cli=0" $(shell which composer)
# phpDocumentor executable file
PHPDOC=$(shell which phpDocumentor)
# Set default OpenSSL configuration file
ifeq ($(OPENSSL_CONF),)
OPENSSL_CONF=$(CURRENTDIR)openssl.cnf
endif
# Mago version
MAGOVERSION=1.43.0
# --- MAKE TARGETS ---
# Display general help about this command
.PHONY: help
help:
@echo ""
@echo "$(PROJECT) $(OPENSSL_CONF) Makefile."
@echo "The following commands are available:"
@echo ""
@awk '/^## /{desc=substr($$0,4)} /^\.PHONY:/{if(NF>1) {target=$$2; if(desc) printf " make %-15s: %s\n",target,desc; desc=""}}' Makefile
@echo ""
@echo "To test and build everything from scratch, use the shortcut:"
@echo " make x"
@echo ""
# alias for help target
.PHONY: all
all: help
# Full build and test sequence
.PHONY: x
x: buildall
## Full build and test sequence
.PHONY: buildall
buildall: deps format qa bz2 rpm deb
## Package the library in a compressed bz2 archive
.PHONY: bz2
bz2:
rm -rf "$(PATHBZ2PKG)"
make install DESTDIR="$(PATHBZ2PKG)"
tar -jcvf "$(PATHBZ2PKG)/$(PKGNAME)-$(VERSION)-$(RELEASE).tbz2" -C "$(PATHBZ2PKG)" "$(DATADIR)"
## Delete the vendor and target directories
.PHONY: clean
clean:
rm -rf ./vendor "$(TARGETDIR)"
## Build a DEB package for Debian-like Linux distributions
.PHONY: deb
deb:
rm -rf "$(PATHDEBPKG)"
$(MAKE) install DESTDIR="$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)"
rm -f "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/$(DOCPATH)LICENSE"
tar -zcvf "$(PATHDEBPKG)/$(PKGNAME)_$(VERSION).orig.tar.gz" -C "$(PATHDEBPKG)/" "$(PKGNAME)-$(VERSION)"
cp -rf ./resources/debian "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian"
find "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/" -type f -name '*.bak' -delete
chmod 755 "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/rules"
find "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/" -type f -exec sed $(SEDINPLACE) "s/~#DATE#~/`date -R`/" {} \;
find "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/" -type f -exec sed $(SEDINPLACE) "s/~#VENDOR#~/$(VENDOR)/" {} \;
find "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/" -type f -exec sed $(SEDINPLACE) "s/~#PROJECT#~/$(PROJECT)/" {} \;
find "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/" -type f -exec sed $(SEDINPLACE) "s/~#PKGNAME#~/$(PKGNAME)/" {} \;
find "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/" -type f -exec sed $(SEDINPLACE) "s/~#VERSION#~/$(VERSION)/" {} \;
find "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/" -type f -exec sed $(SEDINPLACE) "s/~#RELEASE#~/$(RELEASE)/" {} \;
echo "$(LIBPATH)" > "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/$(PKGNAME).dirs"
echo "$(LIBPATH)* $(LIBPATH)" > "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/install"
echo "$(DOCPATH)" >> "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/$(PKGNAME).dirs"
echo "$(DOCPATH)* $(DOCPATH)" >> "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/install"
ifneq ($(strip $(CONFIGPATH)),)
echo "$(CONFIGPATH)" >> "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/$(PKGNAME).dirs"
echo "$(CONFIGPATH)* $(CONFIGPATH)" >> "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/install"
endif
echo "new-package-should-close-itp-bug" > "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/$(PKGNAME).lintian-overrides"
cd "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)" && debuild -us -uc
## Clean all artifacts and download all dependencies
.PHONY: deps
deps: ensuretarget
rm -rf ./vendor/*
($(COMPOSER) install -vvv --no-interaction)
curl --proto '=https' --tlsv1.2 --silent --show-error --fail --location https://carthage.software/mago.sh | bash -s -- --install-dir=./vendor/bin --version=$(MAGOVERSION)
## Generate source code documentation
.PHONY: doc
doc: ensuretarget
rm -rf "$(TARGETDIR)/doc"
$(PHPDOC) -d ./src -t "$(TARGETDIR)/doc/"
## Create missing target directories for test and build artifacts
.PHONY: ensuretarget
ensuretarget:
mkdir -p "$(TARGETDIR)/test"
mkdir -p "$(TARGETDIR)/report"
mkdir -p "$(TARGETDIR)/doc"
## Install this application
.PHONY: install
install: uninstall
mkdir -p "$(PATHINSTBIN)"
cp -rf ./src/* "$(PATHINSTBIN)"
cp -f ./resources/autoload.php "$(PATHINSTBIN)"
find "$(PATHINSTBIN)" -type d -exec chmod 755 {} \;
find "$(PATHINSTBIN)" -type f -exec chmod 644 {} \;
mkdir -p "$(PATHINSTDOC)"
cp -f ./LICENSE "$(PATHINSTDOC)"
cp -f ./README.md "$(PATHINSTDOC)"
cp -f ./VERSION "$(PATHINSTDOC)"
cp -f ./RELEASE "$(PATHINSTDOC)"
chmod -R 644 "$(PATHINSTDOC)"*
ifneq ($(strip $(CONFIGPATH)),)
mkdir -p "$(PATHINSTCFG)"
touch -c "$(PATHINSTCFG)"*
cp -ru "./resources/${CONFIGPATH}"* "$(PATHINSTCFG)"
find "$(PATHINSTCFG)" -type d -exec chmod 755 {} \;
find "$(PATHINSTCFG)" -type f -exec chmod 644 {} \;
endif
## Format the source code
.PHONY: format
format:
./vendor/bin/mago fmt src test
## Analyze and Lint the source code
.PHONY: lint
lint:
./vendor/bin/mago --config ./mago.src.toml analyze src
./vendor/bin/mago --config ./mago.test.toml analyze test
./vendor/bin/mago --config ./mago.src.toml lint src
./vendor/bin/mago --config ./mago.test.toml lint test
## Run all tests and reports
.PHONY: qa
qa: ensuretarget lint test report
## Generate various reports
.PHONY: report
report: ensuretarget
./vendor/bin/pdepend --jdepend-xml="$(TARGETDIR)/report/dependencies.xml" --summary-xml="$(TARGETDIR)/report/metrics.xml" --jdepend-chart="$(TARGETDIR)/report/dependecies.svg" --overview-pyramid="$(TARGETDIR)/report/overview-pyramid.svg" --ignore=vendor ./src
#./vendor/bartlett/php-compatinfo/bin/phpcompatinfo --no-ansi analyser:run src/ > $(TARGETDIR)/report/phpcompatinfo.txt
## Build the RPM package for RedHat-like Linux distributions
.PHONY: rpm
rpm:
@test $(words $(CURDIR)) -eq 1 || { echo "ERROR: rpmbuild does not support spaces in the project path: $(CURDIR)"; exit 1; }
rm -rf "$(PATHRPMPKG)"
mkdir -p "$(RPMDBPATH)" "$(PATHRPMPKG)/tmp"
rpmbuild \
--define "_topdir $(CURRENTDIR)$(PATHRPMPKG)" \
--define "_dbpath $(CURRENTDIR)$(RPMDBPATH)" \
--define "_tmppath $(CURRENTDIR)$(PATHRPMPKG)/tmp" \
--define "_vendor $(VENDOR)" \
--define "_owner $(OWNER)" \
--define "_project $(PROJECT)" \
--define "_package $(PKGNAME)" \
--define "_version $(VERSION)" \
--define "_release $(RELEASE)" \
--define "_current_directory $(CURRENTDIR)" \
--define "_libpath /$(LIBPATH)" \
--define "_docpath /$(DOCPATH)" \
--define "_configpath /$(CONFIGPATH)" \
-bb resources/rpm/rpm.spec
## Start the development server
.PHONY: server
server:
$(PHP) -t example -S localhost:$(PORT)
## Tag this GIT version
.PHONY: tag
tag:
git checkout main && \
git tag -a ${VERSION} -m "Release ${VERSION}" && \
git push origin --tags && \
git pull
## Run unit tests
.PHONY: test
test:
cp phpunit.xml.dist phpunit.xml
#./vendor/bin/phpunit --migrate-configuration || true
OPENSSL_CONF=${OPENSSL_CONF} XDEBUG_MODE=coverage ./vendor/bin/phpunit --stderr test
## Remove all installed files
.PHONY: uninstall
uninstall:
rm -rf "$(PATHINSTBIN)"
rm -rf "$(PATHINSTDOC)"
## Increase the version patch number
.PHONY: versionup
versionup:
echo ${VERSION} | gawk -F. '{printf("%d.%d.%d\n",$$1,$$2,(($$3+1)));}' > VERSION
+178
View File
@@ -0,0 +1,178 @@
# tc-lib-pdf-sign
> Digital signature primitives for PDF documents (PKCS#7, CAdES, PAdES).
[![Latest Stable Version](https://poser.pugx.org/tecnickcom/tc-lib-pdf-sign/version)](https://packagist.org/packages/tecnickcom/tc-lib-pdf-sign)
[![Build](https://github.com/tecnickcom/tc-lib-pdf-sign/actions/workflows/check.yml/badge.svg)](https://github.com/tecnickcom/tc-lib-pdf-sign/actions/workflows/check.yml)
[![Coverage](https://codecov.io/gh/tecnickcom/tc-lib-pdf-sign/graph/badge.svg?token=Pv1MNH3X3v)](https://codecov.io/gh/tecnickcom/tc-lib-pdf-sign)
[![License](https://poser.pugx.org/tecnickcom/tc-lib-pdf-sign/license)](https://packagist.org/packages/tecnickcom/tc-lib-pdf-sign)
[![Downloads](https://poser.pugx.org/tecnickcom/tc-lib-pdf-sign/downloads)](https://packagist.org/packages/tecnickcom/tc-lib-pdf-sign)
[![Sponsor on GitHub](https://img.shields.io/badge/sponsor-github-EA4AAA.svg?logo=githubsponsors&logoColor=white)](https://github.com/sponsors/tecnickcom)
> 💖 Part of the [tc-lib-pdf / TCPDF](https://github.com/tecnickcom/tc-lib-pdf) ecosystem (100M+ installs). [Sponsor its maintenance →](https://github.com/sponsors/tecnickcom)
---
## Overview
`tc-lib-pdf-sign` provides the cryptographic building blocks and PDF signature objects used by `tc-lib-pdf` to produce signed PDF documents.
The crypto and the PDF object generation live here, while the host library keeps the ByteRange placement, the incremental update writer, and the public facade.
The package assembles CMS/CAdES signatures natively in pure PHP (via a small DER ASN.1 codec), so it can embed the ESS `signing-certificate-v2` attribute that `openssl_pkcs7_sign()` cannot add. This is what lifts a plain PKCS#7 signature to a PAdES baseline signature.
| | |
|---|---|
| **Namespace** | `\Com\Tecnick\Pdf\Sign` |
| **Author** | Nicola Asuni <info@tecnick.com> |
| **License** | [GNU LGPL v3](https://www.gnu.org/copyleft/lesser.html) - see [LICENSE](LICENSE) |
| **API docs** | <https://tcpdf.org/docs/srcdoc/tc-lib-pdf-sign> |
| **Packagist** | <https://packagist.org/packages/tecnickcom/tc-lib-pdf-sign> |
---
## Features
Signature profiles (each level builds on the previous one):
| Profile | /SubFilter | What it provides |
|---|---|---|
| **Legacy** | `adbe.pkcs7.detached` | ISO 32000-1 detached CMS (now carrying the ESS `signing-certificate-v2` attribute). |
| **PAdES B-B** | `ETSI.CAdES.detached` | CAdES-based CMS with `content-type`, `message-digest`, and `signing-certificate-v2` signed attributes. |
| **PAdES B-T** | `ETSI.CAdES.detached` | B-B plus an RFC 3161 signature timestamp embedded as the `id-aa-signatureTimeStampToken` unsigned attribute. |
| **PAdES B-LT** | `ETSI.CAdES.detached` | B-T plus a Document Security Store (`/DSS`, `/VRI`) with certificate, OCSP, and CRL validation material. |
| **PAdES B-LTA** | `ETSI.CAdES.detached` + `ETSI.RFC3161` | B-LT plus a `/Type /DocTimeStamp` archive timestamp for long-term archival. |
- RSA and ECDSA signing keys, with SHA-256, SHA-384, or SHA-512 digests.
- Both the local (private key) and the external/remote (HSM) signing workflows are supported through the `tc-lib-pdf` facade, which builds on these primitives.
- The PAdES baseline output has been validated against the [EU DSS](https://ec.europa.eu/digital-building-blocks/sites/display/DIGITAL/Digital+Signature+Service+-++DSS) reference validator (B-B, B-T, B-LT, B-LTA all report the expected baseline level).
---
## Components
| Component | Responsibility |
|---|---|
| `Config` | Immutable signature configuration (profile, digest algorithm, certification level) with `/SubFilter` derivation. |
| `Signer` | Orchestration entry point: builds the detached CAdES CMS and collects the LTV material, tying the pieces below together. |
| `Cms\Builder` | Native detached CAdES-BES `SignedData` builder (signs the DER signed attributes with `openssl_sign()`). |
| `Cms\Asn1` | Minimal DER ASN.1 encoder/decoder for CMS, RFC 3161, and OCSP structures. |
| `Timestamp\Client` / `Timestamp\Config` | RFC 3161 timestamp request/response codec. |
| `Ocsp\Client` | RFC 6960 OCSP request builder and response fetcher. |
| `Ltv\ValidationMaterial` | DSS material collection: certificate dedup, AIA/CRL-DP URL extraction, OCSP/CRL retrieval. |
| `Output\Signature` | The `/Sig` value dictionary, including the `/ByteRange` and `/Contents` placeholders. |
| `Output\Widget` | Signature and empty-field widget annotations. |
| `Output\Dss` | DSS/VRI object emitter. |
| `Output\DocTimeStamp` | The `/Type /DocTimeStamp` value object (B-LTA). |
| `Output\PdfString` | Shared PDF string-token encoder. |
| `Exception` | Library exception type. |
### Design
The codecs are pure and perform no file or network access. HTTP transports (TSA, OCSP, CRL) and key loading are injected by the host as callables, so the consuming application owns networking and SSRF protection. This keeps the package deterministic and testable, and lets the host reuse its existing HTTP stack and URL allow-list.
---
## Requirements
- PHP 8.2 or later
- Extensions: `hash`, `openssl`
- Composer
---
## Installation
```bash
composer require tecnickcom/tc-lib-pdf-sign
```
This package is normally pulled in transitively by `tc-lib-pdf`; install it directly only when you need the low-level primitives on their own.
---
## Usage
For signing PDF documents, use the `tc-lib-pdf` fluent `signature()` facade, which drives this package end to end:
```php
$pdf->signature()->configure([
'profile' => 'pades-b-t', // legacy | pades-b-b | pades-b-t | pades-b-lt | pades-b-lta
'digest_algorithm' => 'sha256', // sha256 | sha384 | sha512
'signcert' => 'file:///path/to/cert.pem',
'privkey' => 'file:///path/to/key.pem',
'password' => '',
]);
```
See the full guide in [`tc-lib-pdf/doc/DIGITAL_SIGNATURES.md`](https://github.com/tecnickcom/tc-lib-pdf/blob/main/doc/DIGITAL_SIGNATURES.md) and the runnable `E007`/`E008`/`E009`/`E081` signature examples in `tc-lib-pdf`.
### Low-level: building a detached CMS
`Cms\Builder` produces a detached CAdES-BES CMS over arbitrary bytes (the host supplies the ByteRange-covered content). It is the core of PAdES B-B:
```php
<?php
require_once __DIR__ . '/vendor/autoload.php';
use Com\Tecnick\Pdf\Sign\Cms\Builder;
$privateKey = openssl_pkey_get_private('file:///path/to/key.pem');
$certDer = ''; // DER bytes of the signing certificate
$content = ''; // detached content bytes (the ByteRange-covered document)
$cms = (new Builder())->sign(
$content, // detached content bytes (the ByteRange-covered document)
$certDer, // DER of the signing certificate
$privateKey, // OpenSSLAsymmetricKey (RSA or EC)
[], // additional chain certificates (DER), if any
'sha256', // digest algorithm
time(), // signing time (Unix timestamp)
);
// $cms is a DER-encoded CMS ContentInfo ready for injection into /Contents.
```
---
## Standards
- **ETSI EN 319 142-1** - PAdES baseline profiles (B-B, B-T, B-LT, B-LTA)
- **ISO 32000-1 / ISO 32000-2** - PDF digital signatures and the Document Security Store
- **RFC 5652** - Cryptographic Message Syntax (CMS)
- **RFC 5035** - ESS `signing-certificate-v2` attribute
- **RFC 3161** - Time-Stamp Protocol (TSP)
- **RFC 6960** - Online Certificate Status Protocol (OCSP)
- **RFC 5280** - X.509 certificates and CRLs
---
## Development
```bash
make deps
make help
make qa
```
---
## Packaging
```bash
make rpm
make deb
```
For system packages, bootstrap with:
```php
require_once '/usr/share/php/Com/Tecnick/Pdf/Sign/autoload.php';
```
---
## Contributing
Contributions are welcome. Please review [CONTRIBUTING.md](CONTRIBUTING.md), [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md), and [SECURITY.md](SECURITY.md).
+1
View File
@@ -0,0 +1 @@
1
+62
View File
@@ -0,0 +1,62 @@
# Security Policy
This document describes the security policy for **tc-lib-pdf-sign**.
---
## Supported Versions
Security fixes are applied only to the **latest stable release** on the `main` branch.
We strongly recommend always running the latest release.
---
## Reporting a Vulnerability
**Please do not open a public GitHub issue for security vulnerabilities.**
If you discover a security vulnerability — or suspect one — follow responsible disclosure:
1. **Email** the maintainer directly at **[info@tecnick.com](mailto:info@tecnick.com)** with the subject line:
`[SECURITY] tc-lib-pdf-sign <brief description>`
2. Include as much detail as possible (see [What to include](#what-to-include) below).
3. You will receive an acknowledgement as soon as possible.
4. We will work on a fix or mitigation as promptly as the complexity of the issue allows.
If you do not receive a timely response, please follow up by replying to the same email thread.
---
## What to Include
A high-quality report helps us triage and fix issues faster. Please provide:
- **Description** — a clear summary of the vulnerability and its potential impact.
- **Affected component** — which class, method, or feature is involved (e.g., `HTML::render()`, font loading, image processing).
- **Steps to reproduce** — a minimal, self-contained PHP script or unit test that demonstrates the issue.
- **Expected vs. actual behaviour** — what you expected to happen and what actually happened.
- **Environment** — PHP version, OS, library version (output of `composer show tecnickcom/tc-lib-pdf-sign`).
- **CVE / CWE reference** (optional) — if you have already identified a relevant classification.
- **Suggested fix** (optional) — a patch or proposed mitigation if you have one.
---
## Security Best Practices for Integrators
Integrators are responsible for sanitising input **before** passing it to the library. We recommend:
- **Validate and sanitise all user-supplied data**. Use a dedicated sanitiser when accepting content from end users.
- **Keep dependencies up to date.** Run `composer update` regularly and monitor advisories via [Packagist Security Advisories](https://packagist.org/packages/tecnickcom/tc-lib-pdf-sign) or tools such as `composer audit`.
- **Pin versions in production.** Use `composer.lock` and review changes on every update.
---
## Contact
| Channel | Details |
|---------|---------|
| Security email | [info@tecnick.com](mailto:info@tecnick.com) |
| Project website | <https://tcpdf.org> |
| GitHub repository | <https://github.com/tecnickcom/tc-lib-pdf-sign> |
| Packagist | <https://packagist.org/packages/tecnickcom/tc-lib-pdf-sign> |
+1
View File
@@ -0,0 +1 @@
1.1.3
+68
View File
@@ -0,0 +1,68 @@
{
"name": "tecnickcom/tc-lib-pdf-sign",
"description": "PHP library to create and embed digital signatures (PKCS#7 / CAdES / PAdES) in PDF documents",
"type": "library",
"homepage": "https://tcpdf.org",
"license": "LGPL-3.0-or-later",
"keywords": [
"tc-lib-pdf-sign",
"PDF",
"signature",
"digital-signature",
"PAdES",
"CAdES",
"PKCS7",
"timestamp",
"sign"
],
"authors": [
{
"name": "Nicola Asuni",
"email": "info@tecnick.com",
"role": "lead"
}
],
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/tecnickcom"
}
],
"require": {
"php": ">=8.2",
"ext-hash": "*",
"ext-openssl": "*",
"ext-pcre": "*"
},
"minimum-stability": "stable",
"prefer-stable": true,
"require-dev": {
"pdepend/pdepend": "^2.16",
"phpunit/phpunit": "^11.5 || ^12.5 || ^13.2"
},
"autoload": {
"psr-4": {
"Com\\Tecnick\\Pdf\\Sign\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Test\\": "test"
}
},
"support": {
"issues": "https://github.com/tecnickcom/tc-lib-pdf-sign/issues",
"source": "https://github.com/tecnickcom/tc-lib-pdf-sign"
},
"scripts": {
"test": "@php -d xdebug.mode=coverage vendor/bin/phpunit --stderr test",
"analyse": ["@analyse:src", "@analyse:test"],
"analyse:src": "mago --config mago.src.toml analyze src",
"analyse:test": "mago --config mago.test.toml analyze test",
"cs-check": ["@cs-check:src", "@cs-check:test"],
"cs-check:src": "mago --config mago.src.toml lint src",
"cs-check:test": "mago --config mago.test.toml lint test",
"cs-fix": "mago fmt src test",
"qa": ["@cs-check", "@analyse", "@test"]
}
}
+56
View File
@@ -0,0 +1,56 @@
#:schema https://mago.carthage.software/1.43.0/schema.json
version = "1"
php-version = "8.2.0"
[source]
workspace = "."
paths = ["src"]
includes = ["vendor"]
excludes = []
[source.glob]
literal-separator = true
[formatter]
print-width = 120
tab-width = 4
use-tabs = false
[linter]
integrations = []
[linter.rules]
ambiguous-function-call = { enabled = false }
literal-named-argument = { enabled = false }
cyclomatic-complexity = { enabled = false }
excessive-parameter-list = { enabled = true, threshold = 10 }
halstead = { enabled = true, effort-threshold = 7000 }
identity-comparison = { enabled = true }
kan-defect = { enabled = false }
no-boolean-flag-parameter = { enabled = false }
no-else-clause = { enabled = false }
no-empty = { enabled = true }
too-many-methods = { enabled = false }
no-isset = { enabled = true, allow-array-checks = true }
[analyzer]
plugins = []
find-unused-definitions = true
find-unused-expressions = true
analyze-dead-code = true
memoize-properties = true
check-throws = true
unchecked-exceptions = [
"Error",
"LogicException",
"ReflectionException",
]
unchecked-exception-classes = []
check-missing-override = true
find-unused-parameters = true
strict-list-index-checks = true
strict-array-index-existence = true
allow-array-truthy-operand = false
no-boolean-literal-comparison = true
check-missing-type-hints = true
register-super-globals = true
+66
View File
@@ -0,0 +1,66 @@
#:schema https://mago.carthage.software/1.43.0/schema.json
version = "1"
php-version = "8.2.0"
[source]
workspace = "."
paths = ["src", "test"]
includes = ["vendor"]
excludes = []
[source.glob]
literal-separator = true
[formatter]
print-width = 120
tab-width = 4
use-tabs = false
[linter]
integrations = ["phpunit"]
[linter.rules]
ambiguous-function-call = { enabled = false }
literal-named-argument = { enabled = false }
assertion-style = { enabled = false }
cyclomatic-complexity = { enabled = false }
excessive-parameter-list = { enabled = false }
halstead = { enabled = false, effort-threshold = 7000 }
identity-comparison = { enabled = false }
kan-defect = { enabled = false }
no-boolean-flag-parameter = { enabled = false }
no-else-clause = { enabled = false }
no-empty = { enabled = false }
no-empty-catch-clause = { enabled = false }
no-isset = { enabled = false }
readable-literal = { enabled = false }
str-contains = { enabled = false }
strict-assertions = { enabled = false }
strict-behavior = { enabled = false }
strict-types = { enabled = false }
too-many-methods = { enabled = false }
[analyzer]
plugins = []
find-unused-definitions = true
find-unused-expressions = true
analyze-dead-code = true
memoize-properties = true
check-throws = false
unchecked-exceptions = [
"Error",
"LogicException",
"ReflectionException",
"PHPUnit\\Framework\\Exception",
"PHPUnit\\Framework\\ExpectationFailedException",
"PHPUnit\\Framework\\UnknownClassOrInterfaceException",
]
unchecked-exception-classes = []
check-missing-override = true
find-unused-parameters = true
strict-list-index-checks = true
strict-array-index-existence = true
allow-array-truthy-operand = false
no-boolean-literal-comparison = true
check-missing-type-hints = true
register-super-globals = true
+400
View File
@@ -0,0 +1,400 @@
#
# OpenSSL example configuration file.
# See doc/man5/config.pod for more info.
#
# This is mostly being used for generation of certificate requests,
# but may be used for auto loading of providers
# Note that you can include other files from the main configuration
# file using the .include directive.
#.include filename
# This definition stops the following lines choking if HOME isn't
# defined.
HOME = .
# Use this in order to automatically load providers.
openssl_conf = openssl_init
# Comment out the next line to ignore configuration errors
config_diagnostics = 1
# Extra OBJECT IDENTIFIER info:
# oid_file = $ENV::HOME/.oid
oid_section = new_oids
# To use this configuration file with the "-extfile" option of the
# "openssl x509" utility, name here the section containing the
# X.509v3 extensions to use:
# extensions =
# (Alternatively, use a configuration file that has only
# X.509v3 extensions in its main [= default] section.)
[ new_oids ]
# We can add new OIDs in here for use by 'ca', 'req' and 'ts'.
# Add a simple OID like this:
# testoid1=1.2.3.4
# Or use config file substitution like this:
# testoid2=${testoid1}.5.6
# Policies used by the TSA examples.
tsa_policy1 = 1.2.3.4.1
tsa_policy2 = 1.2.3.4.5.6
tsa_policy3 = 1.2.3.4.5.7
# For FIPS
# Optionally include a file that is generated by the OpenSSL fipsinstall
# application. This file contains configuration data required by the OpenSSL
# fips provider. It contains a named section e.g. [fips_sect] which is
# referenced from the [provider_sect] below.
# Refer to the OpenSSL security policy for more information.
# .include fipsmodule.cnf
[openssl_init]
providers = provider_sect
ssl_conf = ssl_sect
# List of providers to load
[provider_sect]
default = default_sect
legacy = legacy_sect
# The fips section name should match the section name inside the
# included fipsmodule.cnf.
# fips = fips_sect
# If no providers are activated explicitly, the default one is activated implicitly.
# See man 7 OSSL_PROVIDER-default for more details.
#
# If you add a section explicitly activating any other provider(s), you most
# probably need to explicitly activate the default provider, otherwise it
# becomes unavailable in openssl. As a consequence applications depending on
# OpenSSL may not work correctly which could lead to significant system
# problems including inability to remotely access the system.
[default_sect]
activate = 1
[legacy_sect]
activate = 1
####################################################################
[ ca ]
default_ca = CA_default # The default ca section
####################################################################
[ CA_default ]
dir = ./demoCA # Where everything is kept
certs = $dir/certs # Where the issued certs are kept
crl_dir = $dir/crl # Where the issued crl are kept
database = $dir/index.txt # database index file.
#unique_subject = no # Set to 'no' to allow creation of
# several certs with same subject.
new_certs_dir = $dir/newcerts # default place for new certs.
certificate = $dir/cacert.pem # The CA certificate
serial = $dir/serial # The current serial number
crlnumber = $dir/crlnumber # the current crl number
# must be commented out to leave a V1 CRL
crl = $dir/crl.pem # The current CRL
private_key = $dir/private/cakey.pem# The private key
x509_extensions = usr_cert # The extensions to add to the cert
# Comment out the following two lines for the "traditional"
# (and highly broken) format.
name_opt = ca_default # Subject Name options
cert_opt = ca_default # Certificate field options
# Extension copying option: use with caution.
# copy_extensions = copy
# Extensions to add to a CRL. Note: Netscape communicator chokes on V2 CRLs
# so this is commented out by default to leave a V1 CRL.
# crlnumber must also be commented out to leave a V1 CRL.
# crl_extensions = crl_ext
default_days = 365 # how long to certify for
default_crl_days= 30 # how long before next CRL
default_md = default # use public key default MD
preserve = no # keep passed DN ordering
# A few difference way of specifying how similar the request should look
# For type CA, the listed attributes must be the same, and the optional
# and supplied fields are just that :-)
policy = policy_match
# For the CA policy
[ policy_match ]
countryName = match
stateOrProvinceName = match
organizationName = match
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
# For the 'anything' policy
# At this point in time, you must list all acceptable 'object'
# types.
[ policy_anything ]
countryName = optional
stateOrProvinceName = optional
localityName = optional
organizationName = optional
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
####################################################################
[ req ]
default_bits = 2048
default_keyfile = privkey.pem
distinguished_name = req_distinguished_name
attributes = req_attributes
x509_extensions = v3_ca # The extensions to add to the self signed cert
# Passwords for private keys if not present they will be prompted for
# input_password = secret
# output_password = secret
# This sets a mask for permitted string types. There are several options.
# default: PrintableString, T61String, BMPString.
# pkix : PrintableString, BMPString (PKIX recommendation before 2004)
# utf8only: only UTF8Strings (PKIX recommendation after 2004).
# nombstr : PrintableString, T61String (no BMPStrings or UTF8Strings).
# MASK:XXXX a literal mask value.
# WARNING: ancient versions of Netscape crash on BMPStrings or UTF8Strings.
string_mask = utf8only
# req_extensions = v3_req # The extensions to add to a certificate request
[ req_distinguished_name ]
countryName = Country Name (2 letter code)
countryName_default = AU
countryName_min = 2
countryName_max = 2
stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = Some-State
localityName = Locality Name (eg, city)
0.organizationName = Organization Name (eg, company)
0.organizationName_default = Internet Widgits Pty Ltd
# we can do this but it is not needed normally :-)
#1.organizationName = Second Organization Name (eg, company)
#1.organizationName_default = World Wide Web Pty Ltd
organizationalUnitName = Organizational Unit Name (eg, section)
#organizationalUnitName_default =
commonName = Common Name (e.g. server FQDN or YOUR name)
commonName_max = 64
emailAddress = Email Address
emailAddress_max = 64
# SET-ex3 = SET extension number 3
[ req_attributes ]
challengePassword = A challenge password
challengePassword_min = 4
challengePassword_max = 20
unstructuredName = An optional company name
[ usr_cert ]
# These extensions are added when 'ca' signs a request.
# This goes against PKIX guidelines but some CAs do it and some software
# requires this to avoid interpreting an end user certificate as a CA.
basicConstraints=CA:FALSE
# This is typical in keyUsage for a client certificate.
# keyUsage = nonRepudiation, digitalSignature, keyEncipherment
# PKIX recommendations harmless if included in all certificates.
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer
# This stuff is for subjectAltName and issuerAltname.
# Import the email address.
# subjectAltName=email:copy
# An alternative to produce certificates that aren't
# deprecated according to PKIX.
# subjectAltName=email:move
# Copy subject details
# issuerAltName=issuer:copy
# This is required for TSA certificates.
# extendedKeyUsage = critical,timeStamping
[ v3_req ]
# Extensions to add to a certificate request
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
[ v3_ca ]
# Extensions for a typical CA
# PKIX recommendation.
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer
basicConstraints = critical,CA:true
# Key usage: this is typical for a CA certificate. However since it will
# prevent it being used as an test self-signed certificate it is best
# left out by default.
# keyUsage = cRLSign, keyCertSign
# Include email address in subject alt name: another PKIX recommendation
# subjectAltName=email:copy
# Copy issuer details
# issuerAltName=issuer:copy
# DER hex encoding of an extension: beware experts only!
# obj=DER:02:03
# Where 'obj' is a standard or added object
# You can even override a supported extension:
# basicConstraints= critical, DER:30:03:01:01:FF
[ crl_ext ]
# CRL extensions.
# Only issuerAltName and authorityKeyIdentifier make any sense in a CRL.
# issuerAltName=issuer:copy
authorityKeyIdentifier=keyid:always
[ proxy_cert_ext ]
# These extensions should be added when creating a proxy certificate
# This goes against PKIX guidelines but some CAs do it and some software
# requires this to avoid interpreting an end user certificate as a CA.
basicConstraints=CA:FALSE
# This is typical in keyUsage for a client certificate.
# keyUsage = nonRepudiation, digitalSignature, keyEncipherment
# PKIX recommendations harmless if included in all certificates.
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer
# This stuff is for subjectAltName and issuerAltname.
# Import the email address.
# subjectAltName=email:copy
# An alternative to produce certificates that aren't
# deprecated according to PKIX.
# subjectAltName=email:move
# Copy subject details
# issuerAltName=issuer:copy
# This really needs to be in place for it to be a proxy certificate.
proxyCertInfo=critical,language:id-ppl-anyLanguage,pathlen:3,policy:foo
####################################################################
[ tsa ]
default_tsa = tsa_config1 # the default TSA section
[ tsa_config1 ]
# These are used by the TSA reply generation only.
dir = ./demoCA # TSA root directory
serial = $dir/tsaserial # The current serial number (mandatory)
crypto_device = builtin # OpenSSL engine to use for signing
signer_cert = $dir/tsacert.pem # The TSA signing certificate
# (optional)
certs = $dir/cacert.pem # Certificate chain to include in reply
# (optional)
signer_key = $dir/private/tsakey.pem # The TSA private key (optional)
signer_digest = sha256 # Signing digest to use. (Optional)
default_policy = tsa_policy1 # Policy if request did not specify it
# (optional)
other_policies = tsa_policy2, tsa_policy3 # acceptable policies (optional)
digests = sha1, sha256, sha384, sha512 # Acceptable message digests (mandatory)
accuracy = secs:1, millisecs:500, microsecs:100 # (optional)
clock_precision_digits = 0 # number of digits after dot. (optional)
ordering = yes # Is ordering defined for timestamps?
# (optional, default: no)
tsa_name = yes # Must the TSA name be included in the reply?
# (optional, default: no)
ess_cert_id_chain = no # Must the ESS cert id chain be included?
# (optional, default: no)
ess_cert_id_alg = sha1 # algorithm to compute certificate
# identifier (optional, default: sha1)
[insta] # CMP using Insta Demo CA
# Message transfer
server = pki.certificate.fi:8700
# proxy = # set this as far as needed, e.g., http://192.168.1.1:8080
# tls_use = 0
path = pkix/
# Server authentication
recipient = "/C=FI/O=Insta Demo/CN=Insta Demo CA" # or set srvcert or issuer
ignore_keyusage = 1 # potentially needed quirk
unprotected_errors = 1 # potentially needed quirk
extracertsout = insta.extracerts.pem
# Client authentication
ref = 3078 # user identification
secret = pass:insta # can be used for both client and server side
# Generic message options
cmd = ir # default operation, can be overridden on cmd line with, e.g., kur
# Certificate enrollment
subject = "/CN=openssl-cmp-test"
newkey = insta.priv.pem
out_trusted = insta.ca.crt
certout = insta.cert.pem
[pbm] # Password-based protection for Insta CA
# Server and client authentication
ref = $insta::ref # 3078
secret = $insta::secret # pass:insta
[signature] # Signature-based protection for Insta CA
# Server authentication
trusted = insta.ca.crt # does not include keyUsage digitalSignature
# Client authentication
secret = # disable PBM
key = $insta::newkey # insta.priv.pem
cert = $insta::certout # insta.cert.pem
[ir]
cmd = ir
[cr]
cmd = cr
[kur]
# Certificate update
cmd = kur
oldcert = $insta::certout # insta.cert.pem
[rr]
# Certificate revocation
cmd = rr
oldcert = $insta::certout # insta.cert.pem
[ssl_sect]
system_default = system_default_sect
[system_default_sect]
CipherString = DEFAULT:@SECLEVEL=2
+15
View File
@@ -0,0 +1,15 @@
{
"source-providers": [
{
"in": "src as source",
"exclude": "vendor",
"name": "/\\.(php)$/"
}
],
"plugins": [
],
"analysers": [
],
"services": [
]
}
+31
View File
@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
bootstrap="vendor/autoload.php"
colors="true"
displayDetailsOnTestsThatTriggerDeprecations="true"
displayDetailsOnTestsThatTriggerErrors="true"
displayDetailsOnTestsThatTriggerNotices="true"
displayDetailsOnTestsThatTriggerWarnings="true"
displayDetailsOnPhpunitDeprecations="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="tc-lib-pdf-sign Test Suite">
<directory>./test</directory>
</testsuite>
</testsuites>
<source>
<include>
<directory suffix=".php">src</directory>
</include>
</source>
<coverage>
<report>
<clover outputFile="target/coverage/coverage.xml"/>
<html outputDirectory="target/coverage" lowUpperBound="50" highLowerBound="90"/>
</report>
</coverage>
<logging>
<junit outputFile="target/logs/junit.xml"/>
</logging>
</phpunit>
@@ -0,0 +1,30 @@
<?php
/**
* autoload.php
*
* Autoloader for Tecnick.com libraries
*
* @since 2015-03-04
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2015-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
\spl_autoload_register(
function ($class) {
$prefix = 'Com\\Tecnick\\';
$len = \strlen($prefix);
if (\strncmp($prefix, $class, $len) !== 0) {
return;
}
$relative_class = \substr($class, $len);
$file = \dirname(\dirname(__DIR__)).'/'.\str_replace('\\', '/', $relative_class).'.php';
if (\file_exists($file)) {
require $file;
}
}
);
@@ -0,0 +1,7 @@
~#PKGNAME#~ (~#VERSION#~-~#RELEASE#~) UNRELEASED; urgency=low
* Please check the
https://github.com/~#VENDOR#~/~#PROJECT#~
commit history
-- Nicola Asuni <info@tecnick.com> ~#DATE#~
@@ -0,0 +1,17 @@
Source: ~#PKGNAME#~
Maintainer: Nicola Asuni <info@tecnick.com>
Section: php
Priority: optional
Build-Depends: debhelper-compat (= 13)
Standards-Version: 4.7.2
Rules-Requires-Root: no
Homepage: https://github.com/~#VENDOR#~/~#PROJECT#~
Vcs-Git: https://github.com/~#VENDOR#~/~#PROJECT#~.git
Vcs-Browser: https://github.com/~#VENDOR#~/~#PROJECT#~
Package: ~#PKGNAME#~
Provides: php-~#PROJECT#~
Architecture: all
Depends: php (>= 8.2.0), ${misc:Depends}
Description: PHP PDF Sign Library
PHP library to sign data for PDF.
@@ -0,0 +1,20 @@
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: ~#PROJECT#~
Source: https://github.com/~#VENDOR#~/~#PROJECT#~
Files: *
Copyright: Copyright 2001-2026 Nicola Asuni <info@tecnick.com>
License: LGPL-3
License: LGPL-3
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/> or
/usr/share/common-licenses/LGPL-3
@@ -0,0 +1,3 @@
#!/usr/bin/make -f
%:
dh $@
@@ -0,0 +1 @@
3.0 (quilt)
@@ -0,0 +1,4 @@
version=4
opts=filenamemangle=s/.+\/v?(\d[\d\.]+)\.tar\.gz/~#PKGNAME#~_$1.orig.tar.gz/ \
https://github.com/~#VENDOR#~/~#PROJECT#~/tags \
.*/archive/refs/tags/v?(\d[\d\.]*)\.tar\.gz
@@ -0,0 +1,44 @@
# SPEC file
%global c_vendor %{_vendor}
%global gh_owner %{_owner}
%global gh_project %{_project}
Name: %{_package}
Version: %{_version}
Release: %{_release}%{?dist}
Summary: PHP library to sign data for PDF
License: LGPLv3+
URL: https://github.com/%{gh_owner}/%{gh_project}
BuildArch: noarch
Requires: php(language) >= 8.2.0
Requires: php-date
Requires: php-hash
Requires: php-openssl
Requires: php-pcre
Provides: php-composer(%{c_vendor}/%{gh_project}) = %{version}
Provides: php-%{gh_project} = %{version}
%description
PHP library to sign data for PDF
%build
#(cd %{_current_directory} && make build)
%install
rm -rf "%{buildroot}"
(cd "%{_current_directory}" && make install DESTDIR="%{buildroot}")
%files
%attr(-,root,root) %{_libpath}
%attr(-,root,root) %{_docpath}
%docdir %{_docpath}
# Optional config files can be listed here when used by a project.
%changelog
* Wed Sep 23 2026 Nicola Asuni <info@tecnick.com> 1.0.0-1
- Initial Commit
+317
View File
@@ -0,0 +1,317 @@
<?php
declare(strict_types=1);
/**
* Asn1.php
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
namespace Com\Tecnick\Pdf\Sign\Cms;
use Com\Tecnick\Pdf\Sign\Exception;
/**
* Com\Tecnick\Pdf\Sign\Cms\Asn1
*
* Minimal DER ASN.1 encoder/decoder used to assemble and inspect CMS/CAdES
* structures, RFC 3161 timestamp messages, and OCSP requests. Only the subset
* of ASN.1 needed by PDF signatures is implemented.
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*/
class Asn1
{
/**
* Encode a DER length octet sequence.
*
* @param int<0, max> $length Number of content octets.
*
* @throws Exception If the length is too large to encode.
*/
public function encodeLength(int $length): string
{
if ($length < 128) {
return \chr($length);
}
$encoded = '';
$value = $length;
while ($value > 0) {
$encoded = \chr((int) ($value & 0xFF)) . $encoded;
$value = (int) ($value / 256);
}
$encodedLength = \strlen($encoded);
if ($encodedLength > 0x7F) {
// Defensive: unreachable, as this needs content larger than 2^1016
// bytes, which is unrepresentable and unallocatable.
throw new Exception('ASN.1 length encoding overflow');
}
return \chr(0x80 | $encodedLength) . $encoded;
}
/**
* Encode a non-negative integer as a DER INTEGER.
*
* @param int<0, max> $value Integer value.
*
* @throws Exception If the length cannot be encoded.
*/
public function encodeInteger(int $value): string
{
$data = '';
$num = $value;
while ($num > 0) {
$data = \chr((int) ($num & 0xFF)) . $data;
$num = (int) ($num / 256);
}
if ($data === '') {
$data = "\x00";
}
if ((\ord($data[0]) & 0x80) !== 0) {
$data = "\x00" . $data;
}
return "\x02" . $this->encodeLength(\strlen($data)) . $data;
}
/**
* Encode a big-endian magnitude byte string as a DER INTEGER.
*
* Trims superfluous leading zero octets and prepends a zero octet when the
* most significant bit is set, so the value stays non-negative. Useful for
* certificate serial numbers.
*
* @throws Exception If the length cannot be encoded.
*/
public function encodeIntegerBytes(string $bytes): string
{
$len = \strlen($bytes);
$start = 0;
while ($start < ($len - 1) && $bytes[$start] === "\x00" && (\ord($bytes[$start + 1]) & 0x80) === 0) {
++$start;
}
$magnitude = \substr($bytes, $start);
if ($magnitude === '') {
$magnitude = "\x00";
}
if ((\ord($magnitude[0]) & 0x80) !== 0) {
$magnitude = "\x00" . $magnitude;
}
return "\x02" . $this->encodeLength(\strlen($magnitude)) . $magnitude;
}
/**
* Encode a DER BOOLEAN.
*/
public function encodeBoolean(bool $value): string
{
return "\x01\x01" . ($value ? "\xFF" : "\x00");
}
/**
* Encode a DER NULL.
*/
public function encodeNull(): string
{
return "\x05\x00";
}
/**
* Encode a DER OCTET STRING.
*
* @throws Exception If the length cannot be encoded.
*/
public function encodeOctetString(string $value): string
{
return "\x04" . $this->encodeLength(\strlen($value)) . $value;
}
/**
* Wrap pre-encoded content in a DER SEQUENCE.
*
* @throws Exception If the length cannot be encoded.
*/
public function encodeSequence(string $value): string
{
return "\x30" . $this->encodeLength(\strlen($value)) . $value;
}
/**
* Wrap pre-encoded content in a DER SET.
*
* @throws Exception If the length cannot be encoded.
*/
public function encodeSet(string $value): string
{
return "\x31" . $this->encodeLength(\strlen($value)) . $value;
}
/**
* Wrap pre-encoded content in a context-specific constructed tag [n].
*
* @param int<0, 30> $number Context tag number.
*
* @throws Exception If the length cannot be encoded.
*/
public function encodeContext(int $number, string $value): string
{
return \chr(0xA0 | ($number & 0x1F)) . $this->encodeLength(\strlen($value)) . $value;
}
/**
* Encode a dotted OID string as a DER OBJECT IDENTIFIER.
*
* @throws Exception If the OID is malformed or the length cannot be encoded.
*/
public function encodeObjectIdentifier(string $oid): string
{
$parts = \array_map('intval', \explode('.', $oid));
if (\count($parts) < 2) {
throw new Exception('Invalid OID');
}
$data = \chr((int) ((($parts[0] * 40) + ($parts[1] ?? 0)) & 0xFF));
$count = \count($parts);
for ($idx = 2; $idx < $count; ++$idx) {
$part = (int) ($parts[$idx] ?? 0);
if ($part < 0) {
$part = 0;
}
$data .= $this->encodeBase128Int($part);
}
return "\x06" . $this->encodeLength(\strlen($data)) . $data;
}
/**
* Encode a non-negative integer in base-128 with continuation bits.
*
* @param int<0, max> $value Integer value.
*/
public function encodeBase128Int(int $value): string
{
$bytes = [$value & 0x7F];
$value = (int) ($value / 128);
while ($value > 0) {
\array_unshift($bytes, ($value & 0x7F) | 0x80);
$value = (int) ($value / 128);
}
$out = '';
foreach ($bytes as $byte) {
$out .= \chr($byte);
}
return $out;
}
/**
* Read one DER TLV triplet starting at the given offset.
*
* @param int $offset Read cursor; advanced past the parsed element.
*
* @return array{tag: int, value: string, raw: string}
*
* @throws Exception If the structure or length is malformed.
*/
public function readTlv(string $data, int &$offset): array
{
if ($offset >= \strlen($data)) {
throw new Exception('Malformed ASN.1 structure');
}
$start = $offset;
$tag = \ord($data[$offset]);
++$offset;
$length = $this->readLength($data, $offset);
if (($offset + $length) > \strlen($data)) {
throw new Exception('Malformed ASN.1 length');
}
$value = \substr($data, $offset, $length);
$offset += $length;
$raw = \substr($data, $start, $offset - $start);
return ['tag' => $tag, 'value' => $value, 'raw' => $raw];
}
/**
* Read a DER length starting at the given offset.
*
* @param int $offset Read cursor; advanced past the length octets.
*
* @throws Exception If the length is malformed or unsupported.
*/
public function readLength(string $data, int &$offset): int
{
if ($offset >= \strlen($data)) {
throw new Exception('Malformed ASN.1 length');
}
$first = \ord($data[$offset]);
++$offset;
if (($first & 0x80) === 0) {
return $first;
}
$numBytes = $first & 0x7F;
if ($numBytes < 1 || $numBytes > 4 || ($offset + $numBytes) > \strlen($data)) {
throw new Exception('Unsupported ASN.1 length');
}
$length = 0;
for ($idx = 0; $idx < $numBytes; ++$idx) {
$length = ($length * 256) + \ord($data[$offset + $idx]);
}
$offset += $numBytes;
return $length;
}
/**
* Decode a DER INTEGER content string to a PHP integer.
*
* @param string $value Content octets (without tag/length).
*
* @throws Exception If the value is empty.
*/
public function decodeInteger(string $value): int
{
if ($value === '') {
throw new Exception('Invalid ASN.1 integer');
}
$int = 0;
$len = \strlen($value);
for ($idx = 0; $idx < $len; ++$idx) {
$int = ($int * 256) + \ord($value[$idx]);
}
return $int;
}
}
+347
View File
@@ -0,0 +1,347 @@
<?php
declare(strict_types=1);
/**
* Builder.php
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
namespace Com\Tecnick\Pdf\Sign\Cms;
use Com\Tecnick\Pdf\Sign\Exception;
use OpenSSLAsymmetricKey;
/**
* Com\Tecnick\Pdf\Sign\Cms\Builder
*
* Native builder for a detached CAdES-BES CMS SignedData, suitable for a
* PAdES B-B signature (/SubFilter /ETSI.CAdES.detached). It assembles the
* SignerInfo with the mandatory signed attributes (content-type,
* message-digest, signing-time, and the ESS signing-certificate-v2 that plain
* openssl_pkcs7_sign() cannot add), signs the DER SET OF signed attributes with
* openssl_sign(), and encodes the ContentInfo. RSA and ECDSA keys are
* supported with SHA-256/384/512.
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*/
final class Builder
{
private const OID_SIGNED_DATA = '1.2.840.113549.1.7.2';
private const OID_DATA = '1.2.840.113549.1.7.1';
private const OID_CONTENT_TYPE = '1.2.840.113549.1.9.3';
private const OID_MESSAGE_DIGEST = '1.2.840.113549.1.9.4';
private const OID_SIGNING_TIME = '1.2.840.113549.1.9.5';
private const OID_SIGNING_CERTIFICATE_V2 = '1.2.840.113549.1.9.16.2.47';
private const OID_SIGNATURE_TIMESTAMP = '1.2.840.113549.1.9.16.2.14';
private const OID_RSA_ENCRYPTION = '1.2.840.113549.1.1.1';
/**
* Digest name to [digest OID, openssl algo constant, ecdsa-with-* OID].
*
* @var array<string, array{string, int, string}>
*/
private const DIGESTS = [
'sha256' => ['2.16.840.1.101.3.4.2.1', OPENSSL_ALGO_SHA256, '1.2.840.10045.4.3.2'],
'sha384' => ['2.16.840.1.101.3.4.2.2', OPENSSL_ALGO_SHA384, '1.2.840.10045.4.3.3'],
'sha512' => ['2.16.840.1.101.3.4.2.3', OPENSSL_ALGO_SHA512, '1.2.840.10045.4.3.4'],
];
private Asn1 $asn1;
public function __construct(?Asn1 $asn1 = null)
{
$this->asn1 = $asn1 ?? new Asn1();
}
/**
* Produce a detached CAdES-BES CMS SignedData over the given content.
*
* @param string $data Detached content bytes (the signed data).
* @param string $signerCertDer DER of the signing certificate.
* @param OpenSSLAsymmetricKey $privateKey Signing private key (RSA or EC).
* @param list<string> $chainCertsDer Additional certificates (DER) to embed.
* @param string $digestAlgorithm One of the DIGESTS keys.
* @param int $signingTime Unix timestamp for the signing-time attribute.
* @param (callable(string): string)|null $signatureTimestamp Optional provider that receives the
* raw SignerInfo signature bytes and returns a DER-encoded RFC 3161
* timestamp token (ContentInfo). When supplied, the token is embedded as
* the id-aa-signatureTimeStampToken unsigned attribute (PAdES B-T).
* @param bool $includeSigningTime Whether to add the CMS signing-time signed
* attribute. The legacy (ISO 32000-1) profile includes it; PAdES-BASELINE
* forbids it (ETSI EN 319 142-1) and carries the time in the /M signature
* dictionary entry instead.
*
* @return string DER-encoded CMS ContentInfo.
*
* @throws Exception If the digest or key is unsupported, or signing fails.
*/
public function sign(
string $data,
string $signerCertDer,
OpenSSLAsymmetricKey $privateKey,
array $chainCertsDer,
string $digestAlgorithm,
int $signingTime,
?callable $signatureTimestamp = null,
bool $includeSigningTime = true,
): string {
[$digestOid, $opensslAlgo, $ecdsaOid] = $this->algorithms($digestAlgorithm);
[$signatureOid, $signatureHasNullParams] = $this->signatureAlgorithm($privateKey, $ecdsaOid);
$messageDigest = \hash($digestAlgorithm, $data, true);
$certHash = \hash($digestAlgorithm, $signerCertDer, true);
$signedAttributes = $this->signedAttributes(
$messageDigest,
$certHash,
$digestAlgorithm,
$digestOid,
$signingTime,
$includeSigningTime,
);
$signedAttributesForSigning = $this->asn1->encodeSet($signedAttributes);
$signature = '';
if (!\openssl_sign($signedAttributesForSigning, $signature, $privateKey, $opensslAlgo)) {
throw new Exception('Unable to sign the CMS signed attributes');
}
$unsignedAttributes = $signatureTimestamp === null
? ''
: $this->signatureTimestampAttributes($signatureTimestamp, $signature);
$signerInfo = $this->asn1->encodeSequence(
$this->asn1->encodeInteger(1)
. $this->issuerAndSerialNumber($signerCertDer)
. $this->algorithmIdentifier($digestOid, false)
. $this->asn1->encodeContext(0, $signedAttributes)
. $this->algorithmIdentifier($signatureOid, $signatureHasNullParams)
. $this->asn1->encodeOctetString($signature)
. $unsignedAttributes,
);
$certificates = $this->asn1->encodeContext(0, $signerCertDer . \implode('', $chainCertsDer));
$signedData = $this->asn1->encodeSequence(
$this->asn1->encodeInteger(1)
. $this->asn1->encodeSet($this->algorithmIdentifier($digestOid, false))
. $this->asn1->encodeSequence($this->asn1->encodeObjectIdentifier(self::OID_DATA))
. $certificates
. $this->asn1->encodeSet($signerInfo),
);
return $this->asn1->encodeSequence(
$this->asn1->encodeObjectIdentifier(self::OID_SIGNED_DATA) . $this->asn1->encodeContext(0, $signedData),
);
}
/**
* Resolve the OIDs and openssl constant for a digest name.
*
* @return array{string, int, string} [digest OID, openssl algo, ecdsa OID]
*
* @throws Exception If the digest is unsupported.
*/
private function algorithms(string $digestAlgorithm): array
{
if (!isset(self::DIGESTS[$digestAlgorithm])) {
throw new Exception('Unsupported digest algorithm: ' . $digestAlgorithm);
}
return self::DIGESTS[$digestAlgorithm];
}
/**
* Resolve the signature AlgorithmIdentifier for the signing key.
*
* @return array{string, bool} [signature OID, whether NULL parameters are emitted]
*
* @throws Exception If the key type is unsupported.
*/
private function signatureAlgorithm(OpenSSLAsymmetricKey $privateKey, string $ecdsaOid): array
{
$details = \openssl_pkey_get_details($privateKey);
$type = $details !== false ? $details['type'] ?? -1 : -1;
if ($type === OPENSSL_KEYTYPE_RSA) {
return [self::OID_RSA_ENCRYPTION, true];
}
if ($type === OPENSSL_KEYTYPE_EC) {
return [$ecdsaOid, false];
}
throw new Exception('Unsupported signing key type');
}
/**
* Build the sorted DER SET OF signed attributes content (without the tag).
*
* @throws Exception If encoding fails.
*/
private function signedAttributes(
string $messageDigest,
string $certHash,
string $digestAlgorithm,
string $digestOid,
int $signingTime,
bool $includeSigningTime,
): string {
$attributes = [
$this->attribute(self::OID_CONTENT_TYPE, $this->asn1->encodeObjectIdentifier(self::OID_DATA)),
$this->attribute(self::OID_MESSAGE_DIGEST, $this->asn1->encodeOctetString($messageDigest)),
$this->attribute(self::OID_SIGNING_CERTIFICATE_V2, $this->signingCertificateV2(
$certHash,
$digestAlgorithm,
$digestOid,
)),
];
// The CMS signing-time attribute belongs to the legacy (ISO 32000-1) profile.
// PAdES-BASELINE forbids it (ETSI EN 319 142-1): the signing time is carried by
// the /M entry of the PDF signature dictionary, so validators demote a signature
// that carries signing-time from PAdES-BASELINE-B to the older PAdES-BES format.
if ($includeSigningTime) {
$attributes[] = $this->attribute(self::OID_SIGNING_TIME, $this->encodeTime($signingTime));
}
// DER requires the members of a SET OF to be sorted by their encoding,
// compared as octet strings padded with trailing zero octets.
\usort($attributes, static function (string $one, string $two): int {
$length = \max(\strlen($one), \strlen($two));
return \strcmp(\str_pad($one, $length, "\x00"), \str_pad($two, $length, "\x00"));
});
return \implode('', $attributes);
}
/**
* Build the SignerInfo [1] IMPLICIT unsignedAttrs carrying the signature
* timestamp.
*
* The provider computes an RFC 3161 token over the raw signature bytes
* (CAdES id-aa-signatureTimeStampToken), which is then wrapped as a single
* unsigned Attribute value.
*
* @param callable(string): string $provider Maps the signature bytes to a DER token.
* @param string $signature Raw SignerInfo signature bytes.
*
* @throws Exception If the provider yields an empty or non-string token, or encoding fails.
*/
private function signatureTimestampAttributes(callable $provider, string $signature): string
{
/** @var mixed $token */
$token = $provider($signature);
if (!\is_string($token) || $token === '') {
throw new Exception('Invalid signature timestamp token');
}
return $this->asn1->encodeContext(1, $this->attribute(self::OID_SIGNATURE_TIMESTAMP, $token));
}
/**
* Encode a single Attribute (type plus a one-element value SET).
*
* @throws Exception If encoding fails.
*/
private function attribute(string $oid, string $value): string
{
return $this->asn1->encodeSequence($this->asn1->encodeObjectIdentifier($oid) . $this->asn1->encodeSet($value));
}
/**
* Encode the SigningCertificateV2 attribute value.
*
* The ESSCertIDv2 hashAlgorithm defaults to SHA-256, so it is omitted when
* the digest is SHA-256 and included otherwise (DER default handling).
*
* @throws Exception If encoding fails.
*/
private function signingCertificateV2(string $certHash, string $digestAlgorithm, string $digestOid): string
{
$essCertId = '';
if ($digestAlgorithm !== 'sha256') {
$essCertId .= $this->algorithmIdentifier($digestOid, false);
}
$essCertId .= $this->asn1->encodeOctetString($certHash);
return $this->asn1->encodeSequence($this->asn1->encodeSequence($this->asn1->encodeSequence($essCertId)));
}
/**
* Encode an AlgorithmIdentifier, with optional NULL parameters.
*
* @throws Exception If encoding fails.
*/
private function algorithmIdentifier(string $oid, bool $nullParameters): string
{
$parameters = $nullParameters ? $this->asn1->encodeNull() : '';
return $this->asn1->encodeSequence($this->asn1->encodeObjectIdentifier($oid) . $parameters);
}
/**
* Encode the signing-time value as UTCTime (1950-2049) or GeneralizedTime.
*
* @throws Exception If encoding fails.
*/
private function encodeTime(int $signingTime): string
{
$year = (int) \gmdate('Y', $signingTime);
if ($year >= 1950 && $year < 2050) {
$value = \gmdate('ymdHis', $signingTime) . 'Z';
return "\x17" . $this->asn1->encodeLength(\strlen($value)) . $value;
}
$value = \gmdate('YmdHis', $signingTime) . 'Z';
return "\x18" . $this->asn1->encodeLength(\strlen($value)) . $value;
}
/**
* Build the IssuerAndSerialNumber from the signer certificate.
*
* @throws Exception If the certificate cannot be parsed.
*/
private function issuerAndSerialNumber(string $certDer): string
{
$certOff = 0;
$certTlv = $this->asn1->readTlv($certDer, $certOff);
$tbsOff = 0;
$tbsTlv = $this->asn1->readTlv($certTlv['value'], $tbsOff);
$tbs = $tbsTlv['value'];
$off = 0;
if ($off < \strlen($tbs) && (\ord($tbs[$off]) & 0xE0) === 0xA0) {
$this->asn1->readTlv($tbs, $off); // version [0]
}
$serial = $this->asn1->readTlv($tbs, $off); // serialNumber
$this->asn1->readTlv($tbs, $off); // signature AlgorithmIdentifier
$issuer = $this->asn1->readTlv($tbs, $off); // issuer Name
return $this->asn1->encodeSequence($issuer['raw'] . $serial['raw']);
}
}
+174
View File
@@ -0,0 +1,174 @@
<?php
declare(strict_types=1);
/**
* Config.php
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
namespace Com\Tecnick\Pdf\Sign;
/**
* Com\Tecnick\Pdf\Sign\Config
*
* Immutable signature configuration value object. Captures the signing profile,
* digest algorithm, and certification level, and derives the PDF /SubFilter
* from the selected profile.
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*/
final class Config
{
/**
* Legacy ISO 32000-1 signature (/SubFilter /adbe.pkcs7.detached).
*/
public const PROFILE_LEGACY = 'legacy';
/**
* PAdES baseline B-B (CAdES-based, /SubFilter /ETSI.CAdES.detached).
*/
public const PROFILE_PADES_B_B = 'pades-b-b';
/**
* PAdES baseline B-T (B-B plus a signature timestamp).
*/
public const PROFILE_PADES_B_T = 'pades-b-t';
/**
* PAdES baseline B-LT (B-T plus a Document Security Store).
*/
public const PROFILE_PADES_B_LT = 'pades-b-lt';
/**
* PAdES baseline B-LTA (B-LT plus a document timestamp).
*/
public const PROFILE_PADES_B_LTA = 'pades-b-lta';
/**
* Supported signature profiles.
*
* @var list<string>
*/
public const PROFILES = [
self::PROFILE_LEGACY,
self::PROFILE_PADES_B_B,
self::PROFILE_PADES_B_T,
self::PROFILE_PADES_B_LT,
self::PROFILE_PADES_B_LTA,
];
/**
* Supported CMS digest algorithms.
*
* @var list<string>
*/
public const DIGEST_ALGORITHMS = ['sha256', 'sha384', 'sha512'];
/**
* Selected signature profile (one of the PROFILE_* constants).
*/
public readonly string $profile;
/**
* Selected CMS digest algorithm (one of the DIGEST_ALGORITHMS values).
*/
public readonly string $digestAlgorithm;
/**
* @param string|SignatureProfile $profile Profile identifier or enum case.
* @param string|DigestAlgorithm $digestAlgorithm Digest algorithm name or enum case.
* @param int $certType Certification level (DocMDP P value):
* 0 = approval/UR signature,
* 1 = no changes permitted,
* 2 = form fill-in and signing permitted,
* 3 = as 2 plus annotation changes.
*
* @throws Exception If any option is invalid.
*/
public function __construct(
string|SignatureProfile $profile = self::PROFILE_LEGACY,
string|DigestAlgorithm $digestAlgorithm = 'sha256',
public readonly int $certType = 2,
) {
$profile = $profile instanceof SignatureProfile ? $profile->value : $profile;
$digestAlgorithm = $digestAlgorithm instanceof DigestAlgorithm ? $digestAlgorithm->value : $digestAlgorithm;
if (!\in_array($profile, self::PROFILES, true)) {
throw new Exception('Invalid signature profile: ' . $profile);
}
if (!\in_array($digestAlgorithm, self::DIGEST_ALGORITHMS, true)) {
throw new Exception('Invalid digest algorithm: ' . $digestAlgorithm);
}
if ($certType < 0 || $certType > 3) {
throw new Exception('Invalid certification level (cert_type): ' . $certType);
}
$this->profile = $profile;
$this->digestAlgorithm = $digestAlgorithm;
}
/**
* True when a PAdES profile is selected.
*/
public function isPades(): bool
{
return $this->profile !== self::PROFILE_LEGACY;
}
/**
* PDF /SubFilter value for the selected profile.
*/
public function subFilter(): string
{
return $this->isPades() ? 'ETSI.CAdES.detached' : 'adbe.pkcs7.detached';
}
/**
* Build a Config from the legacy associative-array shape used by
* Tcpdf::setSignature(), for backward compatibility.
*
* @param array<string, mixed> $data Signature options.
*
* @throws Exception If any option is present but of the wrong type or value.
*/
public static function fromArray(array $data): self
{
/** @var mixed $profile */
$profile = $data['profile'] ?? self::PROFILE_LEGACY;
if (!\is_string($profile) && !$profile instanceof SignatureProfile) {
throw new Exception('Invalid signature profile');
}
/** @var mixed $digest */
$digest = $data['digest_algorithm'] ?? 'sha256';
if (!\is_string($digest) && !$digest instanceof DigestAlgorithm) {
throw new Exception('Invalid digest algorithm');
}
/** @var mixed $certType */
$certType = $data['cert_type'] ?? 2;
if (!\is_int($certType)) {
throw new Exception('Invalid certification level (cert_type)');
}
return new self($profile, $digest, $certType);
}
}
@@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
/**
* DigestAlgorithm.php
*
* @since 2026-07-17
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
namespace Com\Tecnick\Pdf\Sign;
/**
* Com\Tecnick\Pdf\Sign\DigestAlgorithm
*
* Backed enum for the supported message-digest algorithms. Unifies the two
* previously identical closed sets: Config::DIGEST_ALGORITHMS (CMS builder) and
* Timestamp\Config::HASH_ALGORITHMS (RFC 3161 message imprint). The backing
* value is the lowercase algorithm name accepted by both.
*
* @since 2026-07-17
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*/
enum DigestAlgorithm: string
{
case Sha256 = 'sha256';
case Sha384 = 'sha384';
case Sha512 = 'sha512';
/**
* Resolve a loose digest algorithm value to the matching enum case.
*
* Accepts the canonical algorithm string (as validated by Config and
* Timestamp\Config) or an enum instance (returned unchanged). Unknown values
* throw, matching the closed set enforced by both configs.
*
* @param string|self $value Digest algorithm name or enum case.
*
* @throws Exception if the value does not match a known digest algorithm.
*/
public static function fromLoose(string|self $value): self
{
if ($value instanceof self) {
return $value;
}
return self::tryFrom($value) ?? throw new Exception('Invalid digest algorithm: ' . $value);
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
/**
* Exception.php
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
namespace Com\Tecnick\Pdf\Sign;
/**
* Com\Tecnick\Pdf\Sign\Exception
*
* Custom Exception class for the PDF signature library.
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*/
class Exception extends \Exception {}
@@ -0,0 +1,226 @@
<?php
declare(strict_types=1);
/**
* ValidationMaterial.php
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
namespace Com\Tecnick\Pdf\Sign\Ltv;
use Com\Tecnick\Pdf\Sign\Exception;
use Com\Tecnick\Pdf\Sign\Ocsp\Client as OcspClient;
/**
* Com\Tecnick\Pdf\Sign\Ltv\ValidationMaterial
*
* Collects the long-term validation (LTV) material embedded in a PDF Document
* Security Store (DSS): the certificate DERs, OCSP responses, and CRLs. URL
* discovery uses the certificate AIA and CRL distribution point extensions;
* network retrieval is delegated to injected transport callables so this class
* stays testable and free of SSRF concerns. The VRI key (SHA-1 of the signature
* Contents) is intentionally not computed here: it belongs to the DSS writer,
* which holds the final signature bytes.
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*/
final class ValidationMaterial
{
private OcspClient $ocsp;
public function __construct(?OcspClient $ocsp = null)
{
$this->ocsp = $ocsp ?? new OcspClient();
}
/**
* Convert a list of PEM certificates to deduplicated DER strings.
*
* @param list<string> $certsPem
*
* @return list<string>
*
* @throws Exception If any certificate is not valid PEM.
*/
public function certificates(array $certsPem): array
{
$seen = [];
$result = [];
foreach ($certsPem as $pem) {
$der = $this->pemToDer($pem);
$fingerprint = \hash('sha256', $der);
if (isset($seen[$fingerprint])) {
continue;
}
$seen[$fingerprint] = true;
$result[] = $der;
}
return $result;
}
/**
* Extract the OCSP responder URLs from a certificate's AIA extension.
*
* Returns an empty list when the certificate has no AIA extension or cannot be
* parsed (LTV collection is best-effort; see extensionText).
*
* @return list<string>
*/
public function certificateOcspUrls(string $certPem): array
{
return $this->extractUris($this->extensionText($certPem, 'authorityInfoAccess'), '~OCSP\s*-\s*URI:(\S+)~i');
}
/**
* Extract the CRL distribution point URLs from a certificate.
*
* Returns an empty list when the certificate has no CRL distribution point or cannot
* be parsed (LTV collection is best-effort; see extensionText).
*
* @return list<string>
*/
public function certificateCrlUrls(string $certPem): array
{
return $this->extractUris($this->extensionText($certPem, 'crlDistributionPoints'), '~URI:(\S+)~');
}
/**
* Fetch OCSP responses for a certificate from the given responder URLs.
*
* @param list<string> $urls
* @param callable $transport Receives (url, DER request) and returns the DER response.
*
* @return list<string> Deduplicated OCSP response bytes.
*
* @throws Exception If the OCSP request cannot be built.
*/
public function fetchOcsp(string $issuerDer, string $leafDer, array $urls, callable $transport): array
{
if ($urls === []) {
return [];
}
$request = $this->ocsp->build($issuerDer, $leafDer);
return $this->fetchDeduplicated($urls, static fn(string $url): mixed => $transport($url, $request));
}
/**
* Fetch CRLs from the given distribution point URLs.
*
* @param list<string> $urls
* @param callable $transport Receives (url) and returns the CRL bytes.
*
* @return list<string> Deduplicated CRL bytes.
*/
public function fetchCrl(array $urls, callable $transport): array
{
return $this->fetchDeduplicated($urls, static fn(string $url): mixed => $transport($url));
}
/**
* Fetch each URL through the callback, skipping failures and duplicates.
*
* @param list<string> $urls
* @param callable(string): mixed $fetch
*
* @return list<string>
*/
private function fetchDeduplicated(array $urls, callable $fetch): array
{
$seen = [];
$result = [];
foreach ($urls as $url) {
try {
/** @var mixed $data */
$data = $fetch($url);
} catch (\Throwable) {
continue;
}
if (!\is_string($data) || $data === '') {
continue;
}
$fingerprint = \hash('sha256', $data);
if (isset($seen[$fingerprint])) {
continue;
}
$seen[$fingerprint] = true;
$result[] = $data;
}
return $result;
}
/**
* Return the human-readable text of a named certificate extension.
*
* LTV material collection is best-effort: a certificate whose extensions cannot be
* parsed (for example a legacy certificate with a negative serial that a strict
* OpenSSL build rejects) yields no extension text, so no OCSP/CRL URLs are derived
* from it, rather than aborting the whole signing operation. The certificate itself
* is still embedded, since its DER bytes are obtained separately (see pemToDer).
*/
private function extensionText(string $certPem, string $name): string
{
$info = \openssl_x509_parse($certPem);
if (!\is_array($info)) {
return '';
}
$extensions = $info['extensions'];
/** @var mixed $value */
$value = $extensions[$name] ?? '';
return \is_string($value) ? $value : '';
}
/**
* Extract and deduplicate the capture group 1 matches of a pattern.
*
* @return list<string>
*/
private function extractUris(string $text, string $pattern): array
{
$matches = [];
\preg_match_all($pattern, $text, $matches);
return \array_values(\array_unique($matches[1] ?? []));
}
/**
* Decode a PEM certificate to DER.
*
* @throws Exception If the PEM cannot be decoded.
*/
private function pemToDer(string $pem): string
{
$stripped = (string) \preg_replace('/-----[^-]+-----|\s+/', '', $pem);
$der = \base64_decode($stripped, true);
if ($der === false) {
throw new Exception('Invalid PEM certificate');
}
return $der;
}
}
+187
View File
@@ -0,0 +1,187 @@
<?php
declare(strict_types=1);
/**
* Client.php
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
namespace Com\Tecnick\Pdf\Sign\Ocsp;
use Com\Tecnick\Pdf\Sign\Cms\Asn1;
use Com\Tecnick\Pdf\Sign\Exception;
/**
* Com\Tecnick\Pdf\Sign\Ocsp\Client
*
* RFC 6960 OCSP request builder. Extracts the subject Name and public key from
* the issuer certificate and the serial number from the target certificate,
* then assembles an OCSPRequest with a SHA-1 CertID. HTTP transport is injected
* into fetch() so the codec stays pure and testable while the host controls
* networking (and SSRF protection).
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*/
final class Client
{
private Asn1 $asn1;
public function __construct(?Asn1 $asn1 = null)
{
$this->asn1 = $asn1 ?? new Asn1();
}
/**
* Build a DER-encoded RFC 6960 OCSPRequest for a single certificate.
*
* @param string $issuerDer DER of the issuing certificate.
* @param string $leafDer DER of the certificate whose status is queried.
*
* @throws Exception If either certificate cannot be parsed or encoded.
*/
public function build(string $issuerDer, string $leafDer): string
{
$issuer = $this->extractSubjectAndPublicKey($issuerDer);
$issuerNameHash = \hash('sha1', $issuer['subject'], true);
$issuerKeyHash = \hash('sha1', $issuer['public_key'], true);
$serial = $this->extractSerialNumber($leafDer);
$algId = $this->asn1->encodeSequence(
$this->asn1->encodeObjectIdentifier('1.3.14.3.2.26') . $this->asn1->encodeNull(),
);
$certId = $this->asn1->encodeSequence(
$algId . $this->asn1->encodeOctetString($issuerNameHash) . $this->asn1->encodeOctetString($issuerKeyHash)
. $this->asn1->encodeIntegerBytes($serial),
);
$requestList = $this->asn1->encodeSequence($this->asn1->encodeSequence($certId));
return $this->asn1->encodeSequence($this->asn1->encodeSequence($requestList));
}
/**
* Build the request and submit it through the given transport.
*
* @param string $url OCSP responder URL.
* @param string $issuerDer DER of the issuing certificate.
* @param string $leafDer DER of the target certificate.
* @param callable $transport Receives (url, DER request) and must return the
* DER response string.
*
* @throws Exception If building, transport, or the response type fails.
*/
public function fetch(string $url, string $issuerDer, string $leafDer, callable $transport): string
{
$request = $this->build($issuerDer, $leafDer);
/** @var mixed $response */
$response = $transport($url, $request);
if (!\is_string($response)) {
throw new Exception('Invalid OCSP transport response');
}
return $response;
}
/**
* Extract the raw DER of the subject Name and the public-key bytes from a
* DER-encoded X.509 certificate.
*
* The subject bytes are the full DER of the subject Name SEQUENCE. The
* public-key bytes are the subjectPublicKey BIT STRING value without the
* leading unused-bits octet. For an OCSP CertID the issuerNameHash and
* issuerKeyHash are computed over the SUBJECT of the issuing certificate,
* so this reads the subject field (not the issuer field).
*
* @return array{subject: string, public_key: string}
*
* @throws Exception If the certificate cannot be parsed.
*/
public function extractSubjectAndPublicKey(string $certDer): array
{
$tbs = $this->tbsCertificate($certDer);
$off = 0;
$this->skipOptionalVersion($tbs, $off);
$this->asn1->readTlv($tbs, $off); // serialNumber
$this->asn1->readTlv($tbs, $off); // signature AlgorithmIdentifier
$this->asn1->readTlv($tbs, $off); // issuer Name
$this->asn1->readTlv($tbs, $off); // validity
$subjectStart = $off;
$this->asn1->readTlv($tbs, $off); // subject Name
$subjectDer = \substr($tbs, $subjectStart, $off - $subjectStart);
$spki = $this->asn1->readTlv($tbs, $off); // subjectPublicKeyInfo
$spkiOff = 0;
$this->asn1->readTlv($spki['value'], $spkiOff); // algorithm
$bitStr = $this->asn1->readTlv($spki['value'], $spkiOff); // subjectPublicKey BIT STRING
return [
'subject' => $subjectDer,
'public_key' => \substr($bitStr['value'], 1),
];
}
/**
* Extract the raw serialNumber INTEGER content octets from a DER-encoded
* X.509 certificate.
*
* @throws Exception If the certificate cannot be parsed.
*/
public function extractSerialNumber(string $certDer): string
{
$tbs = $this->tbsCertificate($certDer);
$off = 0;
$this->skipOptionalVersion($tbs, $off);
$serial = $this->asn1->readTlv($tbs, $off); // serialNumber
return $serial['value'];
}
/**
* Return the TBSCertificate content octets of a DER-encoded certificate.
*
* @throws Exception If the certificate cannot be parsed.
*/
private function tbsCertificate(string $certDer): string
{
$certOff = 0;
$certTlv = $this->asn1->readTlv($certDer, $certOff);
$tbsOff = 0;
$tbsTlv = $this->asn1->readTlv($certTlv['value'], $tbsOff);
return $tbsTlv['value'];
}
/**
* Skip the optional [0] EXPLICIT version field if present.
*
* @param int $off Read cursor; advanced past the version when present.
*
* @throws Exception If the version field is malformed.
*/
private function skipOptionalVersion(string $tbs, int &$off): void
{
if ($off < \strlen($tbs) && (\ord($tbs[$off]) & 0xE0) === 0xA0) {
$this->asn1->readTlv($tbs, $off);
}
}
}
@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
/**
* DocTimeStamp.php
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
namespace Com\Tecnick\Pdf\Sign\Output;
/**
* Com\Tecnick\Pdf\Sign\Output\DocTimeStamp
*
* Emits a document timestamp value object (/Type /DocTimeStamp,
* /SubFilter /ETSI.RFC3161) whose /Contents is a bare RFC 3161 timestamp token.
* It is added in an incremental update to reach PAdES B-LTA. It shares the
* /ByteRange and /Contents placeholders with the signature value object so the
* host's signing pass locates them the same way for either object type.
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*/
final class DocTimeStamp
{
/**
* SubFilter for an RFC 3161 document timestamp.
*/
public const SUB_FILTER = 'ETSI.RFC3161';
/**
* Emit the /DocTimeStamp value object.
*
* @param int $objectId Object number for the value object.
* @param int $contentsLength Placeholder length reserved for the token.
*/
public function valueObject(int $objectId, int $contentsLength = Signature::DEFAULT_CONTENTS_LENGTH): string
{
$out = $objectId . " 0 obj\n";
$out .= '<< /Type /DocTimeStamp /Filter /Adobe.PPKLite /SubFilter /' . self::SUB_FILTER . ' ';
$out .= Signature::BYTE_RANGE_PLACEHOLDER;
$out .= ' /Contents<' . \str_repeat('0', \max(0, $contentsLength)) . '>';
return $out . " >>\nendobj\n";
}
}
+183
View File
@@ -0,0 +1,183 @@
<?php
declare(strict_types=1);
/**
* Dss.php
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
namespace Com\Tecnick\Pdf\Sign\Output;
use Com\Tecnick\Pdf\Sign\Exception;
/**
* Com\Tecnick\Pdf\Sign\Output\Dss
*
* Emits the Document Security Store (DSS) PDF objects for a single signature:
* the certificate, OCSP, and CRL streams, a VRI entry, and the DSS dictionary.
* The object number is passed by reference and advanced, and the concatenated
* object bytes are returned. Stream encryption is delegated to an optional
* encryptor callable so the emitter does not depend on the host encryption object.
*
* The VRI key is the uppercase base-16 SHA-1 digest of the signature Contents
* bytes, per ISO 32000-2 clause 12.8.4.3.
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*/
final class Dss
{
/**
* Emit the DSS objects for a signature's validation material.
*
* @param array{certs: list<string>, ocsp: list<string>, crls: list<string>} $material
* @param string $signatureContents Signature /Contents bytes (hex-decoded,
* including any placeholder padding), hashed for the VRI key.
* @param int $pon Current object number; advanced by reference.
* @param callable|null $encryptor Optional fn(string $data, int $objectId): string.
*
* @return array{objects: array<int, string>, object_id: int} The emitted object
* bodies keyed by object number, and the DSS dictionary object number
* (an empty map and 0 when there is no material to emit). The keyed shape
* feeds an incremental-update writer directly, one xref entry per object.
*
* @throws Exception If the encryptor returns a non-string value.
*/
public function emit(array $material, string $signatureContents, int &$pon, ?callable $encryptor = null): array
{
if ($material['certs'] === [] && $material['ocsp'] === [] && $material['crls'] === []) {
return ['objects' => [], 'object_id' => 0];
}
$objects = [];
$certIds = $this->emitStreams($material['certs'], $pon, $objects, $encryptor);
$ocspIds = $this->emitStreams($material['ocsp'], $pon, $objects, $encryptor);
$crlIds = $this->emitStreams($material['crls'], $pon, $objects, $encryptor);
$vriKey = \strtoupper(\sha1($signatureContents));
$vriObjectId = ++$pon;
$objects[$vriObjectId] = $this->vriObject($vriObjectId, $certIds, $ocspIds, $crlIds);
$dssObjectId = ++$pon;
$objects[$dssObjectId] = $this->dssObject($dssObjectId, $vriKey, $vriObjectId, $certIds, $ocspIds, $crlIds);
return ['objects' => $objects, 'object_id' => $dssObjectId];
}
/**
* Emit one stream object per payload and return the assigned object numbers.
*
* @param list<string> $items
* @param array<int, string> $objects Emitted object bodies keyed by number; appended to.
*
* @return list<int>
*
* @throws Exception If the encryptor returns a non-string value.
*/
private function emitStreams(array $items, int &$pon, array &$objects, ?callable $encryptor): array
{
$ids = [];
foreach ($items as $item) {
$objectId = ++$pon;
$ids[] = $objectId;
$stream = $encryptor !== null ? $this->encryptStream($encryptor, $item, $objectId) : $item;
$objects[$objectId] =
$objectId
. " 0 obj\n"
. '<< /Length '
. \strlen($stream)
. " >>\n"
. "stream\n"
. $stream
. "\nendstream\n"
. "endobj\n";
}
return $ids;
}
/**
* @throws Exception If the encryptor returns a non-string value.
*/
private function encryptStream(callable $encryptor, string $data, int $objectId): string
{
/** @var mixed $result */
$result = $encryptor($data, $objectId);
if (!\is_string($result)) {
throw new Exception('Invalid stream encryptor result');
}
return $result;
}
/**
* @param list<int> $certIds
* @param list<int> $ocspIds
* @param list<int> $crlIds
*/
private function vriObject(int $objectId, array $certIds, array $ocspIds, array $crlIds): string
{
$out = $objectId . " 0 obj\n" . '<< /Type /VRI';
$out .= $this->referenceArray('Cert', $certIds);
$out .= $this->referenceArray('OCSP', $ocspIds);
$out .= $this->referenceArray('CRL', $crlIds);
return $out . " >>\nendobj\n";
}
/**
* @param list<int> $certIds
* @param list<int> $ocspIds
* @param list<int> $crlIds
*/
private function dssObject(
int $objectId,
string $vriKey,
int $vriObjectId,
array $certIds,
array $ocspIds,
array $crlIds,
): string {
$out = $objectId . " 0 obj\n" . '<< /Type /DSS';
$out .= ' /VRI << /' . $vriKey . ' ' . $vriObjectId . ' 0 R >>';
$out .= $this->referenceArray('Certs', $certIds);
$out .= $this->referenceArray('OCSPs', $ocspIds);
$out .= $this->referenceArray('CRLs', $crlIds);
return $out . " >>\nendobj\n";
}
/**
* Render a named array of indirect references, or the empty string.
*
* @param list<int> $ids
*/
private function referenceArray(string $name, array $ids): string
{
if ($ids === []) {
return '';
}
$refs = '';
foreach ($ids as $id) {
$refs .= ' ' . $id . ' 0 R';
}
return ' /' . $name . ' [' . $refs . ' ]';
}
}
@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
/**
* PdfString.php
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
namespace Com\Tecnick\Pdf\Sign\Output;
use Com\Tecnick\Pdf\Sign\Exception;
/**
* Com\Tecnick\Pdf\Sign\Output\PdfString
*
* Encodes a text value as a PDF string token, either through a host-supplied
* encoder (which may apply UTF-16, escaping, and encryption) or, when none is
* given, a minimal literal-string fallback for ASCII content.
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*/
final class PdfString
{
/**
* Encode a text value as a PDF string token.
*
* @param callable|null $encoder fn(string $text, int $objectId): string
*
* @throws Exception If the encoder returns a non-string value.
*/
public static function encode(string $text, int $objectId, ?callable $encoder = null): string
{
if ($encoder === null) {
return '(' . \strtr($text, ['\\' => '\\\\', '(' => '\\(', ')' => '\\)']) . ')';
}
/** @var mixed $result */
$result = $encoder($text, $objectId);
if (!\is_string($result)) {
throw new Exception('Invalid string encoder result');
}
return $result;
}
}
@@ -0,0 +1,103 @@
<?php
declare(strict_types=1);
/**
* Signature.php
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
namespace Com\Tecnick\Pdf\Sign\Output;
use Com\Tecnick\Pdf\Sign\Exception;
/**
* Com\Tecnick\Pdf\Sign\Output\Signature
*
* Emits the /Sig value dictionary (the object referenced by a signature field's
* /V): the fixed skeleton, the /SubFilter, and the /ByteRange and /Contents
* placeholders that the host rewrites while signing, plus the optional
* Name/Location/Reason/ContactInfo strings.
*
* The /Reference (DocMDP or UR3 transform) and the /M date token are supplied by
* the caller as ready fragments, because their content and formatting depend on
* host state (certification level, user rights, timezone, encryption). This keeps
* the byte skeleton and the signing-critical placeholders in one place while
* letting the host own the semantic parts. String encoding (escaping, UTF-16,
* encryption) of the info values is delegated to an injected encoder.
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*/
final class Signature
{
/**
* ByteRange placeholder rewritten by the host once the byte offsets are known.
*/
public const BYTE_RANGE_PLACEHOLDER = '/ByteRange[0 ********** ********** **********]';
/**
* Default number of hex zero placeholder characters reserved for /Contents.
*/
public const DEFAULT_CONTENTS_LENGTH = 11_742;
/**
* Info string entries, in output order.
*
* @var list<string>
*/
private const INFO_KEYS = ['Name', 'Location', 'Reason', 'ContactInfo'];
/**
* Emit the /Sig value object.
*
* @param int $objectId Object number for the /Sig value object.
* @param string $subFilter e.g. "ETSI.CAdES.detached" or "adbe.pkcs7.detached".
* @param string $reference Ready /Reference fragment (DocMDP or UR3 transform),
* leading space included, or '' for an approval signature.
* @param array<string, string> $info Optional Name/Location/Reason/ContactInfo.
* @param string $dateValue Ready (already encoded) PDF string token for /M.
* @param int $contentsLength Placeholder length for /Contents.
* @param callable|null $stringEncoder fn(string $text, int $objectId): string returning a PDF string token.
*
* @throws Exception If the string encoder returns a non-string value.
*/
public function valueObject(
int $objectId,
string $subFilter,
string $reference,
array $info,
string $dateValue,
int $contentsLength = self::DEFAULT_CONTENTS_LENGTH,
?callable $stringEncoder = null,
): string {
$out = $objectId . " 0 obj\n";
$out .= '<< /Type /Sig /Filter /Adobe.PPKLite /SubFilter /' . $subFilter . ' ';
$out .= self::BYTE_RANGE_PLACEHOLDER;
$out .= ' /Contents<' . \str_repeat('0', \max(0, $contentsLength)) . '>';
$out .= $reference;
foreach (self::INFO_KEYS as $key) {
$value = $info[$key] ?? '';
if ($value !== '') {
$out .= ' /' . $key . ' ' . PdfString::encode($value, $objectId, $stringEncoder);
}
}
return $out . ' /M ' . $dateValue . " >>\nendobj\n";
}
}
+79
View File
@@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
/**
* Widget.php
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
namespace Com\Tecnick\Pdf\Sign\Output;
use Com\Tecnick\Pdf\Sign\Exception;
/**
* Com\Tecnick\Pdf\Sign\Output\Widget
*
* Emits a signature field's widget annotation (/Subtype /Widget, /FT /Sig). The
* same shape serves the signed field (with a /V reference to the /Sig value
* object) and the reserved empty approval fields (no /V). The rectangle, the
* page object number, and any appearance fragment are computed by the host,
* which knows the page geometry and appearance resources.
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*/
final class Widget
{
/**
* Emit a signature widget annotation object.
*
* @param int $objectId Annotation object number.
* @param string $rect Rectangle coordinates "x0 y0 x1 y1".
* @param int $pageObjectId Object number of the page the widget is on (/P).
* @param string $fieldName Partial field name (/T).
* @param int|null $valueObjectId /V value object number; null for an unsigned field.
* @param string $appearance Optional pre-built appearance fragment (e.g. " /AS /N /AP << ... >>").
* @param callable|null $stringEncoder fn(string $text, int $objectId): string.
*
* @throws Exception If the string encoder returns a non-string value.
*/
public function annotation(
int $objectId,
string $rect,
int $pageObjectId,
string $fieldName,
?int $valueObjectId = null,
string $appearance = '',
?callable $stringEncoder = null,
): string {
$out = $objectId . " 0 obj\n";
$out .= '<< /Type /Annot /Subtype /Widget';
$out .= ' /Rect [' . $rect . ']';
$out .= ' /P ' . $pageObjectId . ' 0 R';
$out .= ' /F 4 /FT /Sig';
$out .= ' /T ' . PdfString::encode($fieldName, $objectId, $stringEncoder);
$out .= ' /Ff 0';
$out .= $appearance;
if ($valueObjectId !== null) {
$out .= ' /V ' . $valueObjectId . ' 0 R';
}
return $out . " >>\nendobj\n";
}
}
@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
/**
* SignatureProfile.php
*
* @since 2026-07-17
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
namespace Com\Tecnick\Pdf\Sign;
/**
* Com\Tecnick\Pdf\Sign\SignatureProfile
*
* Backed enum for the supported signature profiles. The backing value of each
* case matches the corresponding Config::PROFILE_* constant validated by Config.
*
* @since 2026-07-17
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*/
enum SignatureProfile: string
{
case Legacy = 'legacy';
case PadesBB = 'pades-b-b';
case PadesBT = 'pades-b-t';
case PadesBLT = 'pades-b-lt';
case PadesBLTA = 'pades-b-lta';
/**
* Resolve a loose signature profile value to the matching enum case.
*
* Accepts the canonical profile string (as validated by Config) or an enum
* instance (returned unchanged). Unknown values throw, matching the closed
* set enforced by Config.
*
* @param string|self $value Signature profile identifier or enum case.
*
* @throws Exception if the value does not match a known signature profile.
*/
public static function fromLoose(string|self $value): self
{
if ($value instanceof self) {
return $value;
}
return self::tryFrom($value) ?? throw new Exception('Invalid signature profile: ' . $value);
}
}
+226
View File
@@ -0,0 +1,226 @@
<?php
declare(strict_types=1);
/**
* Signer.php
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
namespace Com\Tecnick\Pdf\Sign;
use Com\Tecnick\Pdf\Sign\Cms\Builder;
use Com\Tecnick\Pdf\Sign\Ltv\ValidationMaterial;
use Com\Tecnick\Pdf\Sign\Timestamp\Client as TimestampClient;
use OpenSSLAsymmetricKey;
/**
* Com\Tecnick\Pdf\Sign\Signer
*
* Package-internal orchestration entry point that ties the CMS builder, the RFC
* 3161 timestamp codec, and the LTV material collector together behind two
* host-facing calls. It stays transport-injected and free of file and network
* access: the host loads keys and owns HTTP (and SSRF protection).
*
* sign() produces the detached CAdES CMS for a document's ByteRange bytes. For a
* legacy or PAdES B-B profile that is the plain CMS; for B-T and above it also
* requests an RFC 3161 signature timestamp and embeds it as the SignerInfo
* id-aa-signatureTimeStampToken unsigned attribute.
*
* collectValidationMaterial() gathers the certificates, OCSP responses, and CRLs
* a B-LT or B-LTA document needs, shaped for the DSS emitter. The VRI key is not
* computed here: it depends on the final signature Contents and belongs to the
* DSS writer.
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*/
final class Signer
{
/**
* Profiles that require an embedded signature timestamp (B-T and above).
*
* @var list<string>
*/
private const TIMESTAMPED_PROFILES = [
Config::PROFILE_PADES_B_T,
Config::PROFILE_PADES_B_LT,
Config::PROFILE_PADES_B_LTA,
];
private Builder $builder;
private ValidationMaterial $validationMaterial;
public function __construct(?Builder $builder = null, ?ValidationMaterial $validationMaterial = null)
{
$this->builder = $builder ?? new Builder();
$this->validationMaterial = $validationMaterial ?? new ValidationMaterial();
}
/**
* Produce the detached CAdES CMS for a document's ByteRange content.
*
* When the profile is B-T or above, the timestamp client and transport are
* required: the RFC 3161 token is requested over the raw signature bytes and
* embedded as the id-aa-signatureTimeStampToken unsigned attribute.
*
* @param string $content ByteRange-covered document bytes to sign.
* @param string $signerCertDer DER of the signing certificate.
* @param OpenSSLAsymmetricKey $privateKey Signing private key (RSA or EC).
* @param list<string> $chainCertsDer Additional certificates (DER) to embed.
* @param Config $config Signature profile and digest configuration.
* @param int $signingTime Unix timestamp for the signing-time attribute.
* @param TimestampClient|null $timestamp RFC 3161 codec; required for B-T and above.
* @param (callable(string): string)|null $timestampTransport Maps a DER TimeStampReq to a DER
* TimeStampResp; required for B-T and above.
*
* @return string DER-encoded CMS ContentInfo ready for /Contents injection.
*
* @throws Exception If a timestamp is required but not configured, or signing fails.
*/
public function sign(
string $content,
string $signerCertDer,
OpenSSLAsymmetricKey $privateKey,
array $chainCertsDer,
Config $config,
int $signingTime,
?TimestampClient $timestamp = null,
?callable $timestampTransport = null,
): string {
$signatureTimestamp = null;
if (\in_array($config->profile, self::TIMESTAMPED_PROFILES, true)) {
if ($timestamp === null || $timestampTransport === null) {
throw new Exception('Profile ' . $config->profile . ' requires a timestamp client and transport');
}
$signatureTimestamp =
/** @throws Exception */
static fn(string $signature): string => $timestamp->requestToken($signature, $timestampTransport);
}
// PAdES-BASELINE carries the signing time in the /M dictionary entry and forbids
// the CMS signing-time attribute; only the legacy profile embeds it.
return $this->builder->sign(
$content,
$signerCertDer,
$privateKey,
$chainCertsDer,
$config->digestAlgorithm,
$signingTime,
$signatureTimestamp,
!$config->isPades(),
);
}
/**
* Collect the long-term validation material for an ordered certificate chain.
*
* The chain must be ordered leaf-first, each entry followed by its issuer.
* For every certificate that has an issuer in the chain, OCSP is attempted
* against the responder URLs found in its AIA extension; CRLs are attempted
* against every certificate's CRL distribution points. A null transport skips
* that revocation source. Responses are deduplicated across the whole chain.
*
* @param list<string> $chainPem Certificates in PEM, leaf first up to the root.
* @param (callable(string, string): (string|false))|null $ocspTransport Maps (url, DER request) to
* the DER response, or null to skip OCSP.
* @param (callable(string): (string|false))|null $crlTransport Maps a url to the CRL bytes, or null
* to skip CRLs.
*
* @return array{certs: list<string>, ocsp: list<string>, crls: list<string>} DSS-ready material.
*
* @throws Exception If a certificate cannot be parsed or converted.
*/
public function collectValidationMaterial(
array $chainPem,
?callable $ocspTransport = null,
?callable $crlTransport = null,
): array {
$certs = [];
foreach ($chainPem as $pem) {
$certs[] = ['pem' => $pem, 'der' => $this->pemToDer($pem)];
}
$ocsp = [];
$crls = [];
foreach ($certs as $idx => $cert) {
$issuer = $certs[$idx + 1] ?? null;
if ($ocspTransport !== null && $issuer !== null) {
$urls = $this->validationMaterial->certificateOcspUrls($cert['pem']);
$ocsp = [
...$ocsp,
...$this->validationMaterial->fetchOcsp($issuer['der'], $cert['der'], $urls, $ocspTransport),
];
}
if ($crlTransport !== null) {
$urls = $this->validationMaterial->certificateCrlUrls($cert['pem']);
$crls = [...$crls, ...$this->validationMaterial->fetchCrl($urls, $crlTransport)];
}
}
$certDers = \array_map(static fn(array $cert): string => $cert['der'], $certs);
return [
'certs' => $this->deduplicate($certDers),
'ocsp' => $this->deduplicate($ocsp),
'crls' => $this->deduplicate($crls),
];
}
/**
* Deduplicate a list of binary blobs by content, preserving first-seen order.
*
* @param list<string> $items
*
* @return list<string>
*/
private function deduplicate(array $items): array
{
$seen = [];
$result = [];
foreach ($items as $item) {
$fingerprint = \hash('sha256', $item);
if (isset($seen[$fingerprint])) {
continue;
}
$seen[$fingerprint] = true;
$result[] = $item;
}
return $result;
}
/**
* Decode a PEM certificate to DER.
*
* @throws Exception If the PEM cannot be decoded.
*/
private function pemToDer(string $pem): string
{
$stripped = (string) \preg_replace('/-----[^-]+-----|\s+/', '', $pem);
$der = \base64_decode($stripped, true);
if ($der === false) {
throw new Exception('Invalid PEM certificate');
}
return $der;
}
}
@@ -0,0 +1,177 @@
<?php
declare(strict_types=1);
/**
* Client.php
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
namespace Com\Tecnick\Pdf\Sign\Timestamp;
use Com\Tecnick\Pdf\Sign\Cms\Asn1;
use Com\Tecnick\Pdf\Sign\Exception;
/**
* Com\Tecnick\Pdf\Sign\Timestamp\Client
*
* RFC 3161 timestamp codec. Builds a TimeStampReq for a signature, parses a
* TimeStampResp to extract the timestamp token, and maps digest algorithms to
* their OIDs. HTTP transport is intentionally not part of this class: pass a
* transport callable to requestToken() so the codec stays pure and testable
* while the host controls networking (and SSRF protection).
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*/
final class Client
{
private Asn1 $asn1;
public function __construct(
private readonly Config $config,
?Asn1 $asn1 = null,
) {
$this->asn1 = $asn1 ?? new Asn1();
}
/**
* Build a DER-encoded RFC 3161 TimeStampReq for the given signature bytes.
*
* @param string $signature Signature (or any bytes) to be timestamped.
*
* @throws Exception If encoding fails or a nonce cannot be generated.
*/
public function buildRequest(string $signature): string
{
$hashAlgo = $this->config->hashAlgorithm;
$hash = \hash($hashAlgo, $signature, true);
$oid = $this->hashAlgorithmOid($hashAlgo);
$messageImprint = $this->asn1->encodeSequence(
$this->asn1->encodeSequence($this->asn1->encodeObjectIdentifier($oid) . $this->asn1->encodeNull())
. $this->asn1->encodeOctetString($hash),
);
$body = $this->asn1->encodeInteger(1) . $messageImprint;
if ($this->config->policyOid !== '') {
$body .= $this->asn1->encodeObjectIdentifier($this->config->policyOid);
}
if ($this->config->nonceEnabled) {
try {
$nonce = \random_int(1, PHP_INT_MAX);
} catch (\Random\RandomException $e) {
// Defensive: the CSPRNG failing is not reproducible in a unit test.
throw new Exception('Unable to generate random nonce: ' . $e->getMessage(), 0, $e);
}
$body .= $this->asn1->encodeInteger($nonce);
}
$body .= $this->asn1->encodeBoolean(true);
return $this->asn1->encodeSequence($body);
}
/**
* Extract the timestamp token from a DER-encoded RFC 3161 TimeStampResp.
*
* @param string $response DER-encoded timestamp response.
*
* @return string DER-encoded timestamp token (ContentInfo).
*
* @throws Exception If the response is empty, malformed, or rejected.
*/
public function parseResponse(string $response): string
{
if ($response === '') {
throw new Exception('Empty TSA response');
}
$offset = 0;
$root = $this->asn1->readTlv($response, $offset);
if ($root['tag'] !== 0x30 || $offset !== \strlen($response)) {
throw new Exception('Invalid TSA response');
}
$inner = 0;
$statusSeq = $this->asn1->readTlv($root['value'], $inner);
if ($statusSeq['tag'] !== 0x30) {
throw new Exception('Invalid TSA status response');
}
$statusOffset = 0;
$status = $this->asn1->readTlv($statusSeq['value'], $statusOffset);
if ($status['tag'] !== 0x02) {
throw new Exception('Invalid TSA status code');
}
$statusCode = $this->asn1->decodeInteger($status['value']);
if ($statusCode !== 0 && $statusCode !== 1) {
throw new Exception('TSA request rejected');
}
if ($inner >= \strlen($root['value'])) {
throw new Exception('Missing TSA token');
}
$token = $this->asn1->readTlv($root['value'], $inner);
if ($token['tag'] !== 0x30) {
throw new Exception('Invalid TSA token structure');
}
return $token['raw'];
}
/**
* Build the request, submit it through the given transport, and parse the
* returned token.
*
* @param string $signature Signature bytes to timestamp.
* @param callable $transport Receives the DER request string and must
* return the DER response string.
*
* @throws Exception If encoding, transport, or parsing fails.
*/
public function requestToken(string $signature, callable $transport): string
{
$request = $this->buildRequest($signature);
/** @var mixed $response */
$response = $transport($request);
if (!\is_string($response)) {
throw new Exception('Invalid TSA transport response');
}
return $this->parseResponse($response);
}
/**
* Map a digest algorithm name to its OID.
*
* @throws Exception If the algorithm is not supported.
*/
public function hashAlgorithmOid(string $algorithm): string
{
return match ($algorithm) {
'sha256' => '2.16.840.1.101.3.4.2.1',
'sha384' => '2.16.840.1.101.3.4.2.2',
'sha512' => '2.16.840.1.101.3.4.2.3',
default => throw new Exception('Unsupported TSA hash algorithm: ' . $algorithm),
};
}
}
@@ -0,0 +1,98 @@
<?php
declare(strict_types=1);
/**
* Config.php
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
namespace Com\Tecnick\Pdf\Sign\Timestamp;
use Com\Tecnick\Pdf\Sign\DigestAlgorithm;
use Com\Tecnick\Pdf\Sign\Exception;
/**
* Com\Tecnick\Pdf\Sign\Timestamp\Config
*
* Immutable RFC 3161 Time Stamping Authority (TSA) configuration. The codec
* fields (hash algorithm, policy OID, nonce) drive request construction; the
* transport fields (host, timeout, credentials, CA file, peer verification)
* are consumed by the caller-provided transport.
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*/
final class Config
{
/**
* Supported TSA message-imprint digest algorithms.
*
* @var list<string>
*/
public const HASH_ALGORITHMS = ['sha256', 'sha384', 'sha512'];
/**
* Selected message-imprint digest algorithm (one of HASH_ALGORITHMS).
*/
public readonly string $hashAlgorithm;
/**
* @param string $host TSA endpoint URL (https).
* @param string|DigestAlgorithm $hashAlgorithm Message-imprint digest name or enum case.
* @param string $policyOid Optional requested TSA policy OID (dotted form).
* @param bool $nonceEnabled Add a random nonce to the request.
* @param int $timeout Transport timeout in seconds (>= 1).
* @param bool $verifyPeer Validate the TSA TLS certificate.
* @param string $username Optional HTTP basic-auth username.
* @param string $password Optional HTTP basic-auth password.
* @param string $cert Optional CA bundle path for the transport.
*
* @throws Exception If any option is invalid.
*/
public function __construct(
public readonly string $host,
string|DigestAlgorithm $hashAlgorithm = 'sha256',
public readonly string $policyOid = '',
public readonly bool $nonceEnabled = true,
public readonly int $timeout = 5,
public readonly bool $verifyPeer = true,
public readonly string $username = '',
#[\SensitiveParameter]
public readonly string $password = '',
public readonly string $cert = '',
) {
$hashAlgorithm = $hashAlgorithm instanceof DigestAlgorithm ? $hashAlgorithm->value : $hashAlgorithm;
$this->hashAlgorithm = $hashAlgorithm;
if ($host === '') {
throw new Exception('Invalid TSA host');
}
if (!\in_array($hashAlgorithm, self::HASH_ALGORITHMS, true)) {
throw new Exception('Invalid TSA hash algorithm: ' . $hashAlgorithm);
}
if ($policyOid !== '' && \preg_match('/^\d+(?:\.\d+)+$/', $policyOid) !== 1) {
throw new Exception('Invalid TSA policy OID: ' . $policyOid);
}
if ($timeout < 1) {
throw new Exception('Invalid TSA timeout: ' . $timeout);
}
}
}
+186
View File
@@ -0,0 +1,186 @@
<?php
declare(strict_types=1);
/**
* Asn1Test.php
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
namespace Test\Cms;
use Com\Tecnick\Pdf\Sign\Cms\Asn1;
use Com\Tecnick\Pdf\Sign\Exception;
use PHPUnit\Framework\TestCase;
/**
* Asn1 Test
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*/
class Asn1Test extends TestCase
{
private Asn1 $asn1;
protected function setUp(): void
{
$this->asn1 = new Asn1();
}
public function testEncodeLengthShortForm(): void
{
$this->assertSame("\x05", $this->asn1->encodeLength(5));
$this->assertSame("\x7F", $this->asn1->encodeLength(127));
}
public function testEncodeLengthLongForm(): void
{
$this->assertSame("\x81\x80", $this->asn1->encodeLength(128));
$this->assertSame("\x82\x01\x00", $this->asn1->encodeLength(256));
}
public function testEncodeInteger(): void
{
$this->assertSame("\x02\x01\x00", $this->asn1->encodeInteger(0));
$this->assertSame("\x02\x01\x7F", $this->asn1->encodeInteger(127));
$this->assertSame("\x02\x02\x00\xFF", $this->asn1->encodeInteger(255));
$this->assertSame("\x02\x02\x01\x00", $this->asn1->encodeInteger(256));
}
public function testEncodeIntegerBytesTrimsAndPads(): void
{
$this->assertSame("\x02\x01\x7F", $this->asn1->encodeIntegerBytes("\x00\x7F"));
$this->assertSame("\x02\x02\x00\x80", $this->asn1->encodeIntegerBytes("\x80"));
}
public function testEncodeBoolean(): void
{
$this->assertSame("\x01\x01\xFF", $this->asn1->encodeBoolean(true));
$this->assertSame("\x01\x01\x00", $this->asn1->encodeBoolean(false));
}
public function testEncodeNull(): void
{
$this->assertSame("\x05\x00", $this->asn1->encodeNull());
}
public function testEncodeOctetStringSequenceSet(): void
{
$this->assertSame("\x04\x02AB", $this->asn1->encodeOctetString('AB'));
$this->assertSame("\x30\x02AB", $this->asn1->encodeSequence('AB'));
$this->assertSame("\x31\x02AB", $this->asn1->encodeSet('AB'));
}
public function testEncodeContext(): void
{
$this->assertSame("\xA0\x02AB", $this->asn1->encodeContext(0, 'AB'));
$this->assertSame("\xA3\x02AB", $this->asn1->encodeContext(3, 'AB'));
}
public function testEncodeObjectIdentifier(): void
{
// sha256WithRSAEncryption: 1.2.840.113549.1.1.11
$this->assertSame(
'06092a864886f70d01010b',
\bin2hex($this->asn1->encodeObjectIdentifier('1.2.840.113549.1.1.11')),
);
}
public function testReadTlvRoundTrip(): void
{
$der = $this->asn1->encodeSequence($this->asn1->encodeInteger(256));
$offset = 0;
$tlv = $this->asn1->readTlv($der, $offset);
$this->assertSame(0x30, $tlv['tag']);
$this->assertSame(\strlen($der), $offset);
$this->assertSame($der, $tlv['raw']);
$inner = 0;
$intTlv = $this->asn1->readTlv($tlv['value'], $inner);
$this->assertSame(0x02, $intTlv['tag']);
$this->assertSame(256, $this->asn1->decodeInteger($intTlv['value']));
}
public function testReadTlvRejectsTruncatedData(): void
{
$this->expectException(Exception::class);
$offset = 0;
$this->asn1->readTlv("\x30\x05\x00", $offset);
}
public function testDecodeIntegerRejectsEmpty(): void
{
$this->expectException(Exception::class);
$this->asn1->decodeInteger('');
}
public function testEncodeIntegerBytesEmptyInputYieldsZero(): void
{
$this->assertSame("\x02\x01\x00", $this->asn1->encodeIntegerBytes(''));
}
public function testEncodeObjectIdentifierRejectsSingleArc(): void
{
$this->expectException(Exception::class);
$this->asn1->encodeObjectIdentifier('1');
}
public function testEncodeObjectIdentifierClampsNegativeArc(): void
{
$this->assertSame('06022a00', \bin2hex($this->asn1->encodeObjectIdentifier('1.2.-1')));
}
public function testReadTlvRejectsEmptyData(): void
{
$this->expectException(Exception::class);
$offset = 0;
$this->asn1->readTlv('', $offset);
}
public function testReadTlvRejectsMissingLength(): void
{
$this->expectException(Exception::class);
$offset = 0;
$this->asn1->readTlv("\x30", $offset);
}
public function testReadTlvRejectsUnsupportedLongFormLength(): void
{
$this->expectException(Exception::class);
$offset = 0;
// 0x85 announces a 5-octet length, which exceeds the supported 4 octets.
$this->asn1->readTlv("\x04\x85\x00\x00\x00\x00\x00", $offset);
}
public function testReadTlvHandlesLongFormLength(): void
{
// A 200-byte payload forces a multi-octet (long-form) DER length.
$payload = \str_repeat("\x41", 200);
$der = $this->asn1->encodeOctetString($payload);
$offset = 0;
$tlv = $this->asn1->readTlv($der, $offset);
$this->assertSame(0x04, $tlv['tag']);
$this->assertSame($payload, $tlv['value']);
$this->assertSame(\strlen($der), $offset);
}
// Coverage note: Asn1::encodeLength() throws on a length needing more than
// 127 octets to represent. That requires content larger than 2^1016 bytes,
// which is unrepresentable by a PHP int and unallocatable, so the guard is
// defensive and cannot be exercised in a unit test.
}
@@ -0,0 +1,422 @@
<?php
declare(strict_types=1);
/**
* BuilderTest.php
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
namespace Test\Cms;
use Com\Tecnick\Pdf\Sign\Cms\Asn1;
use Com\Tecnick\Pdf\Sign\Cms\Builder;
use Com\Tecnick\Pdf\Sign\Exception;
use OpenSSLAsymmetricKey;
use PHPUnit\Framework\TestCase;
/**
* CMS Builder Test
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*/
class BuilderTest extends TestCase
{
private const SIGNING_TIME = 1_700_000_000;
private Asn1 $asn1;
protected function setUp(): void
{
$this->asn1 = new Asn1();
}
public function testSignRsaSha256ProducesVerifiableCms(): void
{
$cred = $this->makeCredential('rsa');
$data = 'The quick brown fox jumps over the lazy dog.';
$builder = new Builder($this->asn1);
$cms = $builder->sign($data, $cred['cert_der'], $cred['key'], [], 'sha256', self::SIGNING_TIME);
$parts = $this->parseSignerInfo($cms);
$this->assertSame(0xA0, $parts['signed_attrs']['tag']);
$this->assertSame(0x04, $parts['signature']['tag']);
$this->assertSame(0xA0, $parts['certificates']['tag']);
$this->assertStringContainsString($cred['cert_der'], $parts['certificates']['value']);
// Cryptographically verify the signature over the DER SET OF signed attributes.
$this->assertVerifies($parts, $cred['cert_pem'], OPENSSL_ALGO_SHA256);
// content-type present and equal to id-data.
$contentType = $this->attributeValue($parts['signed_attrs']['value'], '1.2.840.113549.1.9.3');
$this->assertNotNull($contentType);
$this->assertSame($this->asn1->encodeObjectIdentifier('1.2.840.113549.1.7.1'), $contentType['raw']);
// signing-time is a UTCTime for a 2023 timestamp.
$signingTime = $this->attributeValue($parts['signed_attrs']['value'], '1.2.840.113549.1.9.5');
$this->assertNotNull($signingTime);
$this->assertSame(0x17, $signingTime['tag']);
// message-digest equals SHA-256 of the content.
$messageDigest = $this->attributeValue($parts['signed_attrs']['value'], '1.2.840.113549.1.9.4');
$this->assertNotNull($messageDigest);
$this->assertSame(\hash('sha256', $data, true), $messageDigest['value']);
// signing-certificate-v2 carries the SHA-256 hash of the signer certificate;
// for SHA-256 the ESSCertIDv2 hashAlgorithm is omitted so certHash is first.
$certHash = $this->firstCertHash('1.2.840.113549.1.9.16.2.47', $parts['signed_attrs']['value']);
$this->assertSame(0x04, $certHash['tag']);
$this->assertSame(\hash('sha256', $cred['cert_der'], true), $certHash['value']);
}
public function testSignOmitsSigningTimeForPadesBaseline(): void
{
$cred = $this->makeCredential('rsa');
$data = 'PAdES-BASELINE forbids the CMS signing-time attribute.';
$builder = new Builder($this->asn1);
// includeSigningTime = false: the PAdES-BASELINE case, where the signing time
// is carried by the /M signature dictionary entry rather than the CMS.
$cms = $builder->sign($data, $cred['cert_der'], $cred['key'], [], 'sha256', self::SIGNING_TIME, null, false);
$parts = $this->parseSignerInfo($cms);
// The signature still verifies over the (smaller) DER SET OF signed attributes.
$this->assertVerifies($parts, $cred['cert_pem'], OPENSSL_ALGO_SHA256);
// signing-time (1.2.840.113549.1.9.5) is absent.
$this->assertNull($this->attributeValue($parts['signed_attrs']['value'], '1.2.840.113549.1.9.5'));
// The other mandatory signed attributes remain present.
$this->assertNotNull($this->attributeValue($parts['signed_attrs']['value'], '1.2.840.113549.1.9.3'));
$this->assertNotNull($this->attributeValue($parts['signed_attrs']['value'], '1.2.840.113549.1.9.4'));
$this->assertNotNull($this->attributeValue($parts['signed_attrs']['value'], '1.2.840.113549.1.9.16.2.47'));
}
public function testSignEcSha256ProducesVerifiableCms(): void
{
$cred = $this->makeCredential('ec');
$data = 'elliptic-curve payload';
$builder = new Builder($this->asn1);
$cms = $builder->sign($data, $cred['cert_der'], $cred['key'], [], 'sha256', self::SIGNING_TIME);
$parts = $this->parseSignerInfo($cms);
$this->assertVerifies($parts, $cred['cert_pem'], OPENSSL_ALGO_SHA256);
}
public function testSignRsaSha384IncludesEssCertHashAlgorithm(): void
{
$cred = $this->makeCredential('rsa');
$builder = new Builder($this->asn1);
$cms = $builder->sign('data', $cred['cert_der'], $cred['key'], [], 'sha384', self::SIGNING_TIME);
$parts = $this->parseSignerInfo($cms);
$this->assertVerifies($parts, $cred['cert_pem'], OPENSSL_ALGO_SHA384);
// For a non-default digest, ESSCertIDv2 begins with the hashAlgorithm SEQUENCE.
$scv2 = $this->attributeValue($parts['signed_attrs']['value'], '1.2.840.113549.1.9.16.2.47');
$this->assertNotNull($scv2);
$certsOffset = 0;
$certs = $this->asn1->readTlv($scv2['value'], $certsOffset);
$essOffset = 0;
$ess = $this->asn1->readTlv($certs['value'], $essOffset);
$firstOffset = 0;
$first = $this->asn1->readTlv($ess['value'], $firstOffset);
$this->assertSame(0x30, $first['tag']);
}
public function testSignRsaSha512ProducesVerifiableCms(): void
{
$cred = $this->makeCredential('rsa');
$builder = new Builder($this->asn1);
$cms = $builder->sign('data', $cred['cert_der'], $cred['key'], [], 'sha512', self::SIGNING_TIME);
$parts = $this->parseSignerInfo($cms);
$this->assertVerifies($parts, $cred['cert_pem'], OPENSSL_ALGO_SHA512);
}
public function testSignEmbedsChainCertificates(): void
{
$cred = $this->makeCredential('rsa');
$chainDer = $this->pemToDer((string) \file_get_contents(__DIR__ . '/../data/ocsp_ca.pem'));
$builder = new Builder($this->asn1);
$cms = $builder->sign('data', $cred['cert_der'], $cred['key'], [$chainDer], 'sha256', self::SIGNING_TIME);
$parts = $this->parseSignerInfo($cms);
$this->assertStringContainsString($cred['cert_der'], $parts['certificates']['value']);
$this->assertStringContainsString($chainDer, $parts['certificates']['value']);
}
public function testSignWithoutTimestampHasNoUnsignedAttributes(): void
{
$cred = $this->makeCredential('rsa');
$builder = new Builder($this->asn1);
$cms = $builder->sign('data', $cred['cert_der'], $cred['key'], [], 'sha256', self::SIGNING_TIME);
$parts = $this->parseSignerInfo($cms);
$this->assertNull($parts['unsigned_attrs']);
}
public function testSignEmbedsSignatureTimestampUnsignedAttribute(): void
{
$cred = $this->makeCredential('rsa');
$token = $this->asn1->encodeSequence($this->asn1->encodeOctetString('fake-rfc3161-token'));
$captured = '';
$provider = static function (string $signature) use (&$captured, $token): string {
$captured = $signature;
return $token;
};
$builder = new Builder($this->asn1);
$cms = $builder->sign('data', $cred['cert_der'], $cred['key'], [], 'sha256', self::SIGNING_TIME, $provider);
$parts = $this->parseSignerInfo($cms);
// The signature is cryptographically unchanged by the added unsigned attribute.
$this->assertVerifies($parts, $cred['cert_pem'], OPENSSL_ALGO_SHA256);
// The provider timestamps the raw SignerInfo signature bytes.
$this->assertSame($parts['signature']['value'], $captured);
// unsignedAttrs is a [1] IMPLICIT context tag carrying id-aa-signatureTimeStampToken.
$this->assertNotNull($parts['unsigned_attrs']);
$this->assertSame(0xA1, $parts['unsigned_attrs']['tag']);
$tstValue = $this->attributeValue($parts['unsigned_attrs']['value'], '1.2.840.113549.1.9.16.2.14');
$this->assertNotNull($tstValue);
$this->assertSame($token, $tstValue['raw']);
}
public function testSignRejectsEmptySignatureTimestampToken(): void
{
$cred = $this->makeCredential('rsa');
$provider = static fn(): string => '';
$builder = new Builder($this->asn1);
$this->expectException(Exception::class);
$builder->sign('data', $cred['cert_der'], $cred['key'], [], 'sha256', self::SIGNING_TIME, $provider);
}
public function testSignUsesGeneralizedTimeForFarFuture(): void
{
$cred = $this->makeCredential('rsa');
$builder = new Builder($this->asn1);
// 2100-01-01T00:00:00Z is outside the UTCTime range (1950-2049).
$cms = $builder->sign('data', $cred['cert_der'], $cred['key'], [], 'sha256', 4_102_444_800);
$parts = $this->parseSignerInfo($cms);
$signingTime = $this->attributeValue($parts['signed_attrs']['value'], '1.2.840.113549.1.9.5');
$this->assertNotNull($signingTime);
$this->assertSame(0x18, $signingTime['tag']);
}
public function testSignRejectsUnsupportedDigest(): void
{
$cred = $this->makeCredential('rsa');
$builder = new Builder($this->asn1);
$this->expectException(Exception::class);
$builder->sign('data', $cred['cert_der'], $cred['key'], [], 'md5', self::SIGNING_TIME);
}
public function testSignFailsWithNonSigningKey(): void
{
$cred = $this->makeCredential('rsa');
$publicKey = \openssl_pkey_get_public($cred['cert_pem']);
if ($publicKey === false) {
$this->fail('Unable to load public key');
}
$builder = new Builder($this->asn1);
$this->expectException(Exception::class);
\set_error_handler(static fn(): bool => true);
try {
$builder->sign('data', $cred['cert_der'], $publicKey, [], 'sha256', self::SIGNING_TIME);
} finally {
\restore_error_handler();
}
}
public function testSignRejectsUnsupportedKeyType(): void
{
$cred = $this->makeCredential('dsa');
$builder = new Builder($this->asn1);
$this->expectException(Exception::class);
$builder->sign('data', $cred['cert_der'], $cred['key'], [], 'sha256', self::SIGNING_TIME);
}
/**
* Generate a private key and a matching self-signed certificate.
*
* @return array{key: OpenSSLAsymmetricKey, cert_pem: string, cert_der: string}
*/
private function makeCredential(string $keyType): array
{
$config = [
'config' => __DIR__ . '/../../openssl.cnf',
'digest_alg' => 'sha256',
'private_key_bits' => 2048,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
];
if ($keyType === 'ec') {
$config['private_key_type'] = OPENSSL_KEYTYPE_EC;
$config['curve_name'] = 'prime256v1';
} elseif ($keyType === 'dsa') {
$config['private_key_type'] = OPENSSL_KEYTYPE_DSA;
$config['private_key_bits'] = 1024;
}
$key = \openssl_pkey_new($config);
if (!$key instanceof OpenSSLAsymmetricKey) {
$this->markTestSkipped($keyType . ' key generation is not available');
}
$csr = \openssl_csr_new(['commonName' => 'tc-lib-pdf-sign signer'], $key, $config);
if (!$csr instanceof \OpenSSLCertificateSigningRequest) {
$this->markTestSkipped('CSR generation failed for ' . $keyType);
}
$cert = \openssl_csr_sign($csr, null, $key, 365, $config);
if (!$cert instanceof \OpenSSLCertificate) {
$this->markTestSkipped('Certificate signing failed for ' . $keyType);
}
$certPem = '';
\openssl_x509_export($cert, $certPem);
return ['key' => $key, 'cert_pem' => $certPem, 'cert_der' => $this->pemToDer($certPem)];
}
private function pemToDer(string $pem): string
{
$stripped = (string) \preg_replace('/-----[^-]+-----|\s+/', '', $pem);
$der = \base64_decode($stripped, true);
if ($der === false) {
$this->fail('Invalid PEM');
}
return $der;
}
/**
* Verify the SignerInfo signature over the reconstructed DER SET OF signed attributes.
*
* @param array{signed_attrs: array{tag:int,value:string,raw:string}, signature: array{tag:int,value:string,raw:string}, certificates: array{tag:int,value:string,raw:string}, unsigned_attrs: array{tag:int,value:string,raw:string}|null} $parts
*/
private function assertVerifies(array $parts, string $certPem, int $opensslAlgo): void
{
$publicKey = \openssl_pkey_get_public($certPem);
if ($publicKey === false) {
$this->fail('Unable to load public key');
}
$signedAttrsSet = $this->asn1->encodeSet($parts['signed_attrs']['value']);
$result = \openssl_verify($signedAttrsSet, $parts['signature']['value'], $publicKey, $opensslAlgo);
$this->assertSame(1, $result);
}
/**
* Descend into a SigningCertificate attribute and return the ESSCertID certHash TLV.
*
* @return array{tag: int, value: string, raw: string}
*/
private function firstCertHash(string $oid, string $attrsDer): array
{
$value = $this->attributeValue($attrsDer, $oid);
$this->assertNotNull($value);
$certsOffset = 0;
$certs = $this->asn1->readTlv($value['value'], $certsOffset);
$essOffset = 0;
$ess = $this->asn1->readTlv($certs['value'], $essOffset);
$hashOffset = 0;
return $this->asn1->readTlv($ess['value'], $hashOffset);
}
/**
* Find an Attribute by OID and return the first value TLV of its value SET.
*
* @return array{tag: int, value: string, raw: string}|null
*/
private function attributeValue(string $attrsDer, string $oid): ?array
{
$oidDer = $this->asn1->encodeObjectIdentifier($oid);
$offset = 0;
$length = \strlen($attrsDer);
while ($offset < $length) {
$attribute = $this->asn1->readTlv($attrsDer, $offset);
$inner = 0;
$attrOid = $this->asn1->readTlv($attribute['value'], $inner);
if ($attrOid['raw'] === $oidDer) {
$set = $this->asn1->readTlv($attribute['value'], $inner);
$valueOffset = 0;
return $this->asn1->readTlv($set['value'], $valueOffset);
}
}
return null;
}
/**
* Navigate a CMS ContentInfo to the SignerInfo fields under test.
*
* @return array{signed_attrs: array{tag:int,value:string,raw:string}, signature: array{tag:int,value:string,raw:string}, certificates: array{tag:int,value:string,raw:string}, unsigned_attrs: array{tag:int,value:string,raw:string}|null}
*/
private function parseSignerInfo(string $cms): array
{
$offset = 0;
$contentInfo = $this->asn1->readTlv($cms, $offset);
$ciOffset = 0;
$this->asn1->readTlv($contentInfo['value'], $ciOffset); // contentType OID
$explicit = $this->asn1->readTlv($contentInfo['value'], $ciOffset); // [0] EXPLICIT
$sdOffset = 0;
$signedData = $this->asn1->readTlv($explicit['value'], $sdOffset);
$sdInner = 0;
$this->asn1->readTlv($signedData['value'], $sdInner); // version
$this->asn1->readTlv($signedData['value'], $sdInner); // digestAlgorithms
$this->asn1->readTlv($signedData['value'], $sdInner); // encapContentInfo
$certificates = $this->asn1->readTlv($signedData['value'], $sdInner); // certificates [0]
$signerInfos = $this->asn1->readTlv($signedData['value'], $sdInner); // signerInfos SET
$siOffset = 0;
$signerInfo = $this->asn1->readTlv($signerInfos['value'], $siOffset);
$siInner = 0;
$this->asn1->readTlv($signerInfo['value'], $siInner); // version
$this->asn1->readTlv($signerInfo['value'], $siInner); // sid
$this->asn1->readTlv($signerInfo['value'], $siInner); // digestAlgorithm
$signedAttrs = $this->asn1->readTlv($signerInfo['value'], $siInner); // [0] IMPLICIT
$this->asn1->readTlv($signerInfo['value'], $siInner); // signatureAlgorithm
$signature = $this->asn1->readTlv($signerInfo['value'], $siInner); // signature
$unsignedAttrs = null;
if ($siInner < \strlen($signerInfo['value'])) {
$unsignedAttrs = $this->asn1->readTlv($signerInfo['value'], $siInner); // [1] IMPLICIT
}
return [
'signed_attrs' => $signedAttrs,
'signature' => $signature,
'certificates' => $certificates,
'unsigned_attrs' => $unsignedAttrs,
];
}
}
+113
View File
@@ -0,0 +1,113 @@
<?php
declare(strict_types=1);
/**
* ConfigTest.php
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
namespace Test;
use Com\Tecnick\Pdf\Sign\Config;
use Com\Tecnick\Pdf\Sign\Exception;
use PHPUnit\Framework\TestCase;
/**
* Config Test
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*/
class ConfigTest extends TestCase
{
public function testDefaultsAreLegacy(): void
{
$cfg = new Config();
$this->assertSame(Config::PROFILE_LEGACY, $cfg->profile);
$this->assertSame('sha256', $cfg->digestAlgorithm);
$this->assertSame(2, $cfg->certType);
$this->assertFalse($cfg->isPades());
$this->assertSame('adbe.pkcs7.detached', $cfg->subFilter());
}
public function testPadesProfile(): void
{
$cfg = new Config(Config::PROFILE_PADES_B_T, 'sha384', 1);
$this->assertTrue($cfg->isPades());
$this->assertSame('ETSI.CAdES.detached', $cfg->subFilter());
$this->assertSame('sha384', $cfg->digestAlgorithm);
$this->assertSame(1, $cfg->certType);
}
public function testInvalidProfileThrows(): void
{
$this->expectException(Exception::class);
new Config('bogus');
}
public function testInvalidDigestThrows(): void
{
$this->expectException(Exception::class);
new Config(Config::PROFILE_PADES_B_B, 'md5');
}
public function testInvalidCertTypeThrows(): void
{
$this->expectException(Exception::class);
new Config(Config::PROFILE_LEGACY, 'sha256', 4);
}
public function testFromArrayDefaults(): void
{
$cfg = Config::fromArray([]);
$this->assertSame(Config::PROFILE_LEGACY, $cfg->profile);
$this->assertSame('sha256', $cfg->digestAlgorithm);
$this->assertSame(2, $cfg->certType);
}
public function testFromArrayValues(): void
{
$cfg = Config::fromArray([
'profile' => Config::PROFILE_PADES_B_LTA,
'digest_algorithm' => 'sha512',
'cert_type' => 3,
]);
$this->assertSame(Config::PROFILE_PADES_B_LTA, $cfg->profile);
$this->assertSame('sha512', $cfg->digestAlgorithm);
$this->assertSame(3, $cfg->certType);
$this->assertTrue($cfg->isPades());
}
public function testFromArrayInvalidTypeThrows(): void
{
$this->expectException(Exception::class);
Config::fromArray(['cert_type' => '2']);
}
public function testFromArrayRejectsNonStringProfile(): void
{
$this->expectException(Exception::class);
Config::fromArray(['profile' => 123]);
}
public function testFromArrayRejectsNonStringDigest(): void
{
$this->expectException(Exception::class);
Config::fromArray(['digest_algorithm' => 123]);
}
}
@@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
/**
* DigestAlgorithmTest.php
*
* @since 2026-07-17
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
namespace Test;
use Com\Tecnick\Pdf\Sign\Config;
use Com\Tecnick\Pdf\Sign\DigestAlgorithm;
use Com\Tecnick\Pdf\Sign\Exception;
use Com\Tecnick\Pdf\Sign\Timestamp\Config as TimestampConfig;
use PHPUnit\Framework\TestCase;
/**
* DigestAlgorithm enum test
*
* @since 2026-07-17
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*/
class DigestAlgorithmTest extends TestCase
{
public function testCaseBackingValues(): void
{
$this->assertSame('sha256', DigestAlgorithm::Sha256->value);
$this->assertSame('sha384', DigestAlgorithm::Sha384->value);
$this->assertSame('sha512', DigestAlgorithm::Sha512->value);
}
public function testCasesMatchBothConfigSets(): void
{
$values = \array_map(static fn(DigestAlgorithm $case): string => $case->value, DigestAlgorithm::cases());
$this->assertSame(Config::DIGEST_ALGORITHMS, $values);
$this->assertSame(TimestampConfig::HASH_ALGORITHMS, $values);
}
public function testFromLooseCanonical(): void
{
$this->assertSame(DigestAlgorithm::Sha256, DigestAlgorithm::fromLoose('sha256'));
$this->assertSame(DigestAlgorithm::Sha512, DigestAlgorithm::fromLoose('sha512'));
}
public function testFromLoosePassesThroughEnumInstance(): void
{
$this->assertSame(DigestAlgorithm::Sha384, DigestAlgorithm::fromLoose(DigestAlgorithm::Sha384));
}
public function testFromLooseRoundTrip(): void
{
foreach (DigestAlgorithm::cases() as $case) {
$this->assertSame($case, DigestAlgorithm::fromLoose($case->value));
}
}
public function testFromLooseUnknownThrows(): void
{
$this->expectException(Exception::class);
DigestAlgorithm::fromLoose('md5');
}
public function testConfigAcceptsEnum(): void
{
$cfg = new Config(Config::PROFILE_LEGACY, DigestAlgorithm::Sha384);
$this->assertSame('sha384', $cfg->digestAlgorithm);
}
public function testTimestampConfigAcceptsEnum(): void
{
$cfg = new TimestampConfig(host: 'https://tsa.example.org', hashAlgorithm: DigestAlgorithm::Sha512);
$this->assertSame('sha512', $cfg->hashAlgorithm);
}
}
@@ -0,0 +1,193 @@
<?php
declare(strict_types=1);
/**
* ValidationMaterialTest.php
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
namespace Test\Ltv;
use Com\Tecnick\Pdf\Sign\Exception;
use Com\Tecnick\Pdf\Sign\Ltv\ValidationMaterial;
use PHPUnit\Framework\TestCase;
/**
* ValidationMaterial Test
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*/
class ValidationMaterialTest extends TestCase
{
private ValidationMaterial $material;
private string $ltvPem = '';
private string $caPem = '';
private string $leafDer = '';
private string $caDer = '';
protected function setUp(): void
{
$this->material = new ValidationMaterial();
$this->ltvPem = (string) \file_get_contents(__DIR__ . '/../data/ltv_cert.pem');
$this->caPem = (string) \file_get_contents(__DIR__ . '/../data/ocsp_ca.pem');
$leafPem = (string) \file_get_contents(__DIR__ . '/../data/ocsp_leaf.pem');
$this->leafDer = $this->pemToDer($leafPem);
$this->caDer = $this->pemToDer($this->caPem);
}
private function pemToDer(string $pem): string
{
$stripped = (string) \preg_replace('/-----[^-]+-----|\s+/', '', $pem);
$der = \base64_decode($stripped, true);
if ($der === false) {
$this->fail('Invalid PEM fixture');
}
return $der;
}
public function testCertificateOcspUrlsExtractsOnlyOcsp(): void
{
$urls = $this->material->certificateOcspUrls($this->ltvPem);
$this->assertSame(['http://ocsp.example.org/r'], $urls);
}
public function testCertificateCrlUrlsExtractsAll(): void
{
$urls = $this->material->certificateCrlUrls($this->ltvPem);
$this->assertSame(['http://crl.example.org/root.crl', 'http://crl2.example.org/root.crl'], $urls);
}
public function testUrlsEmptyWhenExtensionAbsent(): void
{
// The OCSP CA fixture carries no AIA or CRL distribution point extensions.
$this->assertSame([], $this->material->certificateOcspUrls($this->caPem));
$this->assertSame([], $this->material->certificateCrlUrls($this->caPem));
}
public function testCertificateUrlsEmptyForUnparseableCertificate(): void
{
// LTV collection is best-effort: a certificate that cannot be parsed yields no
// OCSP/CRL URLs rather than aborting the whole signing operation. The certificate
// is still embeddable because its DER bytes are obtained separately.
\set_error_handler(static fn(): bool => true);
try {
$this->assertSame([], $this->material->certificateOcspUrls('not-a-certificate'));
$this->assertSame([], $this->material->certificateCrlUrls('not-a-certificate'));
} finally {
\restore_error_handler();
}
}
public function testCertificatesDeduplicates(): void
{
$leafPem = (string) \file_get_contents(__DIR__ . '/../data/ocsp_leaf.pem');
$ders = $this->material->certificates([$leafPem, $leafPem, $this->caPem]);
$this->assertCount(2, $ders);
$this->assertSame([$this->leafDer, $this->caDer], $ders);
}
public function testCertificatesRejectsInvalidPem(): void
{
$this->expectException(Exception::class);
$this->material->certificates(["-----BEGIN CERTIFICATE-----\n@@@@\n-----END CERTIFICATE-----"]);
}
public function testFetchOcspBuildsRequestAndDeduplicates(): void
{
$captured = [];
$transport = static function (string $url, string $request) use (&$captured): string {
$captured[] = ['url' => $url, 'request' => $request];
return 'OCSP-RESPONSE';
};
$responses = $this->material->fetchOcsp(
$this->caDer,
$this->leafDer,
['http://ocsp.a.example', 'http://ocsp.b.example'],
$transport,
);
// Two URLs, identical responses collapse to one.
$this->assertSame(['OCSP-RESPONSE'], $responses);
$this->assertCount(2, $captured);
// The transport received a DER OCSP request (SEQUENCE).
$firstCapture = $captured[0] ?? null;
if (!\is_array($firstCapture)) {
$this->fail('Expected a captured OCSP request');
}
$this->assertSame("\x30", $firstCapture['request'][0]);
}
public function testFetchOcspSkipsFailingUrl(): void
{
$transport = static function (string $url): string {
if (\str_contains($url, 'bad')) {
throw new \RuntimeException('boom');
}
return 'RESP-' . $url;
};
$responses = $this->material->fetchOcsp(
$this->caDer,
$this->leafDer,
['http://bad.example', 'http://good.example'],
$transport,
);
$this->assertSame(['RESP-http://good.example'], $responses);
}
public function testFetchOcspReturnsEmptyWhenNoUrls(): void
{
$calls = 0;
$transport = static function () use (&$calls): string {
++$calls;
return 'X';
};
$this->assertSame([], $this->material->fetchOcsp($this->caDer, $this->leafDer, [], $transport));
$this->assertSame(0, $calls);
}
public function testFetchCrlDeduplicatesAndSkipsEmpty(): void
{
$transport = static function (string $url): string {
if (\str_contains($url, 'empty')) {
return '';
}
return 'CRL-DATA';
};
$responses = $this->material->fetchCrl(
['http://empty.example', 'http://a.example', 'http://b.example'],
$transport,
);
// Empty response skipped; the two identical CRLs collapse to one.
$this->assertSame(['CRL-DATA'], $responses);
}
}
@@ -0,0 +1,174 @@
<?php
declare(strict_types=1);
/**
* ClientTest.php
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
namespace Test\Ocsp;
use Com\Tecnick\Pdf\Sign\Cms\Asn1;
use Com\Tecnick\Pdf\Sign\Exception;
use Com\Tecnick\Pdf\Sign\Ocsp\Client;
use PHPUnit\Framework\TestCase;
/**
* OCSP Client Test
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*/
class ClientTest extends TestCase
{
private Asn1 $asn1;
private string $leafPem = '';
private string $leafDer = '';
private string $caDer = '';
protected function setUp(): void
{
$this->asn1 = new Asn1();
$this->leafPem = (string) \file_get_contents(__DIR__ . '/../data/ocsp_leaf.pem');
$this->leafDer = $this->pemToDer($this->leafPem);
$this->caDer = $this->pemToDer((string) \file_get_contents(__DIR__ . '/../data/ocsp_ca.pem'));
}
private function pemToDer(string $pem): string
{
$stripped = (string) \preg_replace('/-----[^-]+-----|\s+/', '', $pem);
$der = \base64_decode($stripped, true);
if ($der === false) {
$this->fail('Invalid PEM fixture');
}
return $der;
}
public function testExtractSubjectReturnsSubjectNotIssuer(): void
{
// The leaf subject (CN=...leaf) differs from its issuer (CN=...root CA),
// so this proves the subject field is read, not the issuer field.
$client = new Client($this->asn1);
$info = $client->extractSubjectAndPublicKey($this->leafDer);
$this->assertStringContainsString('tc-lib-pdf-sign leaf', $info['subject']);
$this->assertStringNotContainsString('root CA', $info['subject']);
$this->assertNotSame('', $info['public_key']);
}
public function testExtractSerialNumberMatchesOpenssl(): void
{
$parsed = \openssl_x509_parse($this->leafPem);
if (!\is_array($parsed)) {
$this->fail('Unable to parse leaf certificate');
}
$expectedHex = \strtolower($parsed['serialNumberHex']);
$client = new Client($this->asn1);
$serial = $client->extractSerialNumber($this->leafDer);
$this->assertSame($expectedHex, \bin2hex($serial));
}
public function testBuildProducesValidOcspRequest(): void
{
$client = new Client($this->asn1);
$req = $client->build($this->caDer, $this->leafDer);
// OCSPRequest ::= SEQ { tbsRequest SEQ { requestList SEQ OF { Request SEQ { CertID SEQ } } } }
$offset = 0;
$ocspRequest = $this->asn1->readTlv($req, $offset);
$this->assertSame(0x30, $ocspRequest['tag']);
$this->assertSame(\strlen($req), $offset);
$certId = $this->descend($ocspRequest['value'], 4); // tbsRequest, requestList, Request, CertID
$this->assertSame(0x30, $certId['tag']);
$inner = 0;
$algId = $this->asn1->readTlv($certId['value'], $inner);
$nameHash = $this->asn1->readTlv($certId['value'], $inner);
$keyHash = $this->asn1->readTlv($certId['value'], $inner);
$serial = $this->asn1->readTlv($certId['value'], $inner);
// SHA-1 CertID hashes are computed over the issuer certificate's subject and key.
$issuer = $client->extractSubjectAndPublicKey($this->caDer);
$this->assertSame(0x04, $nameHash['tag']);
$this->assertSame(\hash('sha1', $issuer['subject'], true), $nameHash['value']);
$this->assertSame(20, \strlen($nameHash['value']));
$this->assertSame(0x04, $keyHash['tag']);
$this->assertSame(\hash('sha1', $issuer['public_key'], true), $keyHash['value']);
$this->assertSame(20, \strlen($keyHash['value']));
// hashAlgorithm OID is SHA-1 (1.3.14.3.2.26).
$algOffset = 0;
$oid = $this->asn1->readTlv($algId['value'], $algOffset);
$this->assertSame($this->asn1->encodeObjectIdentifier('1.3.14.3.2.26'), $oid['raw']);
// serialNumber matches the leaf certificate.
$this->assertSame(0x02, $serial['tag']);
$this->assertSame($client->extractSerialNumber($this->leafDer), $serial['value']);
}
public function testFetchUsesTransport(): void
{
$captured = ['url' => '', 'request' => ''];
$transport = static function (string $url, string $request) use (&$captured): string {
$captured['url'] = $url;
$captured['request'] = $request;
return 'OCSP-RESPONSE-BYTES';
};
$client = new Client($this->asn1);
$result = $client->fetch('http://ocsp.example.org', $this->caDer, $this->leafDer, $transport);
$this->assertSame('OCSP-RESPONSE-BYTES', $result);
$this->assertSame('http://ocsp.example.org', $captured['url']);
$offset = 0;
$root = $this->asn1->readTlv($captured['request'], $offset);
$this->assertSame(0x30, $root['tag']);
}
public function testFetchRejectsNonStringTransportResult(): void
{
$transport = static fn(string $url, string $request): int => \strlen($url . $request);
$this->expectException(Exception::class);
$client = new Client($this->asn1);
$client->fetch('http://x', $this->caDer, $this->leafDer, $transport);
}
/**
* Read the first TLV, then descend into the first child $depth times.
*
* @param int<0, max> $depth
*
* @return array{tag: int, value: string, raw: string}
*/
private function descend(string $data, int $depth): array
{
$tlv = ['tag' => 0, 'value' => $data, 'raw' => $data];
for ($i = 0; $i < $depth; ++$i) {
$offset = 0;
$tlv = $this->asn1->readTlv($tlv['value'], $offset);
}
return $tlv;
}
}
@@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
/**
* DocTimeStampTest.php
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
namespace Test\Output;
use Com\Tecnick\Pdf\Sign\Output\DocTimeStamp;
use Com\Tecnick\Pdf\Sign\Output\Signature;
use PHPUnit\Framework\TestCase;
/**
* DocTimeStamp Output Test
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*/
class DocTimeStampTest extends TestCase
{
private DocTimeStamp $docTimeStamp;
protected function setUp(): void
{
$this->docTimeStamp = new DocTimeStamp();
}
public function testValueObjectStructure(): void
{
$out = $this->docTimeStamp->valueObject(7);
$this->assertStringStartsWith("7 0 obj\n", $out);
$this->assertStringEndsWith(" >>\nendobj\n", $out);
$this->assertStringContainsString('/Type /DocTimeStamp /Filter /Adobe.PPKLite /SubFilter /ETSI.RFC3161', $out);
$this->assertStringContainsString(Signature::BYTE_RANGE_PLACEHOLDER, $out);
$this->assertStringContainsString(
'/Contents<' . \str_repeat('0', Signature::DEFAULT_CONTENTS_LENGTH) . '>',
$out,
);
// A document timestamp is not a signature: no /Sig, /Reference, /M, or /V.
$this->assertStringNotContainsString('/Type /Sig', $out);
$this->assertStringNotContainsString('/Reference', $out);
$this->assertStringNotContainsString('/M ', $out);
$this->assertStringNotContainsString('/V ', $out);
}
public function testCustomContentsLength(): void
{
$out = $this->docTimeStamp->valueObject(2, 64);
$this->assertStringContainsString('/Contents<' . \str_repeat('0', 64) . '>', $out);
$this->assertStringNotContainsString(\str_repeat('0', 65), $out);
}
}
@@ -0,0 +1,122 @@
<?php
declare(strict_types=1);
/**
* DssTest.php
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
namespace Test\Output;
use Com\Tecnick\Pdf\Sign\Exception;
use Com\Tecnick\Pdf\Sign\Output\Dss;
use PHPUnit\Framework\TestCase;
/**
* DSS Output Test
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*/
class DssTest extends TestCase
{
private Dss $dss;
protected function setUp(): void
{
$this->dss = new Dss();
}
public function testEmitReturnsNothingForEmptyMaterial(): void
{
$pon = 7;
$result = $this->dss->emit(['certs' => [], 'ocsp' => [], 'crls' => []], 'SIG', $pon);
$this->assertSame([], $result['objects']);
$this->assertSame(0, $result['object_id']);
$this->assertSame(7, $pon);
}
public function testEmitProducesStreamsVriAndDss(): void
{
$pon = 10;
$contents = 'CMS-SIGNATURE-BYTES';
$result = $this->dss->emit(
['certs' => ['CERT-DER'], 'ocsp' => ['OCSP-RESP'], 'crls' => ['CRL-DATA']],
$contents,
$pon,
);
// 3 streams (11,12,13), VRI (14), DSS (15).
$this->assertSame(15, $pon);
$this->assertSame(15, $result['object_id']);
// The whole map is keyed by object number, ready for an incremental xref.
$vriKey = \strtoupper(\sha1($contents));
$this->assertSame(
[
11 => "11 0 obj\n<< /Length 8 >>\nstream\nCERT-DER\nendstream\nendobj\n",
12 => "12 0 obj\n<< /Length 9 >>\nstream\nOCSP-RESP\nendstream\nendobj\n",
13 => "13 0 obj\n<< /Length 8 >>\nstream\nCRL-DATA\nendstream\nendobj\n",
14 => "14 0 obj\n<< /Type /VRI /Cert [ 11 0 R ] /OCSP [ 12 0 R ] /CRL [ 13 0 R ] >>\nendobj\n",
15 =>
"15 0 obj\n<< /Type /DSS /VRI << /"
. $vriKey
. ' 14 0 R >>'
. ' /Certs [ 11 0 R ] /OCSPs [ 12 0 R ] /CRLs [ 13 0 R ]'
. " >>\nendobj\n",
],
$result['objects'],
);
}
public function testEmitOmitsEmptyCategories(): void
{
$pon = 0;
$result = $this->dss->emit(['certs' => ['A', 'B'], 'ocsp' => [], 'crls' => []], 'SIG', $pon);
// 2 cert streams (1,2), VRI (3), DSS (4).
$this->assertSame(4, $result['object_id']);
$objects = \implode('', $result['objects']);
$this->assertStringContainsString('<< /Type /VRI /Cert [ 1 0 R 2 0 R ] >>', $objects);
$this->assertStringNotContainsString('/OCSP ', $objects);
$this->assertStringNotContainsString('/CRL ', $objects);
$this->assertStringContainsString('/Certs [ 1 0 R 2 0 R ]', $objects);
$this->assertStringNotContainsString('/OCSPs', $objects);
$this->assertStringNotContainsString('/CRLs', $objects);
}
public function testEmitEncryptsStreams(): void
{
$pon = 0;
$encryptor = static fn(string $data, int $objectId): string => 'E' . $objectId . ':' . $data;
$result = $this->dss->emit(['certs' => ['X'], 'ocsp' => [], 'crls' => []], 'SIG', $pon, $encryptor);
// Stream 1 carries the encrypted payload "E1:X" (length 4).
$objects = \implode('', $result['objects']);
$this->assertStringContainsString("1 0 obj\n<< /Length 4 >>\nstream\nE1:X\nendstream\nendobj\n", $objects);
}
public function testEmitRejectsNonStringEncryptorResult(): void
{
$pon = 0;
$encryptor = static fn(string $_data, int $objectId): int => $objectId;
$this->expectException(Exception::class);
$this->dss->emit(['certs' => ['X'], 'ocsp' => [], 'crls' => []], 'SIG', $pon, $encryptor);
}
}
@@ -0,0 +1,128 @@
<?php
declare(strict_types=1);
/**
* SignatureTest.php
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
namespace Test\Output;
use Com\Tecnick\Pdf\Sign\Exception;
use Com\Tecnick\Pdf\Sign\Output\Signature;
use PHPUnit\Framework\TestCase;
/**
* Signature Output Test
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*/
class SignatureTest extends TestCase
{
private Signature $signature;
protected function setUp(): void
{
$this->signature = new Signature();
}
private const DOCMDP_REFERENCE =
' /Reference [ << /Type /SigRef /TransformMethod /DocMDP'
. ' /TransformParams << /Type /TransformParams /P 2 /V /1.2 >> >> ]';
private const DATE_VALUE = "(D:20231114221320+00'00')";
public function testValueObjectWithReferenceAndInfo(): void
{
$out = $this->signature->valueObject(
12,
'ETSI.CAdES.detached',
self::DOCMDP_REFERENCE,
['Name' => 'Jane Doe', 'Location' => 'Rome', 'Reason' => 'Approval', 'ContactInfo' => 'jane@example.org'],
self::DATE_VALUE,
);
$this->assertStringStartsWith("12 0 obj\n", $out);
$this->assertStringEndsWith(" >>\nendobj\n", $out);
$this->assertStringContainsString('/Type /Sig /Filter /Adobe.PPKLite /SubFilter /ETSI.CAdES.detached', $out);
$this->assertStringContainsString(Signature::BYTE_RANGE_PLACEHOLDER, $out);
$this->assertStringContainsString(
'/Contents<' . \str_repeat('0', Signature::DEFAULT_CONTENTS_LENGTH) . '>',
$out,
);
$this->assertStringContainsString(self::DOCMDP_REFERENCE, $out);
$this->assertStringContainsString('/Name (Jane Doe)', $out);
$this->assertStringContainsString('/Location (Rome)', $out);
$this->assertStringContainsString('/Reason (Approval)', $out);
$this->assertStringContainsString('/ContactInfo (jane@example.org)', $out);
// The /M date token is appended verbatim (already encoded by the caller).
$this->assertStringContainsString(' /M ' . self::DATE_VALUE . ' >>', $out);
}
public function testEmptyReferenceIsOmitted(): void
{
$out = $this->signature->valueObject(3, 'ETSI.CAdES.detached', '', [], self::DATE_VALUE);
$this->assertStringNotContainsString('/Reference', $out);
$this->assertStringNotContainsString('/Name', $out);
$this->assertStringContainsString('/SubFilter /ETSI.CAdES.detached', $out);
}
public function testCustomContentsLength(): void
{
$out = $this->signature->valueObject(1, 'adbe.pkcs7.detached', '', [], self::DATE_VALUE, 128);
$this->assertStringContainsString('/Contents<' . \str_repeat('0', 128) . '>', $out);
$this->assertStringNotContainsString(\str_repeat('0', 129), $out);
}
public function testDefaultEncoderEscapesLiteralStrings(): void
{
$out = $this->signature->valueObject(1, 'adbe.pkcs7.detached', '', ['Name' => 'A (B) \\ C'], self::DATE_VALUE);
$this->assertStringContainsString('/Name (A \\(B\\) \\\\ C)', $out);
}
public function testUsesInjectedStringEncoder(): void
{
$encoder = static fn(string $text, int $_objectId): string => '<' . \bin2hex($text) . '>';
$out = $this->signature->valueObject(
5,
'ETSI.CAdES.detached',
'',
['Reason' => 'Hi'],
self::DATE_VALUE,
Signature::DEFAULT_CONTENTS_LENGTH,
$encoder,
);
$this->assertStringContainsString('/Reason <' . \bin2hex('Hi') . '>', $out);
}
public function testRejectsNonStringEncoderResult(): void
{
$encoder = static fn(string $_text, int $objectId): int => $objectId;
$this->expectException(Exception::class);
$this->signature->valueObject(
5,
'ETSI.CAdES.detached',
'',
['Reason' => 'Hi'],
self::DATE_VALUE,
Signature::DEFAULT_CONTENTS_LENGTH,
$encoder,
);
}
}
@@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
/**
* WidgetTest.php
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
namespace Test\Output;
use Com\Tecnick\Pdf\Sign\Exception;
use Com\Tecnick\Pdf\Sign\Output\Widget;
use PHPUnit\Framework\TestCase;
/**
* Widget Output Test
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*/
class WidgetTest extends TestCase
{
private Widget $widget;
protected function setUp(): void
{
$this->widget = new Widget();
}
public function testSignedFieldWidget(): void
{
$out = $this->widget->annotation(8, '10.0 20.0 110.0 60.0', 5, 'Signature', 9, ' /AS /N /AP << /N 20 0 R >>');
$this->assertStringStartsWith("8 0 obj\n", $out);
$this->assertStringEndsWith(" >>\nendobj\n", $out);
$this->assertStringContainsString('/Type /Annot /Subtype /Widget', $out);
$this->assertStringContainsString('/Rect [10.0 20.0 110.0 60.0]', $out);
$this->assertStringContainsString('/P 5 0 R', $out);
$this->assertStringContainsString('/F 4 /FT /Sig', $out);
$this->assertStringContainsString('/T (Signature)', $out);
$this->assertStringContainsString('/Ff 0', $out);
$this->assertStringContainsString('/AS /N /AP << /N 20 0 R >>', $out);
$this->assertStringContainsString('/V 9 0 R', $out);
}
public function testEmptyFieldWidgetHasNoValueOrAppearance(): void
{
$out = $this->widget->annotation(4, '0 0 100 40', 5, 'Reviewer [002]');
$this->assertStringContainsString('/T (Reviewer [002])', $out);
$this->assertStringNotContainsString('/V ', $out);
$this->assertStringNotContainsString('/AP', $out);
}
public function testUsesInjectedStringEncoder(): void
{
$encoder = static fn(string $text, int $_objectId): string => '<' . \bin2hex($text) . '>';
$out = $this->widget->annotation(4, '0 0 1 1', 5, 'Sig', null, '', $encoder);
$this->assertStringContainsString('/T <' . \bin2hex('Sig') . '>', $out);
}
public function testRejectsNonStringEncoderResult(): void
{
$encoder = static fn(string $_text, int $objectId): int => $objectId;
$this->expectException(Exception::class);
$this->widget->annotation(4, '0 0 1 1', 5, 'Sig', null, '', $encoder);
}
}
@@ -0,0 +1,84 @@
<?php
declare(strict_types=1);
/**
* SignatureProfileTest.php
*
* @since 2026-07-17
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
namespace Test;
use Com\Tecnick\Pdf\Sign\Config;
use Com\Tecnick\Pdf\Sign\Exception;
use Com\Tecnick\Pdf\Sign\SignatureProfile;
use PHPUnit\Framework\TestCase;
/**
* SignatureProfile enum test
*
* @since 2026-07-17
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*/
class SignatureProfileTest extends TestCase
{
public function testCaseBackingValuesMatchConfigConstants(): void
{
$this->assertSame(Config::PROFILE_LEGACY, SignatureProfile::Legacy->value);
$this->assertSame(Config::PROFILE_PADES_B_B, SignatureProfile::PadesBB->value);
$this->assertSame(Config::PROFILE_PADES_B_T, SignatureProfile::PadesBT->value);
$this->assertSame(Config::PROFILE_PADES_B_LT, SignatureProfile::PadesBLT->value);
$this->assertSame(Config::PROFILE_PADES_B_LTA, SignatureProfile::PadesBLTA->value);
}
public function testFromLooseCanonical(): void
{
$this->assertSame(SignatureProfile::Legacy, SignatureProfile::fromLoose('legacy'));
$this->assertSame(SignatureProfile::PadesBLTA, SignatureProfile::fromLoose('pades-b-lta'));
}
public function testFromLoosePassesThroughEnumInstance(): void
{
$this->assertSame(SignatureProfile::PadesBT, SignatureProfile::fromLoose(SignatureProfile::PadesBT));
}
public function testFromLooseRoundTrip(): void
{
foreach (SignatureProfile::cases() as $case) {
$this->assertSame($case, SignatureProfile::fromLoose($case->value));
}
}
public function testFromLooseUnknownThrows(): void
{
$this->expectException(Exception::class);
SignatureProfile::fromLoose('bogus');
}
public function testConfigAcceptsEnum(): void
{
$cfg = new Config(SignatureProfile::PadesBLTA);
$this->assertSame(Config::PROFILE_PADES_B_LTA, $cfg->profile);
$this->assertTrue($cfg->isPades());
}
public function testFromArrayAcceptsEnum(): void
{
$cfg = Config::fromArray(['profile' => SignatureProfile::PadesBB]);
$this->assertSame(Config::PROFILE_PADES_B_B, $cfg->profile);
}
}
+291
View File
@@ -0,0 +1,291 @@
<?php
declare(strict_types=1);
/**
* SignerTest.php
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
namespace Test;
use Com\Tecnick\Pdf\Sign\Cms\Asn1;
use Com\Tecnick\Pdf\Sign\Config;
use Com\Tecnick\Pdf\Sign\Exception;
use Com\Tecnick\Pdf\Sign\Signer;
use Com\Tecnick\Pdf\Sign\Timestamp\Client as TimestampClient;
use Com\Tecnick\Pdf\Sign\Timestamp\Config as TimestampConfig;
use OpenSSLAsymmetricKey;
use PHPUnit\Framework\TestCase;
/**
* Signer Test
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*/
class SignerTest extends TestCase
{
private const SIGNING_TIME = 1_700_000_000;
private const OID_SIGNATURE_TIMESTAMP = '1.2.840.113549.1.9.16.2.14';
private const OID_SIGNING_TIME = '1.2.840.113549.1.9.5';
private Asn1 $asn1;
protected function setUp(): void
{
$this->asn1 = new Asn1();
}
public function testSignLegacyProfileHasNoSignatureTimestamp(): void
{
$cred = $this->makeCredential();
$signer = new Signer();
$cms = $signer->sign(
'document bytes',
$cred['cert_der'],
$cred['key'],
[],
new Config(Config::PROFILE_LEGACY),
self::SIGNING_TIME,
);
$this->assertStringNotContainsString($this->timestampOidDer(), $cms);
// The legacy (ISO 32000-1) profile keeps the CMS signing-time attribute.
$this->assertStringContainsString($this->signingTimeOidDer(), $cms);
}
public function testSignBbProfileHasNoSignatureTimestamp(): void
{
$cred = $this->makeCredential();
$signer = new Signer();
$cms = $signer->sign(
'document bytes',
$cred['cert_der'],
$cred['key'],
[],
new Config(Config::PROFILE_PADES_B_B),
self::SIGNING_TIME,
);
$this->assertStringNotContainsString($this->timestampOidDer(), $cms);
// PAdES-BASELINE forbids the CMS signing-time attribute (ETSI EN 319 142-1);
// the signing time is carried by the /M signature dictionary entry instead.
$this->assertStringNotContainsString($this->signingTimeOidDer(), $cms);
}
public function testSignBtProfileEmbedsSignatureTimestamp(): void
{
$cred = $this->makeCredential();
$token = $this->asn1->encodeSequence($this->asn1->encodeOctetString('rfc3161-token-body'));
$captured = null;
$transport = function (string $request) use (&$captured, $token): string {
$captured = $request;
return $this->timestampResponse($token);
};
$signer = new Signer();
$cms = $signer->sign(
'document bytes',
$cred['cert_der'],
$cred['key'],
[],
new Config(Config::PROFILE_PADES_B_T),
self::SIGNING_TIME,
new TimestampClient(new TimestampConfig('https://tsa.example.org')),
$transport,
);
// The transport received a DER TimeStampReq (SEQUENCE).
$this->assertIsString($captured);
$this->assertSame("\x30", $captured[0]);
// The CMS carries the signature-timestamp attribute and the returned token bytes.
$this->assertStringContainsString($this->timestampOidDer(), $cms);
$this->assertStringContainsString($token, $cms);
}
public function testSignBtProfileRequiresTimestampClient(): void
{
$cred = $this->makeCredential();
$signer = new Signer();
$this->expectException(Exception::class);
$signer->sign(
'document bytes',
$cred['cert_der'],
$cred['key'],
[],
new Config(Config::PROFILE_PADES_B_T),
self::SIGNING_TIME,
);
}
public function testSignBtProfileRequiresTransport(): void
{
$cred = $this->makeCredential();
$signer = new Signer();
$this->expectException(Exception::class);
$signer->sign(
'document bytes',
$cred['cert_der'],
$cred['key'],
[],
new Config(Config::PROFILE_PADES_B_LTA),
self::SIGNING_TIME,
new TimestampClient(new TimestampConfig('https://tsa.example.org')),
null,
);
}
public function testCollectValidationMaterialGathersCertsOcspAndCrls(): void
{
$ltvPem = (string) \file_get_contents(__DIR__ . '/data/ltv_cert.pem');
$caPem = (string) \file_get_contents(__DIR__ . '/data/ocsp_ca.pem');
$ocspCalls = [];
$ocspTransport = static function (string $url, string $request) use (&$ocspCalls): string {
$ocspCalls[] = ['url' => $url, 'request' => $request];
return 'OCSP-RESPONSE';
};
$crlTransport = static fn(string $url): string => 'CRL-' . $url;
$signer = new Signer();
$material = $signer->collectValidationMaterial([$ltvPem, $caPem], $ocspTransport, $crlTransport);
// Both certificates are collected as DER.
$this->assertCount(2, $material['certs']);
// The leaf's single OCSP responder was queried; the CA has none.
$this->assertCount(1, $ocspCalls);
$firstOcspCall = $ocspCalls[0] ?? null;
if (!\is_array($firstOcspCall)) {
$this->fail('Expected a captured OCSP call');
}
$this->assertSame('http://ocsp.example.org/r', $firstOcspCall['url']);
$this->assertSame("\x30", $firstOcspCall['request'][0]);
$this->assertSame(['OCSP-RESPONSE'], $material['ocsp']);
// The leaf carries two distinct CRL distribution points.
$this->assertSame(
['CRL-http://crl.example.org/root.crl', 'CRL-http://crl2.example.org/root.crl'],
$material['crls'],
);
}
public function testCollectValidationMaterialSkipsRevocationWithoutTransports(): void
{
$ltvPem = (string) \file_get_contents(__DIR__ . '/data/ltv_cert.pem');
$caPem = (string) \file_get_contents(__DIR__ . '/data/ocsp_ca.pem');
$signer = new Signer();
$material = $signer->collectValidationMaterial([$ltvPem, $caPem]);
$this->assertCount(2, $material['certs']);
$this->assertSame([], $material['ocsp']);
$this->assertSame([], $material['crls']);
}
public function testCollectValidationMaterialDeduplicatesCertificates(): void
{
$ltvPem = (string) \file_get_contents(__DIR__ . '/data/ltv_cert.pem');
$signer = new Signer();
$material = $signer->collectValidationMaterial([$ltvPem, $ltvPem]);
$this->assertCount(1, $material['certs']);
}
public function testCollectValidationMaterialRejectsInvalidPem(): void
{
$signer = new Signer();
$this->expectException(Exception::class);
$signer->collectValidationMaterial(['-----BEGIN CERTIFICATE-----@@-----END CERTIFICATE-----']);
}
/**
* DER of the id-aa-signatureTimeStampToken OID, used as a presence probe.
*/
private function timestampOidDer(): string
{
return $this->asn1->encodeObjectIdentifier(self::OID_SIGNATURE_TIMESTAMP);
}
/**
* DER of the CMS signing-time OID, used as a presence probe.
*/
private function signingTimeOidDer(): string
{
return $this->asn1->encodeObjectIdentifier(self::OID_SIGNING_TIME);
}
/**
* Build a minimal DER RFC 3161 TimeStampResp wrapping the given token.
*/
private function timestampResponse(string $tstDer): string
{
$status = $this->asn1->encodeSequence($this->asn1->encodeInteger(0));
return $this->asn1->encodeSequence($status . $tstDer);
}
/**
* Generate an RSA private key and a matching self-signed certificate.
*
* @return array{key: OpenSSLAsymmetricKey, cert_pem: string, cert_der: string}
*/
private function makeCredential(): array
{
$config = [
'config' => __DIR__ . '/../openssl.cnf',
'digest_alg' => 'sha256',
'private_key_bits' => 2048,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
];
$key = \openssl_pkey_new($config);
if (!$key instanceof OpenSSLAsymmetricKey) {
$this->markTestSkipped('RSA key generation is not available');
}
$csr = \openssl_csr_new(['commonName' => 'tc-lib-pdf-sign signer'], $key, $config);
if (!$csr instanceof \OpenSSLCertificateSigningRequest) {
$this->markTestSkipped('CSR generation failed');
}
$cert = \openssl_csr_sign($csr, null, $key, 365, $config);
if (!$cert instanceof \OpenSSLCertificate) {
$this->markTestSkipped('Certificate signing failed');
}
$certPem = '';
\openssl_x509_export($cert, $certPem);
$stripped = (string) \preg_replace('/-----[^-]+-----|\s+/', '', $certPem);
$der = \base64_decode($stripped, true);
if ($der === false) {
$this->fail('Invalid PEM');
}
return ['key' => $key, 'cert_pem' => $certPem, 'cert_der' => $der];
}
}
@@ -0,0 +1,236 @@
<?php
declare(strict_types=1);
/**
* ClientTest.php
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
namespace Test\Timestamp;
use Com\Tecnick\Pdf\Sign\Cms\Asn1;
use Com\Tecnick\Pdf\Sign\Exception;
use Com\Tecnick\Pdf\Sign\Timestamp\Client;
use Com\Tecnick\Pdf\Sign\Timestamp\Config;
use PHPUnit\Framework\TestCase;
/**
* Timestamp Client Test
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*/
class ClientTest extends TestCase
{
private Asn1 $asn1;
protected function setUp(): void
{
$this->asn1 = new Asn1();
}
private function client(bool $nonce = false, string $policyOid = '', string $hash = 'sha256'): Client
{
return new Client(new Config(
host: 'https://tsa.example.org',
hashAlgorithm: $hash,
policyOid: $policyOid,
nonceEnabled: $nonce,
));
}
/**
* Build a minimal valid TimeStampResp wrapping the given content.
*
* @param int<0, max> $statusCode PKIStatus value.
*/
private function response(int $statusCode, string $content): string
{
return $this->asn1->encodeSequence(
$this->asn1->encodeSequence($this->asn1->encodeInteger($statusCode)) . $content,
);
}
private function sampleToken(): string
{
return $this->asn1->encodeSequence($this->asn1->encodeObjectIdentifier('1.2.840.113549.1.7.2'));
}
public function testHashAlgorithmOid(): void
{
$client = $this->client();
$this->assertSame('2.16.840.1.101.3.4.2.1', $client->hashAlgorithmOid('sha256'));
$this->assertSame('2.16.840.1.101.3.4.2.2', $client->hashAlgorithmOid('sha384'));
$this->assertSame('2.16.840.1.101.3.4.2.3', $client->hashAlgorithmOid('sha512'));
}
public function testHashAlgorithmOidRejectsUnknown(): void
{
$this->expectException(Exception::class);
$this->client()->hashAlgorithmOid('sha1');
}
public function testBuildRequestStructure(): void
{
$req = $this->client()->buildRequest('payload');
$offset = 0;
$root = $this->asn1->readTlv($req, $offset);
$this->assertSame(0x30, $root['tag']);
$this->assertSame(\strlen($req), $offset);
$inner = 0;
$version = $this->asn1->readTlv($root['value'], $inner);
$this->assertSame(0x02, $version['tag']);
$this->assertSame(1, $this->asn1->decodeInteger($version['value']));
$messageImprint = $this->asn1->readTlv($root['value'], $inner);
$this->assertSame(0x30, $messageImprint['tag']);
$certReq = $this->asn1->readTlv($root['value'], $inner);
$this->assertSame(0x01, $certReq['tag']);
$this->assertSame("\xFF", $certReq['value']);
// Nothing follows certReq when no policy and no nonce are present.
$this->assertSame(\strlen($root['value']), $inner);
// The message imprint carries the SHA-256 digest of the input.
$miOffset = 0;
$algId = $this->asn1->readTlv($messageImprint['value'], $miOffset);
$this->assertSame(0x30, $algId['tag']);
$digest = $this->asn1->readTlv($messageImprint['value'], $miOffset);
$this->assertSame(0x04, $digest['tag']);
$this->assertSame(\hash('sha256', 'payload', true), $digest['value']);
}
public function testBuildRequestIncludesPolicyOid(): void
{
$req = $this->client(policyOid: '1.2.3.4')->buildRequest('x');
$offset = 0;
$root = $this->asn1->readTlv($req, $offset);
$inner = 0;
$this->asn1->readTlv($root['value'], $inner); // version
$this->asn1->readTlv($root['value'], $inner); // messageImprint
$policy = $this->asn1->readTlv($root['value'], $inner);
$this->assertSame(0x06, $policy['tag']);
$this->assertSame($this->asn1->encodeObjectIdentifier('1.2.3.4'), $policy['raw']);
}
public function testBuildRequestIncludesNonce(): void
{
$req = $this->client(nonce: true)->buildRequest('x');
$offset = 0;
$root = $this->asn1->readTlv($req, $offset);
$inner = 0;
$this->asn1->readTlv($root['value'], $inner); // version
$this->asn1->readTlv($root['value'], $inner); // messageImprint
$nonce = $this->asn1->readTlv($root['value'], $inner);
$this->assertSame(0x02, $nonce['tag']);
$certReq = $this->asn1->readTlv($root['value'], $inner);
$this->assertSame(0x01, $certReq['tag']);
}
public function testParseResponseReturnsToken(): void
{
$token = $this->sampleToken();
$this->assertSame($token, $this->client()->parseResponse($this->response(0, $token)));
// status 1 (granted with mods) is also accepted
$this->assertSame($token, $this->client()->parseResponse($this->response(1, $token)));
}
public function testParseResponseRejectsEmpty(): void
{
$this->expectException(Exception::class);
$this->client()->parseResponse('');
}
public function testParseResponseRejectsNonSequenceRoot(): void
{
$this->expectException(Exception::class);
$this->client()->parseResponse($this->asn1->encodeInteger(0));
}
public function testParseResponseRejectsInvalidStatusStructure(): void
{
$bad = $this->asn1->encodeSequence($this->asn1->encodeInteger(0) . $this->sampleToken());
$this->expectException(Exception::class);
$this->client()->parseResponse($bad);
}
public function testParseResponseRejectsNonIntegerStatus(): void
{
$bad = $this->asn1->encodeSequence(
$this->asn1->encodeSequence($this->asn1->encodeOctetString('x')) . $this->sampleToken(),
);
$this->expectException(Exception::class);
$this->client()->parseResponse($bad);
}
public function testParseResponseRejectsRejectedStatus(): void
{
$this->expectException(Exception::class);
$this->client()->parseResponse($this->response(2, $this->sampleToken()));
}
public function testParseResponseRejectsMissingToken(): void
{
$noToken = $this->asn1->encodeSequence($this->asn1->encodeSequence($this->asn1->encodeInteger(0)));
$this->expectException(Exception::class);
$this->client()->parseResponse($noToken);
}
public function testParseResponseRejectsNonSequenceToken(): void
{
$bad = $this->asn1->encodeSequence(
$this->asn1->encodeSequence($this->asn1->encodeInteger(0)) . $this->asn1->encodeInteger(5),
);
$this->expectException(Exception::class);
$this->client()->parseResponse($bad);
}
public function testRequestTokenUsesTransport(): void
{
$token = $this->sampleToken();
$response = $this->response(0, $token);
$captured = '';
$transport = static function (string $request) use (&$captured, $response): string {
$captured = $request;
return $response;
};
$result = $this->client()->requestToken('payload', $transport);
$this->assertSame($token, $result);
// The transport received a well-formed DER request.
$offset = 0;
$root = $this->asn1->readTlv($captured, $offset);
$this->assertSame(0x30, $root['tag']);
}
public function testRequestTokenRejectsNonStringTransportResult(): void
{
$transport = static fn(string $request): int => \strlen($request);
$this->expectException(Exception::class);
$this->client()->requestToken('payload', $transport);
}
}
@@ -0,0 +1,78 @@
<?php
declare(strict_types=1);
/**
* ConfigTest.php
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*
* This file is part of tc-lib-pdf-sign software library.
*/
namespace Test\Timestamp;
use Com\Tecnick\Pdf\Sign\Exception;
use Com\Tecnick\Pdf\Sign\Timestamp\Config;
use PHPUnit\Framework\TestCase;
/**
* Timestamp Config Test
*
* @since 2026-07-15
* @category Library
* @package PdfSign
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-sign
*/
class ConfigTest extends TestCase
{
public function testDefaults(): void
{
$cfg = new Config(host: 'https://tsa.example.org/tsr');
$this->assertSame('https://tsa.example.org/tsr', $cfg->host);
$this->assertSame('sha256', $cfg->hashAlgorithm);
$this->assertSame('', $cfg->policyOid);
$this->assertTrue($cfg->nonceEnabled);
$this->assertSame(5, $cfg->timeout);
$this->assertTrue($cfg->verifyPeer);
}
public function testAcceptsValidPolicyOid(): void
{
$cfg = new Config(host: 'https://tsa.example.org', policyOid: '1.2.3.4.5');
$this->assertSame('1.2.3.4.5', $cfg->policyOid);
}
public function testEmptyHostThrows(): void
{
$this->expectException(Exception::class);
new Config(host: '');
}
public function testInvalidHashAlgorithmThrows(): void
{
$this->expectException(Exception::class);
new Config(host: 'https://tsa.example.org', hashAlgorithm: 'md5');
}
public function testInvalidPolicyOidThrows(): void
{
$this->expectException(Exception::class);
new Config(host: 'https://tsa.example.org', policyOid: 'not-an-oid');
}
public function testInvalidTimeoutThrows(): void
{
$this->expectException(Exception::class);
new Config(host: 'https://tsa.example.org', timeout: 0);
}
}
@@ -0,0 +1,25 @@
-----BEGIN CERTIFICATE-----
MIIEIjCCAwqgAwIBAgIUWNwtf35SSDKt+d9LEkCR8OJsr4QwDQYJKoZIhvcNAQEL
BQAwQTELMAkGA1UEBhMCSVQxFDASBgNVBAoMC1RlY25pY2suY29tMRwwGgYDVQQD
DBN0Yy1saWItcGRmLXNpZ24gbHR2MB4XDTI2MDcxNTE1MjA0NFoXDTM2MDcxMjE1
MjA0NFowQTELMAkGA1UEBhMCSVQxFDASBgNVBAoMC1RlY25pY2suY29tMRwwGgYD
VQQDDBN0Yy1saWItcGRmLXNpZ24gbHR2MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A
MIIBCgKCAQEAg4XPQlnyr4QdxRDUBUHLZVC+wEyOtkmSX9RAGISr8ytuY8bFh3Tc
coLT8pdMYGDg3ZxV+MJ1wUAmv2b8pDl2/ve22ZdldrPR06kUQcl/9b/sxWcEuDyV
viwZpXFdkX3minGkbsgoaun2zPvSZS+r77XCXhXFnx70kgQtg0rSuiCVLoPL7XiG
K/vK9ZqcDMQhxyUyqmJxKdvqgmM0v7TjGF+A6Mo65Sc+8rYRa50jfpDf4+3vPAJu
AZktlnhSz5ZAhg6MSDR/qmOJQB0wbHVqrTr/H/Vpxl4Hm4+HvSl+71wxr+eE1ENR
VM7OuBRz0f4FmPpFC1u54xgTvFDz0vDe2wIDAQABo4IBEDCCAQwwHQYDVR0OBBYE
FNGM/XjoY0lALUKtwHTkWY3c6nZ6MB8GA1UdIwQYMBaAFNGM/XjoY0lALUKtwHTk
WY3c6nZ6MA8GA1UdEwEB/wQFMAMBAf8wXwYIKwYBBQUHAQEEUzBRMCUGCCsGAQUF
BzABhhlodHRwOi8vb2NzcC5leGFtcGxlLm9yZy9yMCgGCCsGAQUFBzAChhxodHRw
Oi8vY2EuZXhhbXBsZS5vcmcvY2EuY3J0MFgGA1UdHwRRME8wJaAjoCGGH2h0dHA6
Ly9jcmwuZXhhbXBsZS5vcmcvcm9vdC5jcmwwJqAkoCKGIGh0dHA6Ly9jcmwyLmV4
YW1wbGUub3JnL3Jvb3QuY3JsMA0GCSqGSIb3DQEBCwUAA4IBAQAY7wLUL9YwBdN/
sVtGFDd264QBANh18iKhv9hybvAPA2xcI7vxcW8voiL3ad1IUoUJ+TZktTq/VF52
T7dA9lml5vhospkTlRpG8yRBLYm+p2KuIxAKcuIIxe8kzygVYc3eyWJ8jL2ExcC+
H3Y4W0/5S72qvOUL3avI0s/3ru/bPR5mb55CbNLLlqS+GViU3BqLlP7JwM/DRWPu
k4tH5cSfzGZp9pu9wtXr4sbGF5MPVz8IjwzGvHOR93TtuiKWs52eI8pZ/fVQo2y7
tANdIGmFNUWUrKrtwUHLO+fdQ4p0sqj33UuqVdj04iIubyIdU7Ef7H0kkeJf48/y
D7BYPfJl
-----END CERTIFICATE-----
+21
View File
@@ -0,0 +1,21 @@
-----BEGIN CERTIFICATE-----
MIIDazCCAlOgAwIBAgIUOTFQcwfHy5Q5NgSG2L1p7A9oPWgwDQYJKoZIhvcNAQEL
BQAwRTELMAkGA1UEBhMCSVQxFDASBgNVBAoMC1RlY25pY2suY29tMSAwHgYDVQQD
DBd0Yy1saWItcGRmLXNpZ24gcm9vdCBDQTAeFw0yNjA3MTUxNDU1MzVaFw00NjA3
MTAxNDU1MzVaMEUxCzAJBgNVBAYTAklUMRQwEgYDVQQKDAtUZWNuaWNrLmNvbTEg
MB4GA1UEAwwXdGMtbGliLXBkZi1zaWduIHJvb3QgQ0EwggEiMA0GCSqGSIb3DQEB
AQUAA4IBDwAwggEKAoIBAQDAACX+3AyfPuwOXtzL2l6jVCu3UFVEw6FFqMxFZrpl
QsG1VfQLCIaotd6+UIypRV9hq67Au3n+naLZnLtmCuyiR0EbxnQYf67U4QZak+cq
yKwndEqROMyqZYyf4IYyVyW3E4W/mT9LoD7ISSbPvbAWv72cvBgi2OKUtlxUZehE
V0qVOEQck3ZOwzlggRGZLMnWi55+dTb1fP+61LU3aWBiR1FS0Nxg5PRSC4S6trVZ
2HsGMKtxEKD1veYY6sGcH4fqSA3AI6+AMrgbtp6HsfgnPw+1Q+zt0yEK+E//8Kpx
P9VFMj8/ONT9BVERqihwX+17km5o5/kd01ZzstebvElVAgMBAAGjUzBRMB0GA1Ud
DgQWBBQqzMd3ZI35/UK3VNIFWjzwgJVfTzAfBgNVHSMEGDAWgBQqzMd3ZI35/UK3
VNIFWjzwgJVfTzAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQBt
QYNoek7H5NrID9Csy2ad9RoFpMZeGQr5c0Z8SlBd/CbD9DP6K5UsRb+w1C6XGenl
CWxa0a0FOXqD8pP7foaGd1jieQ3/BAtiBrMn7ulPbJNlLwt0Qxt9FKxihjvOjmiO
wlmLBSJWWh7eeUT0RVCpIksse2TCHuhGcvMLhH/gt0WwIe9fNWikzD4X7Cv1jldF
50OvuSnXdp3ThQ6DDKb/fWDeYJUtXD4Nl/NH34ReV9HJOL8sdpsnWxZb49SkbKKs
3ww1F4Pceiw4BOOUGRyVdizUQmwucE0T/98458acCmCShXdEneS+O7hvFXzrvmgm
hLEVWFk9n7mJuNHTiehZ
-----END CERTIFICATE-----
@@ -0,0 +1,20 @@
-----BEGIN CERTIFICATE-----
MIIDVzCCAj+gAwIBAgIUBNC7KlNLnV+s3gpiiwug3I64MEMwDQYJKoZIhvcNAQEL
BQAwRTELMAkGA1UEBhMCSVQxFDASBgNVBAoMC1RlY25pY2suY29tMSAwHgYDVQQD
DBd0Yy1saWItcGRmLXNpZ24gcm9vdCBDQTAeFw0yNjA3MTUxNDU1MzVaFw0zNjA3
MTIxNDU1MzVaMEIxCzAJBgNVBAYTAklUMRQwEgYDVQQKDAtUZWNuaWNrLmNvbTEd
MBsGA1UEAwwUdGMtbGliLXBkZi1zaWduIGxlYWYwggEiMA0GCSqGSIb3DQEBAQUA
A4IBDwAwggEKAoIBAQCzQUS2pvzQ7P1LBwWEgU5eyT3dRkHeTkcmcmj49IaGKREM
boSywMTqk+LmZYqXrSB90OVIOOU0X7zXJTWta7u97GwFYPscZwS7tEycY8Vrwpau
Y+Su3KpfwN9I5re7RgCW/N3u+voZ4BpOGkhoUgoN3GF87jf/eVq3Uy1FqVOizG5J
aZzflElpg+SyuuRz4H0x+PsyftMDDG+WJoaWV/KIk25+QeiRgqmBwi3bSokeITsl
E5glr9fSktThyoHa/u5Yn1Wv8QqGfOnOxxusHPM/WEZ8JdvnzBXuxVi9xpiBwfq/
FnyAVN8W5OBd91cWR7xTN5aMmzItIgvmYRJ4vuXhAgMBAAGjQjBAMB0GA1UdDgQW
BBQxGlEGCBM5nkqll8ti1cOLI4SD3zAfBgNVHSMEGDAWgBQqzMd3ZI35/UK3VNIF
WjzwgJVfTzANBgkqhkiG9w0BAQsFAAOCAQEAaiQbyzIGNu2qptaKEm/pMBqhuJ/e
S69RfW/ZF3gDwRUdCEV8MCqpX+goWCZwjj8vCBTIYk6sZSpN0S6TQQ19h2U3qoyK
WqKMxZQo69AQ8/O4I6pVuBQ8u4H9aCEkrq0WD+8bNNSYlRFWX49dZ0CmIRpcWBl3
Qwr37FiSdFh8yRdX7HU2yMXtih9eL/teiGxtB8zuwh/UlpamwsldIkkv/45aoRD1
/TV79ltJDEbV1wVPxkccVQbw7PV3DfRb1KZIb3oXM1LMWrCa25dOR8fyqkhdz+f0
dqz41uIJzONQQu7EzWWBYP1XwKsTjP6PHZR6vJ/s+aty0lpQuUCT0HtFwg==
-----END CERTIFICATE-----