CodeSign Chilkat2 Perl Reference Documentation
Chilkat2::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;
my $codeSign = Chilkat2::CodeSign->new;
# or set properties (and RaiseError) at creation:
# my $codeSign = Chilkat2::CodeSign->new(VerboseLogging => 1, RaiseError => 1);Creates the object. The optional pairs set writable properties (and RaiseError) in order, as if set one by one; an unknown or read-only name croaks. use Chilkat2; loads every class; the Chilkat2/CodeSign.pm file holds only this class's documentation (perldoc Chilkat2::CodeSign). Windows only: the class exists only in the Windows builds of the module.
Perl frees the object when its last reference goes (undef $codeSign, or the variable going out of scope); there is nothing to close. Objects returned by methods are independent and freed the same way. The class may be subclassed (use parent -norequire, 'Chilkat2::CodeSign';): an object is a blessed hash reference whose hash is free for the subclass's own fields.
When false (the default), a method that fails returns false (or undef), and the reason is in LastErrorText. When true, it dies with a Chilkat2::Error instead, as DBI does with its RaiseError. Objects returned by a method inherit the value of the object that returned them.
Errors
A Chilkat2::Error stringifies to the failed call's full LastErrorText, and has the methods text, class ('Chilkat2::CodeSign'), method (the method name) and object. Methods that look something up and find nothing return undef without dying (each such method says so), methods that answer a question (HasMember, IsUnlocked, ...) return a plain boolean, and property reads and writes never fail for Chilkat reasons.
Misuse always croaks, with your file and line, whatever RaiseError is: a wrong number of arguments, a reference or undef where a string or number is expected, an object of the wrong class, an out-of-range integer, a string containing a NUL character, a wide character in a byte string, or a write to a read-only property.
Strings are Perl character strings in both directions (length, regexes and :encoding layers see characters); binary data (BinData) is a byte string. Unlocking: call Chilkat2::Global->new->UnlockBundle('...') once at startup.
Properties
DebugLogFilePath
my $strVal = $codeSign->DebugLogFilePath;
$codeSign->DebugLogFilePath($strVal);
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
my $intVal = $codeSign->HeartbeatMs;
$codeSign->HeartbeatMs($intVal);
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
my $strVal = $codeSign->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
my $strVal = $codeSign->LastErrorText;
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
my $strVal = $codeSign->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
my $boolVal = $codeSign->LastMethodSuccess;
$codeSign->LastMethodSuccess($boolVal);
Indicates the success or failure of the most recent method call: 1 means success, 0 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
my $strVal = $codeSign->UncommonOptions;
$codeSign->UncommonOptions($strVal);
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
my $boolVal = $codeSign->VerboseLogging;
$codeSign->VerboseLogging($boolVal);
If set to 1, then the contents of LastErrorText (or LastErrorXml, or LastErrorHtml) may contain more verbose information. The default value is 0. Verbose logging should only be used for debugging. The potentially large quantity of logged information may adversely affect peformance.
Version
my $strVal = $codeSign->Version;
Methods
AddSignature
# $cert is a Chilkat2::Cert
# $options is a Chilkat2::JsonObject
# $success is true or false
my $success = $codeSign->AddSignature($path, $cert, $options);
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 0, 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, false on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
GetSignerCert
# $success is true or false
my $success = $codeSign->GetSignerCert($cert);
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 1. Otherwise, the method returns 0.
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 1. After a failed verification, this method returns 0.
VerifySignature and the returned signature information when making a trust decision.Returns true on success, false on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
RemoveSignature
# $success is true or false
my $success = $codeSign->RemoveSignature($path);
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 1 if the signature is successfully removed; otherwise returns 0.
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, false on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
VerifySignature
# $sigInfo is a Chilkat2::JsonObject
# $success is true or false
my $success = $codeSign->VerifySignature($path, $sigInfo);
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 0. Structured information about the signature, signer, certificate chain, digest algorithms, timestamp, and validation result is written to $sigInfo.
Returns 1 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 0. 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 0 unless the codesign-allow-cert-padding option is set in UncommonOptions.
MSI packages signed with an ECDSA certificate: this method can return 1 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, false on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
Events
All Chilkat methods are synchronous: the call returns when the work is done. During a long-running call, Chilkat2::CodeSign reports progress to handlers installed with on, which takes Event => CODE pairs (closures, so a handler can use the variables around it):
$codeSign->on(
PercentDone => sub { my ($pctDone) = @_; print "$pctDone%\n"; return 0 }, # a true return aborts
ProgressInfo => sub { my ($name, $value) = @_; print "$name: $value\n" },
);
$codeSign->HeartbeatMs(250); # the AbortCheck handler is called 4 times per secondInstalls the handlers given, replacing those installed before for the same events; undef instead of a CODE reference removes one, and $codeSign->on() with no arguments returns the installed handlers as a list of pairs. The event names are checked: a misspelled one croaks, and nothing is installed.
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 true return from the AbortCheck or PercentDone handler aborts the running method, which then fails in the usual way (false or undef, or a Chilkat2::Error under RaiseError).
Handlers run during the method call, on the thread that called it. Inside a handler, other objects may be used, but calling a method of the same object (or its on) croaks. A die in a handler aborts the running method and is re-thrown from the method call; the object remains usable. A handler that uses $codeSign itself makes a reference cycle: weaken the captured copy (Scalar::Util) or remove the handler when done.
AbortCheck
$codeSign->on(AbortCheck => sub { ... });
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
my $deadline = time() + 30; # give up after 30 seconds
$codeSign->HeartbeatMs(250); # call the handler 4 times per second
$codeSign->on(AbortCheck => sub { return time() > $deadline });PercentDone
$codeSign->on(PercentDone => sub { ... });
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 1. This will cause the method to terminate and return a failure status or corresponding failure value.
Example
$codeSign->on(PercentDone => sub {
my ($pctDone) = @_; # 0 to 100
print "Percent done: $pctDone\n";
return 0; # return a true value to abort the method in progress
});ProgressInfo
$codeSign->on(ProgressInfo => sub { ... });
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->on(ProgressInfo => sub {
my ($name, $value) = @_;
print "$name: $value\n";
});