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

Sign a saved MIME message with DKIM

See more DKIM Examples

Sign the complete bytes of message.eml and save the result as signed.eml. Finish the message’s From, To, Date, Message-ID, MIME parts and transfer encodings before signing. Existing signatures stay in place and the new signature is inserted first.

The example signs the full body and includes From in the signed headers. Relaxed canonicalization tolerates defined whitespace and header folding changes. Editing a signed field or changing the body text can still break verification. Prepare the matching DNS record.

Chilkat Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oMessage
LOCAL oPrivateKey
LOCAL oSigner

nSuccess := 0

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

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

//  Supply your RSA signing key. For an encrypted PEM, get its password from your credential store.
oPrivateKey := CreateObject("Chilkat.PrivateKey")
nSuccess := oPrivateKey:LoadAnyFormatFile("dkim-private.pem", "")
IF (nSuccess != 1)
    ? oPrivateKey:LastErrorText
    oMessage:destroy()
    oPrivateKey:destroy()
    RETURN
ENDIF

oSigner := CreateObject("Chilkat.Dkim")
oSigner:DkimDomain := "example.com"
oSigner:DkimSelector := "mail2026"
oSigner:DkimAlg := "rsa-sha256"
nSuccess := oSigner:SetDkimPrivateKey(oPrivateKey)
IF (nSuccess != 1)
    ? oSigner:LastErrorText
    oMessage:destroy()
    oPrivateKey:destroy()
    oSigner:destroy()
    RETURN
ENDIF

//  DkimCanon takes a single setting and applies it to both headers and body.
oSigner:DkimCanon := "relaxed"
oSigner:DkimHeaders := "from:to:subject:date:message-id:mime-version:content-type:content-transfer-encoding"
//  Zero signs the entire canonicalized body and omits the optional l= tag.
oSigner:DkimBodyLengthCount := 0
nSuccess := oSigner:DkimSign(oMessage)
IF (nSuccess != 1)
    ? oSigner:LastErrorText
    oMessage:destroy()
    oPrivateKey:destroy()
    oSigner:destroy()
    RETURN
ENDIF

nSuccess := oMessage:WriteFile("signed.eml")
IF (nSuccess != 1)
    ? "Could not write signed.eml."
    oMessage:destroy()
    oPrivateKey:destroy()
    oSigner:destroy()
    RETURN
ENDIF

? "Saved signed.eml."

oMessage:destroy()
oPrivateKey:destroy()
oSigner:destroy()