Sample code for 30+ languages & platforms
Xbase++ Requires Chilkat v11.0.0+

Verify DKIM using a public key supplied as text

See more DKIM Examples

Applications that keep public keys in configuration can pass a complete PEM string or the base64 value of the DNS p= tag to LoadPublicKey. This example reads a trusted PEM as text so it can be run alongside the file-based example. Supply just the key material when passing a base64 value. Reuse the same verifier for signatures with that exact domain and selector.

Chilkat Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oMessage
LOCAL oVerifier
LOCAL cDomain
LOCAL cSelector
LOCAL oKeyText
LOCAL oInfo

nSuccess := 0

//  Assumes Chilkat is unlocked. See Global Unlock Sample.

oMessage := CreateObject("Chilkat.BinData")
nSuccess := oMessage:LoadFile("signed.eml")
IF (nSuccess != 1)
    ? "Could not read signed.eml."
    oMessage:destroy()
    RETURN
ENDIF

oVerifier := CreateObject("Chilkat.Dkim")
cDomain := "example.com"
cSelector := "mail2026"
oKeyText := CreateObject("Chilkat.StringBuilder")
nSuccess := oKeyText:LoadFile("dkim-public.pem", "utf-8")
IF (nSuccess != 1)
    ? "Could not read the trusted public PEM."
    oMessage:destroy()
    oVerifier:destroy()
    oKeyText:destroy()
    RETURN
ENDIF

nSuccess := oVerifier:LoadPublicKey(cSelector, cDomain, oKeyText:GetAsString())
IF (nSuccess != 1)
    ? oVerifier:LastErrorText
    oMessage:destroy()
    oVerifier:destroy()
    oKeyText:destroy()
    RETURN
ENDIF

//  signed.eml from the signing example has our newly added signature at index zero.
IF (oVerifier:NumDkimSigs(oMessage) == 0)
    ? "No DKIM signature in signed.eml."
    oMessage:destroy()
    oVerifier:destroy()
    oKeyText:destroy()
    RETURN
ENDIF

nSuccess := oVerifier:DkimVerify(0, oMessage)
IF (nSuccess != 1)
    ? oVerifier:LastErrorText
    ? oVerifier:VerifyInfo
    oMessage:destroy()
    oVerifier:destroy()
    oKeyText:destroy()
    RETURN
ENDIF

oInfo := CreateObject("Chilkat.JsonObject")
nSuccess := oInfo:Load(oVerifier:VerifyInfo)
IF ((nSuccess != 1) .OR. (oInfo:StringOfEquals("domain", cDomain, 1) != 1) .OR. (oInfo:StringOfEquals("selector", cSelector, 1) != 1))
    ? "The first signature is not from the selected domain and selector."
    oMessage:destroy()
    oVerifier:destroy()
    oKeyText:destroy()
    oInfo:destroy()
    RETURN
ENDIF

? "The configured public key verifies this message."

oMessage:destroy()
oVerifier:destroy()
oKeyText:destroy()
oInfo:destroy()