Dkim Chilkat2 Java Reference Documentation
Dkim
Current Version: 11.7.0
Markdown version of this page for AI tools (v 11.7.0) · all AI docs
Chilkat.Dkim
Add DKIM signatures to MIME messages using a private key, selector,
signing domain, canonicalization settings, and selected headers.
Choose which message headers are protected by the signature and control
their order in the generated
Verify one or more signatures in a MIME message and determine whether the
signed content, headers, and public key match.
Configure body and header canonicalization so signing and verification
match the requirements of the sending domain and receiving systems.
Retrieve DKIM public keys from DNS, prefetch keys when useful, and cache
public keys to reduce repeated DNS lookups.
Use
For an extended overview, see
Dkim Class Overview.
Sign and verify MIME email with DKIM signatures.
Chilkat.Dkim is the Chilkat class for applying and verifying
DKIM signatures on MIME email data. It supports DKIM signing with
rsa-sha256 or rsa-sha1, configurable
canonicalization, selectable signed headers, signature counting, DNS
public-key lookup, public-key caching, public-key prefetching, and detailed
verification reporting through VerifyInfo.
DKIM signing
Signed header selection
h= tag.
Signature verification
Canonicalization control
DNS public keys
Verification diagnostics
VerifyInfo and related status information to understand
which signatures were found, which were checked, and why verification
succeeded or failed.
Dkim, allow the class
to locate the signature and public key, and inspect VerifyInfo
for detailed results.
Object Creation
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Dkim;
try (Dkim dkim = new Dkim()) {
// ... use dkim ...
} catch (ChilkatException e) {
System.out.println(e.getMessage()); // "Dkim.someMethod failed: <reason>"
System.out.println(e.getLastErrorText()); // the full log of the failed call
}Creates the underlying native Chilkat object. The native library (chilkat2java) is loaded the first time any Chilkat2 object is created; see the README in the download for where it is looked for (-Dchilkat2.library.path, a classpath resource, or java.library.path).
Releases the native object (Dkim is AutoCloseable, so try-with-resources calls it). Calling it again does nothing; any other method or property accessor called afterwards throws IllegalStateException. An object that is never closed is freed by a background cleaner once it becomes unreachable, but the garbage collector does not see native memory, so closing is the normal path. Objects returned by methods are owned by the caller too.
Returns true once close() has been called.
Errors
A method that fails throws ChilkatException, an unchecked exception carrying getClassName(), getMethodName(), getReason() (one line, also in the message) and getLastErrorText() (the full log, captured at the moment of the failure). The object remains usable. Methods that look something up and find nothing return null instead of throwing (each such method says so), and methods that answer a question (hasMember, isUnlocked, ...) return a plain boolean. Property accessors do not throw for Chilkat reasons.
A null string or object argument throws NullPointerException naming the parameter (except where a method documents that null is accepted), and a string containing U+0000 throws IllegalArgumentException.
Use an object from one thread at a time; it may be handed from one thread to another. The one cross-thread operation is setting setAbortCurrent(true) on an object that is busy in another thread (on the classes that have AbortCurrent). Unlocking: call new Global().unlockBundle("...") once at startup.
Properties
AbortCurrent
boolean getAbortCurrent()
void setAbortCurrent(boolean value)
Set to true to request cancellation of a currently running operation. A synchronous operation can be cancelled from another thread by setting this property on the same object. Methods that complete quickly or do not periodically check for cancellation may finish before the request is observed.
DebugLogFilePath
String getDebugLogFilePath()
void setDebugLogFilePath(String value)
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.
DkimAlg
String getDkimAlg()
void setDkimAlg(String value)
Specifies the signing algorithm written to the a= tag of a newly created DKIM-Signature header. The default is rsa-sha256.
| Value | Behavior |
|---|---|
rsa-sha256 | RSA signing with a SHA-256 digest. This is the recommended value. |
rsa-sha1 | Legacy RSA signing with a SHA-1 digest. Use only when an older system specifically requires it. |
The value is trimmed and compared case-insensitively. The recognized values are rsa-sha256 and rsa-sha1. An empty or unrecognized value is normalized to rsa-sha256 rather than rejected.
DkimBodyLengthCount
int getDkimBodyLengthCount()
void setDkimBodyLengthCount(int value)
Controls the maximum number of bytes from the canonicalized message body used when computing the DKIM body hash. The default is 0.
| Value | Behavior |
|---|---|
0 | Hashes the complete canonicalized body and omits the DKIM l= tag. |
| Positive and less than the canonicalized body length | Hashes the specified number of bytes and emits l= with that value. |
| Positive and greater than the canonicalized body length | Hashes the complete canonicalized body and emits l= containing the actual canonicalized body length. |
| Negative | -1 hashes the complete canonicalized body and emits l= containing the actual canonicalized body length. |
When a generated signature contains l=, verification hashes only the indicated prefix of the canonicalized body. Content appended after that signed prefix does not invalidate the signature.
0 is normally preferred.DkimCanon
String getDkimCanon()
void setDkimCanon(String value)
Specifies one DKIM canonicalization algorithm to use for both the signed header fields and the message body. The default is relaxed.
| Value | Generated c= value | Behavior |
|---|---|---|
simple | simple/simple | Preserves formatting closely. Small changes in whitespace or header folding can invalidate the signature. |
relaxed | relaxed/relaxed | Normalizes defined whitespace and header-name differences. |
The value is trimmed and compared case-insensitively. This property does not accept a header/body pair such as relaxed/simple or simple/relaxed. Pair values, an empty string, and other unrecognized values are normalized to relaxed rather than rejected.
DkimDomain
String getDkimDomain()
void setDkimDomain(String value)
Specifies the signing domain written verbatim to the d= tag of the generated DKIM-Signature header. The corresponding public key is normally published beneath the DNS name formed from DkimSelector and this domain.
Set this property to a nonempty, syntactically valid domain before calling DkimSign. If this property is empty, DkimSign returns false without modifying the MIME data. A nonempty value is not otherwise validated or normalized during signing; uppercase letters, surrounding whitespace, a trailing dot, and Unicode characters are emitted as supplied.
DkimSign does not check DNS and does not confirm that the configured private key matches the public key published for this domain.d= to equal the visible From domain. DMARC separately evaluates alignment between the authenticated DKIM domain and the message's From domain.DkimHeaders
String getDkimHeaders()
void setDkimHeaders(String value)
A colon-separated list of header field names to include in the DKIM signature. The list is written to the signature's h= tag in the same order. The default is:
mime-version:date:message-id:subject:from:to:content-type
Header-name matching is case-insensitive. For each occurrence of a name in this list, Chilkat selects the next matching header field from the bottom of the message header block upward, as required by DKIM. For example, if the message contains two Subject fields, listing subject once signs the bottommost field, while listing it twice signs both fields.
If a listed occurrence has no corresponding field in the message, the absent field is still included in the signing calculation. Repeating a name more times than it occurs can therefore implement DKIM oversigning and prevent a matching field from being inserted later without invalidating the signature.
- Use colon-separated field names without surrounding spaces.
- Include
from; DKIM requires theFromfield to be signed, butDkimSigndoes not enforce this requirement or add it automatically. - An empty list and names of missing fields are accepted rather than rejected.
- Avoid transport-added or frequently modified fields such as
ReceivedandReturn-Path.
DkimSelector
String getDkimSelector()
void setDkimSelector(String value)
Specifies the selector written verbatim to the s= tag of a generated DKIM signature. The selector and DkimDomain form the DNS name used to locate the public key:
selector._domainkey.signing-domainFor example, selector
brisbane and domain chilkatsoft.com produce brisbane._domainkey.chilkatsoft.com.
Supply only the selector. Do not include ._domainkey. or the signing domain. If this property is empty, DkimSign returns false without modifying the MIME data. A nonempty value is not otherwise validated or normalized during signing; for example, a complete DNS name is emitted as supplied rather than reduced to a selector.
SetDkimPrivateKey must match the public key published for this selector and domain.HeartbeatMs
int getHeartbeatMs()
void setHeartbeatMs(int value)
Specifies the interval, in milliseconds, between AbortCheck callbacks during methods that support periodic cancellation checks. Set to 0 to disable these callbacks. The default is 0.
PrefetchPublicKey invokes AbortCheck while performing its DNS lookup. Setting this property to 1 and requesting cancellation from the first callback causes PrefetchPublicKey to return false.
LastErrorHtml
String getLastErrorHtml()
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
String getLastErrorText()
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
String getLastErrorXml()
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
boolean getLastMethodSuccess()
void setLastMethodSuccess(boolean value)
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.
VerboseLogging
boolean getVerboseLogging()
void setVerboseLogging(boolean value)
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.
VerifyInfo
String getVerifyInfo()
Contains JSON describing the most recent call to DkimVerify. The property is initially an empty string and is replaced or cleared by each verification attempt.
| Member | Meaning |
|---|---|
domain | The signature's d= value. |
selector | The signature's s= value. |
publicKey | The Base64 public-key value obtained from DNS. This member is present when verification performs an automatic DNS lookup and may be absent when a preloaded or prefetched key is used. |
canonicalization | The header/body canonicalization pair from c=. |
algorithm | The signature algorithm from a=. |
signedHeaders | The signed-header list from h=. |
fromSigned | Indicates whether the required From field name is included in the signed-header list. |
expectedBodyHash | The Base64 body hash obtained from the signature's bh= tag. |
computedBodyHash | The Base64 body hash computed from the received message, applying the signature's canonicalization and optional l= body-length limit. |
bodyHashVerified | The string "yes" when the computed body hash matches bh=, or "no" when it does not. |
verified | The string "yes" for a valid signature or "no" for a completed verification that failed. |
{
"domain": "chilkatsoft.com",
"selector": "brisbane",
"canonicalization": "relaxed/relaxed",
"algorithm": "rsa-sha256",
"signedHeaders": "from:to:subject:date:message-id",
"fromSigned": "yes",
"expectedBodyHash": "...",
"computedBodyHash": "...",
"bodyHashVerified": "yes",
"verified": "yes"
}
Not every member is present in every result. For malformed signatures, unsupported algorithms, missing signatures, DNS failures, or an out-of-range index, the value may be an empty string, {}, or a partial object without verified. Therefore, first check the return value of DkimVerify, and then treat individual JSON members as optional.
Version
String getVersion()
Methods
DkimSign
Creates a DKIM-Signature header and prepends it to the complete MIME message stored in mimeData. The BinData is modified in place.
Before calling this method:
- Construct the final MIME message, including all headers, transfer encodings, MIME boundaries, and body bytes.
- Use RFC 5322 line endings. The MIME header and body must use CRLF and be separated by
. LF-only and CR-only MIME are not normalized and cause the method to fail. - Set
DkimDomain,DkimSelector,DkimAlg,DkimCanon, andDkimHeaders. - Load the RSA private key by calling
SetDkimPrivateKey.
On success, the generated header contains v=1, a=, c=, q=dns/txt, d=, s=, h=, bh=, and b=. When DkimBodyLengthCount is nonzero, the header also contains l=. The generated header does not include t=, x=, or i=. Signing the same bytes twice with the same settings and key produced identical output.
An empty body, a body without a final newline, and body data containing NUL or other binary bytes are accepted. An empty DkimDomain, an empty DkimSelector, missing or invalid private-key state, or malformed MIME causes the method to return false without changing mimeData.
DKIM-Signature fields are preserved. Signature indexes therefore follow top-to-bottom order: the newly added signature is index 0, and older signatures shift to higher indexes. Each signature can be verified independently.Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.
DkimVerify
Verifies the DKIM-Signature header at zero-based sigIndex in the complete MIME message stored in mimeData. Signatures are indexed in top-to-bottom header order. Use NumDkimSigs to obtain the count.
Chilkat first looks for a public key cached under the exact selector/domain strings. If no exact match exists, it synchronously retrieves the TXT record at selector._domainkey.domain. The method does not modify mimeData.
| Return value | Meaning |
|---|---|
true | The selected signature was successfully verified, including its body hash and signed headers. |
false | The signature was invalid, or verification could not be completed because of an invalid index, malformed signature, unsupported algorithm, missing key, DNS failure, or another operational error. |
Verification compares the signature's bh= value with the hash computed from the canonicalized body. When the signature contains l=, only the indicated number of canonicalized body bytes are included, so content appended after the signed prefix does not cause a body-hash failure.
After the call, inspect VerifyInfo. A completed verification failure normally contains "verified":"no". A body-hash mismatch also contains "bodyHashVerified":"no" with the expected and computed hashes. Operational and parsing failures may leave an empty string, {}, or a partial JSON object; use LastErrorText for the detailed reason.
Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.
LoadPublicKey
Loads and caches an RSA public key in this Dkim object for the exact selector and domain strings. A later DkimVerify uses the cached key when the signature contains the same selector and domain; otherwise verification falls back to DNS.
publicKey contains a textual key representation. Supported formats include:
- PEM X.509 SubjectPublicKeyInfo (
-----BEGIN PUBLIC KEY-----) - PEM PKCS#1 RSA public key (
-----BEGIN RSA PUBLIC KEY-----) - XML RSA key data
- RSA JWK JSON
The selector/domain cache key is case-sensitive. Loading a key for uppercase values does not satisfy a lowercase signature. A successful later load for the same pair replaces the earlier key. If a later load fails because the supplied key text is invalid, the previously cached key remains available.
Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.
LoadPublicKeyFile
Loads an RSA public key from the local file at publicKeyFilepath and caches it in this Dkim object for the exact selector and domain strings. The file is read during this call.
Supported formats include PEM X.509 SubjectPublicKeyInfo, PEM PKCS#1 RSA public key, binary DER PKCS#1 RSA public key, XML RSA key data, and RSA JWK JSON. The selector/domain cache key is case-sensitive.
A later successful load for the same selector/domain pair replaces the earlier cached key. If no exact cached key is present when DkimVerify runs, Chilkat performs its normal DNS lookup.
publicKeyFilepath is a path in the local filesystem. Load only keys from a trusted source because the cached key determines which signatures are accepted for that selector and domain.Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.
NumDkimSigs
Returns the number of header fields named DKIM-Signature in mimeData. Header-name matching is case-insensitive. The method counts matching fields without validating the signature syntax; for example, a malformed DKIM-Signature: nonsense field is still counted.
The indexes used by DkimVerify are zero-based and follow top-to-bottom header order. The method returns 0 when no matching header is found, including for an empty message. It does not modify mimeData.
PrefetchPublicKey
Retrieves the DKIM public key from DNS and caches it in this Dkim object for the exact selector and domain strings. The TXT lookup is made for:
selector._domainkey.domain
The method returns true when the DNS lookup and public-key loading succeed. Repeated calls for a cached pair can complete without another observable lookup. A successful prefetch replaces an existing manually loaded key for the same selector/domain pair.
DkimVerify also performs this DNS lookup automatically when no exact cached key is available. Prefetching is useful when several messages will be verified for the same selector and domain.
AbortCheck callbacks according to HeartbeatMs. When the callback requests cancellation, the method returns false and the DNS lookup is aborted.Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.
SetDkimPrivateKey
Copies the RSA key from privateKey into this object for subsequent calls to DkimSign. The source PrivateKey object may be destroyed after this method returns successfully, and the configured key can be reused for multiple signatures.
A later successful call replaces the previously configured signing key. A failed call with an empty or unrecognized key clears the usable signing-key state; a subsequent DkimSign fails until a valid key is set again.
selector._domainkey.domain, using DkimSelector and DkimDomain. This method does not check DNS or confirm the match.Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) 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, Dkim reports progress through a ProgressListener, an interface with three methods, each with a default, so you override only what you need:
import com.chilkatsoft.chilkat2.ProgressListener;
dkim.setProgressListener(new ProgressListener() {
@Override public boolean percentDone(int pctDone) {
System.out.println(pctDone + "%");
return false; // return true to abort the method in progress
}
@Override public void progressInfo(String name, String value) {
System.out.println(name + ": " + value);
}
});
dkim.setHeartbeatMs(250); // abortCheck 4 times per secondFor a single callback, a lambda is shorter:
dkim.onPercentDone(pct -> { System.out.println(pct + "%"); return false; });Installs listener as the receiver of this object's events, replacing any listener or lambda installed before; null removes it.
Returns the installed listener, or null.
Each installs a listener whose only callback is the given lambda (from java.util.function). Like setProgressListener, each replaces the listener installed before, so to handle more than one event, implement ProgressListener. null removes the listener.
abortCheck 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. Returning true from abortCheck or percentDone aborts the running method, which then throws ChilkatException.
Callbacks run on the thread that called the method, before it returns. Inside a callback, property accessors of the object (such as setAbortCurrent(true)) and other objects may be used, but calling a method of the same object throws IllegalStateException. An exception thrown by a callback aborts the running method and is rethrown from it; the object remains usable.
AbortCheck
boolean abortCheck()
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
import java.util.concurrent.atomic.AtomicBoolean;
final AtomicBoolean stop = new AtomicBoolean(false); // another thread may call stop.set(true)
dkim.setHeartbeatMs(250); // call abortCheck 4 times per second
dkim.onAbortCheck(() -> stop.get());PercentDone
boolean percentDone(int pctDone)
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
dkim.onPercentDone(pct -> {
// pct ranges from 0 to 100.
System.out.println("Percent done: " + pct);
return false; // return true to abort the method in progress
});ProgressInfo
void progressInfo(String name, String value)
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
dkim.onProgressInfo((name, value) -> System.out.println(name + ": " + value));