CodeSign Chilkat2 PHP Reference Documentation
CodeSign
Current Version: 11.7.0
Markdown version of this page for AI tools (v 11.7.0) · all AI docs
Chilkat.CodeSign
Apply Authenticode signatures to EXE, DLL, MSI, PowerShell, and VBScript
files using a certificate and associated private key.
Check whether a signed executable has a valid signature and whether the
signing certificate chain can be trusted.
Extract details about the Authenticode signature, including signer
information and signature-related metadata.
Get the certificate used to sign the executable and inspect it with
Remove an existing Authenticode signature from a signed file when
an unsigned output file is required.
Use detailed diagnostic output to troubleshoot signing, certificate,
trust-chain, timestamping, or validation problems.
For an extended overview, see
CodeSign Class Overview.
Sign, verify, inspect, and remove Authenticode signatures on Windows executables, installers, and scripts.
Chilkat.CodeSign works directly with Authenticode signatures on
Windows executable files such as .exe and .dll, and,
starting in v11.7.0, on Windows Installer packages (.msi),
PowerShell files (.ps1, .psm1, .psd1), and
VBScript files (.vbs).
It provides functionality for applying a code-signing signature, validating
whether a signed executable can be trusted, extracting signature information,
retrieving the signer certificate, and removing an existing signature.
Sign executables, installers, and scripts
Validate trust
Inspect signatures
Retrieve signer certificates
Chilkat.Cert.
Remove signatures
Diagnostics
Object Creation
use Chilkat2\CodeSign;
try {
$codeSign = new CodeSign();
// ... use $codeSign ...
} catch (\Chilkat2\Exception $e) {
echo $e->getClass(), '::', $e->getMethod(), " failed\n";
echo $e->getMessage(), "\n"; // the LastErrorText of the failed call
}Creates the object. The optional array sets properties in order, as if assigned one by one (new CodeSign(['VerboseLogging' => true, 'RaiseError' => false])); an unknown or read-only name throws Error. The class is defined by the chilkat2 extension (extension=chilkat2 in php.ini): there is no PHP file to include. Windows only: the class exists only in the Windows builds of the extension.
There is no close(): PHP frees the object when its last reference goes (unset($codeSign), $codeSign = null, or the end of the function or request). Objects returned by methods are independent and freed the same way. The class may be extended (class MyCodeSign extends \Chilkat2\CodeSign); objects cannot be cloned or serialized.
When true (the default), a method that fails throws Chilkat2\Exception. When false, it returns false (or null) instead, and the reason is in LastErrorText. Objects returned by a method inherit the value of the object that returned them.
Errors
Chilkat2\Exception extends RuntimeException: getMessage() is the failed call's full LastErrorText, getClass() its class ('Chilkat2\CodeSign') and getMethod() the method name. The object remains usable. Methods that look something up and find nothing return null without throwing (each such method says so), methods that answer a question (HasMember, IsUnlocked, ...) return a plain bool, and property reads and writes do not throw for Chilkat reasons.
Misuse always throws, whatever RaiseError is: a wrong argument type is a TypeError (exact types under declare(strict_types=1)), a missing or extra argument an ArgumentCountError, a string containing a NUL byte or an out-of-range integer a ValueError, and an unknown property (properties are case-sensitive) or a write to a read-only one an Error. Named arguments work with the parameter names shown.
Strings are passed and returned as UTF-8; binary data is a PHP string of bytes. Unlocking: call (new \Chilkat2\GlobalSettings())->UnlockBundle('...') once at startup.
Properties
DebugLogFilePath
If set to a file path, this property logs the LastErrorText of each Chilkat method or property call to the specified file. This logging helps identify the context and history of Chilkat calls leading up to any crash or hang, aiding in debugging.
Enabling the VerboseLogging property provides more detailed information. This property is mainly used for debugging rare instances where a Chilkat method call causes a hang or crash, which should generally not happen.
Possible causes of hangs include:
- A timeout property set to 0, indicating an infinite timeout.
- A hang occurring within an event callback in the application code.
- An internal bug in the Chilkat code causing the hang.
HeartbeatMs
Specifies the approximate interval, in milliseconds, between AbortCheck event callbacks during supported operations. An event handler can request that the current operation be aborted.
The default is 0, which disables AbortCheck callbacks. Setting a positive value enables periodic callbacks when an operation is sufficiently long-running; methods that finish quickly may complete without generating one.
LastErrorHtml
Provides HTML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
topLastErrorText
Provides plain text information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
LastErrorXml
Provides XML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
topLastMethodSuccess
Indicates the success or failure of the most recent method call: true means success, false means failure. This property remains unchanged by property setters or getters. This method is present to address challenges in checking for null or Nothing returns in certain programming languages. Note: This property does not apply to methods that return integer values or to boolean-returning methods where the boolean does not indicate success or failure.
UncommonOptions
Provides a comma-separated list of specialized compatibility or validation options. The default is an empty string, which is appropriate for normal use.
| Option | Effect |
|---|---|
codesign-allow-expired-cert | Prevents Authenticode verification from failing solely because the signing certificate is expired. |
codesign-allow-cert-padding | Starting in v11.7.0. Prevents verification of an EXE or DLL from failing solely because the PE certificate table fails the strict check (extra data or entries outside the verified signature). The failed check is still reported in LastErrorText. Use only for files known to carry such data, such as some installers that store configuration data in the certificate table. |
codesign-allow-expired-cert is not a substitute for timestamping. A signature carrying a valid trusted timestamp should ordinarily remain verifiable after the signing certificate expires without this option.VerboseLogging
If set to true, then the contents of LastErrorText (or LastErrorXml, or LastErrorHtml) may contain more verbose information. The default value is false. Verbose logging should only be used for debugging. The potentially large quantity of logged information may adversely affect peformance.
Version
Methods
AddSignature
Adds a Microsoft Authenticode signature to the file specified by $path. The file is modified in place. $cert supplies the code-signing certificate and must provide access to its associated private key. $options supplies the signing configuration as JSON.
Starting in v11.7.0, Windows Installer packages, PowerShell files, and VBScript files can be signed in addition to Windows executables and DLLs. The supported file types are:
| File type | Extensions | Where the signature is stored |
|---|---|---|
| Windows PE images | .exe, .dll, and other PE files such as .sys and .ocx | The PE certificate table. PE files are identified from the file content, not the extension. |
| Windows Installer packages (starting in v11.7.0) | .msi | The package's digital signature stream. |
| PowerShell scripts, modules, and data files (starting in v11.7.0) | .ps1, .psm1, .psd1 | A comment block appended to the file (# SIG # Begin signature block ... # SIG # End signature block). The file's text encoding (UTF-8, UTF-8 with BOM, or UTF-16) is kept. |
| VBScript files (starting in v11.7.0) | .vbs | A comment block appended to the file ('' SIG '' Begin signature block ... '' SIG '' End signature block). |
Any other file type (for example .js, .cab, or .cat) causes the method to return false, with LastErrorText explaining that the file type is not supported, and the file is not modified. The file must already exist; this method does not create it.
Starting in v11.7.0, if the file is already Authenticode-signed, the existing signature is removed and replaced by the new one. (Before v11.7.0, signing an already-signed EXE or DLL added a second signature entry instead of replacing the first.)
signtool verify, Get-AuthenticodeSignature, and the file's Digital Signatures properties, report the signature as invalid (TRUST_E_BAD_DIGEST, 0x80096010). This is a limitation of signed MSI files on Windows, not a Chilkat defect: an MSI signed by Microsoft's signtool with the same ECDSA certificate is rejected in the same way, and its signed content is identical to the signature Chilkat produces. Use an RSA code-signing certificate to sign MSI packages. ECDSA certificates work for EXE, DLL, PowerShell, and VBScript files.Common $options options include:
| JSON member | Purpose |
|---|---|
hashAlg | Selects the file-digest algorithm, such as sha256. |
timestampToken.enabled | Enables an RFC 3161 timestamp token. |
timestampToken.tsaUrl | Specifies the timestamp authority URL. |
timestampToken.requestTsaCert | Requests inclusion of the timestamp authority certificate. |
timestampToken.hashAlg | Selects the timestamp-request digest algorithm, such as sha256. |
{
"hashAlg": "sha256",
"timestampToken": {
"enabled": true,
"tsaUrl": "http://timestamp.example.com",
"requestTsaCert": true,
"hashAlg": "sha256"
}
}
Returns true on success. On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns false). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.
GetSignerCert
Retrieves the X.509 signer certificate discovered by the most recent call to VerifySignature on this CodeSign object. If the certificate is fully available, $cert is loaded with it and the method returns true. Otherwise, the method returns false.
The returned object contains the public certificate only; it does not provide the signer's private key. Call this method after VerifySignature and use the same CodeSign instance.
Starting in v11.7.0, the signer certificate is available only after a call to VerifySignature that returned true. After a failed verification, this method returns false.
VerifySignature and the returned signature information when making a trust decision.Returns true on success. On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns false). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.
RemoveSignature
Removes the embedded Authenticode signature from the file specified by $path: a Windows executable or DLL, or, starting in v11.7.0, a Windows Installer package (.msi), PowerShell file (.ps1, .psm1, .psd1), or VBScript file (.vbs). The file is modified in place. Returns true if the signature is successfully removed; otherwise returns false.
For PowerShell and VBScript files, the signature comment block is removed from the end of the file. For MSI packages, the digital signature stream and the extended signature stream (MsiDigitalSignatureEx) are removed.
Returns true on success. On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns false). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.
VerifySignature
Verifies the embedded Microsoft Authenticode signature of the file specified by $path: a Windows executable or DLL, or, starting in v11.7.0, a Windows Installer package (.msi), PowerShell file (.ps1, .psm1, .psd1), or VBScript file (.vbs). See AddSignature for the supported file types. Other file types cause the method to return false. Structured information about the signature, signer, certificate chain, digest algorithms, timestamp, and validation result is written to $sigInfo.
Returns true when the signature satisfies the applicable Authenticode validation checks under the current Windows trust configuration. This includes confirming that the signed portions of the file have not changed and evaluating the signing certificate and timestamp information, as applicable. An unsigned file or a signature that does not validate causes the method to return false. Inspect $sigInfo and LastErrorText for details.
Starting in v11.7.0, verification of an EXE or DLL also includes a strict check of the PE certificate table: it must hold exactly one signature entry, containing exactly the signature that was verified, with no extra data. Data in the certificate table is not covered by the Authenticode signature (see CVE-2013-3900), so anything hidden there would be unsigned. A file that fails this check causes the method to return false unless the codesign-allow-cert-padding option is set in UncommonOptions.
MSI packages signed with an ECDSA certificate: this method can return true for such a package, while Windows itself reports the signature as invalid. This is a limitation of signed MSI files on Windows, not a Chilkat defect; see the note in AddSignature.
Returns true on success. On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns false). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.
Events
All Chilkat methods are synchronous: the call returns when the work is done. During a long-running call, CodeSign reports progress to handlers installed with three methods, each taking any PHP callable (a closure, an arrow function, $this->method(...), an invokable object) and returning the object, so the calls chain:
$codeSign->onPercentDone(function (int $pctDone): bool {
echo "$pctDone%\n";
return false; // return true to abort the method in progress
})
->onProgressInfo(function (string $name, string $value): void {
echo "$name: $value\n";
});
$codeSign->HeartbeatMs = 250; // the AbortCheck handler is called 4 times per secondEach installs the handler for one event, replacing the one installed before; null removes it. A callable that does not exist is a TypeError right away.
The AbortCheck handler is called at the interval set by the HeartbeatMs property (0, the default, disables it); PercentDone is called when an operation's completion percentage is known; ProgressInfo delivers named progress values. A truthy return from the AbortCheck or PercentDone handler aborts the running method, which then fails in the usual way (Chilkat2\Exception, or false / null with RaiseError off). PHP's set_time_limit() does not interrupt a Chilkat call; an AbortCheck handler is how a script enforces its own limit.
Handlers run during the method call, in the same request. Inside a handler, the object's properties (such as $codeSign->AbortCurrent = true) and other objects may be used, but calling a method of the same object throws Error. An exception thrown by a handler aborts the running method and propagates from it; the object remains usable. A closure that captures $codeSign itself makes a reference cycle, which PHP's cycle collector frees.
AbortCheck
public function onAbortCheck(?callable $callback): static
Enables a method call to be aborted by triggering the AbortCheck event at intervals defined by the HeartbeatMs property. If HeartbeatMs is set to its default value of 0, no events will occur. For instance, set HeartbeatMs to 200 to trigger 5 AbortCheck events per second.
Example
$deadline = microtime(true) + 30; // give up after 30 seconds
$codeSign->HeartbeatMs = 250; // call the handler 4 times per second
$codeSign->onAbortCheck(fn(): bool => microtime(true) > $deadline);PercentDone
public function onPercentDone(?callable $callback): static
This provides the percentage completion for any method involving network communications or time-consuming processing, assuming the progress can be measured as a percentage. This event is triggered only when it's possible and logical to express the operation's progress as a percentage. The pctDone argument will range from 1 to 100. For methods that finish quickly, the number of PercentDone callbacks may vary, but the final callback will have pctDone equal to 100. For longer operations, callbacks will not exceed one per percentage point (e.g., 1, 2, 3, ..., 98, 99, 100).
The PercentDone callback also acts as an AbortCheck event. For fast methods where PercentDone fires, an AbortCheck event may not trigger since the PercentDone callback already provides an opportunity to abort. For longer operations, where time between PercentDone callbacks is extended, AbortCheck callbacks enable more responsive operation termination.
To abort the operation, set the abort output argument to true. This will cause the method to terminate and return a failure status or corresponding failure value.
Example
$codeSign->onPercentDone(function (int $pctDone): bool {
// $pctDone ranges from 0 to 100.
echo "Percent done: $pctDone\n";
return false; // return true to abort the method in progress
});ProgressInfo
public function onProgressInfo(?callable $callback): static
This event callback provides tag name/value pairs that detail what occurs during a method call. To discover existing tag names, create code to handle the event, emit the pairs, and review them. Most tag names are self-explanatory.
Note: Some Chilkat methods don't fire any ProgressInfo events.
Example
$codeSign->onProgressInfo(function (string $name, string $value): void {
echo "$name: $value\n";
});