CodeSign Zig Reference Documentation
CodeSign
Current Version: 11.6.1
Chilkat.CodeSign
Apply Authenticode signatures to Windows executable 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 Windows executable 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.
Chilkat.CodeSign works directly with Authenticode signatures on
Windows executable files such as .exe and .dll.
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 EXE and DLL files
Validate trust
Inspect signatures
Retrieve signer certificates
Chilkat.Cert.
Remove signatures
Diagnostics
.exe or .dll, optionally add
timestamping if supported by the signing workflow, then verify the resulting
signature and inspect diagnostics if validation does not succeed.
Object Creation
// Add the package once:
// zig fetch --save https://chilkatdownload.com/11.6.1/chilkat-zig-11.6.1.tar.gz
// and in build.zig:
// const chilkat = b.dependency("chilkat", .{ .target = target, .optimize = optimize });
// exe.root_module.addImport("chilkat", chilkat.module("chilkat"));
const chilkat = @import("chilkat");
// Once per process, before any other Chilkat call:
try chilkat.unlockBundle("Anything for 30-day trial");
const code_sign = try chilkat.CodeSign.init();
defer code_sign.deinit();Creates the underlying native Chilkat object. CodeSign is a one-pointer struct passed by value; copying it copies the handle (two names for one object). Returns error.OutOfMemory if the library could not allocate the object. Use an object from one thread at a time; it may be handed from one thread to another.
Releases the native object. Call it exactly once per object (usually with defer); the handle is invalid afterwards. Objects returned by methods are owned by the caller too and are released the same way.
Wraps a handle obtained from the C API (chilkat.c.CkCodeSign), taking ownership of it. The struct's handle field goes the other way, for anything the Zig API does not cover.
Errors and memory
Methods that can fail return an error union: a method whose only outcome is success or failure returns Error!void; a method producing a string returns (Error || Allocator.Error)![:0]u8; a method producing an object returns Error!T. chilkat.Error is error{ChilkatFailed}; the reason for a failure is in getLastErrorText, and the object remains usable. Properties never fail, and methods that answer a question (hasMember, isUnlocked, ...) return a plain bool.
String arguments are [:0]const u8 (UTF-8; string literals can be passed as is). String results are copies allocated with the allocator argument and owned by the caller, so they stay valid across later calls on the same object.
const text = code_sign.someMethod(allocator, ...) catch |err| {
const why = try code_sign.getLastErrorText(allocator);
defer allocator.free(why);
std.debug.print("{s}\n", .{why});
return err;
};
defer allocator.free(text);
Properties
DebugLogFilePath
pub fn getDebugLogFilePath(self: CodeSign, allocator: Allocator) Allocator.Error![:0]u8
pub fn setDebugLogFilePath(self: CodeSign, value: [:0]const u8) void
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
pub fn getHeartbeatMs(self: CodeSign) i32
pub fn setHeartbeatMs(self: CodeSign, value: i32) void
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
pub fn getLastErrorHtml(self: CodeSign, allocator: Allocator) Allocator.Error![:0]u8
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
pub fn getLastErrorText(self: CodeSign, allocator: Allocator) Allocator.Error![:0]u8
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
pub fn getLastErrorXml(self: CodeSign, allocator: Allocator) Allocator.Error![:0]u8
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
pub fn getLastMethodSuccess(self: CodeSign) bool
pub fn setLastMethodSuccess(self: CodeSign, value: bool) void
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
pub fn getUncommonOptions(self: CodeSign, allocator: Allocator) Allocator.Error![:0]u8
pub fn setUncommonOptions(self: CodeSign, value: [:0]const u8) void
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. |
VerboseLogging
pub fn getVerboseLogging(self: CodeSign) bool
pub fn setVerboseLogging(self: CodeSign, value: bool) void
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
pub fn getVersion(self: CodeSign, allocator: Allocator) Allocator.Error![:0]u8
Methods
AddSignature
Adds a Microsoft Authenticode signature to the Windows executable or DLL 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.
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 error.ChilkatFailed on failure; getLastErrorText explains why.
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.
VerifySignature and the returned signature information when making a trust decision.Returns error.ChilkatFailed on failure; getLastErrorText explains why.
RemoveSignature
Removes the embedded Authenticode signature from the Windows executable or DLL specified by path. The file is modified in place. Returns true if the signature is successfully removed; otherwise returns false.
Returns error.ChilkatFailed on failure; getLastErrorText explains why.
VerifySignature
Verifies the embedded Microsoft Authenticode signature of the Windows executable or DLL specified by path. Structured information about the signature, signer, certificate chain, digest algorithms, timestamp, and validation result is written to sig_info.
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 sig_info and LastErrorText for details.
Returns error.ChilkatFailed on failure; getLastErrorText explains why.
Events
All Chilkat methods are synchronous: the call returns when the work is done. During a call, CodeSign raises three events so your program can show progress and offer a way out. Declare any subset of abortCheck, percentDone and progressInfo in a struct of your own and install a pointer to it with setEventHandler:
const Progress = struct {
pub fn percentDone(_: *Progress, pct: i32) bool {
std.debug.print("{d}%\n", .{pct});
return false; // return true to abort the method in progress
}
pub fn progressInfo(_: *Progress, name: [:0]const u8, value: [:0]const u8) void {
std.debug.print("{s}: {s}\n", .{ name, value });
}
};
var progress = Progress{};
code_sign.setEventHandler(&progress); // progress must outlive the installation
defer code_sign.clearEventHandler();
code_sign.setHeartbeatMs(250); // abortCheck 4 times per second during Chilkat callsInstalls handler, a pointer to any struct, as the receiver of this object's events, replacing any handler installed earlier. The dispatch is resolved at compile time: only the methods the struct declares are called, and a struct declaring none of the three is a compile error. The struct must stay alive, at the same address, until clearEventHandler or deinit.
Removes the handler; events are no longer delivered.
AbortCheck fires at regular intervals controlled by the HeartbeatMs property (0, the default, disables it); PercentDone fires when an operation's completion percentage is known; ProgressInfo delivers named progress values. Returning true from abortCheck or percentDone aborts the running method, which then returns error.ChilkatFailed.
Events fire on the thread that called the method, before that method returns. To abort a long operation from another thread, have abortCheck read a std.atomic.Value(bool), or set the object's AbortCurrent property.
AbortCheck
pub fn abortCheck(self: *T) bool
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
const Abort = struct {
stop: std.atomic.Value(bool) = .init(false),
pub fn abortCheck(self: *Abort) bool {
return self.stop.load(.acquire); // another thread may call abort.stop.store(true, .release)
}
};
var abort = Abort{};
code_sign.setHeartbeatMs(250); // call abortCheck 4 times per second
code_sign.setEventHandler(&abort);
defer code_sign.clearEventHandler();PercentDone
pub fn percentDone(self: *T, pct: i32) bool
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
const Progress = struct {
pub fn percentDone(_: *Progress, pct: i32) bool {
// pct ranges from 1 to 100.
std.debug.print("Percent done: {d}\n", .{pct});
return false; // return true to abort the method in progress
}
};
var progress = Progress{};
code_sign.setEventHandler(&progress);
defer code_sign.clearEventHandler();ProgressInfo
pub fn progressInfo(self: *T, name: [:0]const u8, value: [:0]const u8) void
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
const Info = struct {
pub fn progressInfo(_: *Info, name: [:0]const u8, value: [:0]const u8) void {
std.debug.print("{s}: {s}\n", .{ name, value });
}
};
var info = Info{};
code_sign.setEventHandler(&info);
defer code_sign.clearEventHandler();