Sample code for 30+ languages & platforms
Lianja

Verify DKIM Signatures in a Message

See more DKIM / DomainKey Examples

Demonstrates the Chilkat Dkim.DkimVerify method, which verifies the DKIM-Signature at a given zero-based index in a MIME message. The arguments are the signature index and a BinData holding the complete MIME. This example loops over every signature and reads the JSON VerifyInfo after each.

Tip: JSON parsing code for the VerifyInfo result can be generated at Chilkat Tools.

Note: The file paths are relative to the application's current working directory. Absolute paths may also be used. Supply the paths appropriate to your own environment.

Background: Verifying confirms two things at once: that the message was signed by the claimed domain, and that the signed headers and body have not been altered since. Chilkat uses a cached public key when the selector and domain match one you loaded, and otherwise fetches it from DNS. The message is not modified. After each call, the VerifyInfo JSON records the details — selector, domain, and outcome — which is what you would log or surface when a signature fails. Verification is per-signature, so a message with several signatures may have some pass and others fail.

Chilkat Lianja Downloads

Lianja
llSuccess = .F.

//  Demonstrates the Dkim.DkimVerify method, which verifies the DKIM-Signature at a given index in
//  a MIME message.  The 1st argument is the zero-based signature index and the 2nd is a BinData
//  holding the complete MIME.

loDkim = createobject("CkDkim")

//  Load the received MIME message.
loMimeData = createobject("CkBinData")
llSuccess = loMimeData.LoadFile("qa_data/received.eml")
if (llSuccess = .F.) then
    ? loMimeData.LastErrorText
    release loDkim
    release loMimeData
    return
endif

//  A message may carry more than one DKIM signature.  Verify each in turn.  Signatures are
//  indexed in top-to-bottom header order.
lnNumSigs = loDkim.NumDkimSigs(loMimeData)

for i = 0 to lnNumSigs - 1
    //  DkimVerify uses a cached public key when one matches the signature's selector and domain;
    //  otherwise it retrieves the key from DNS.
    llSuccess = loDkim.DkimVerify(i,loMimeData)
    if (llSuccess = .T.) then
        ? "Signature " + str(i) + ": verified."
    else
        ? "Signature " + str(i) + ": verification failed."
    endif

    //  VerifyInfo contains JSON describing the most recent DkimVerify call (selector, domain,
    //  result, and so on).
    ? loDkim.VerifyInfo
    //  JSON parsing code for this result can be generated at Chilkat's online tool:
    //  https://tools.chilkat.io/jsonParse
next


release loDkim
release loMimeData