Sample code for 30+ languages & platforms
PowerBuilder 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 PowerBuilder Downloads

PowerBuilder
integer li_rc
long li_Success
oleobject loo_Message
oleobject loo_PrivateKey
oleobject loo_Signer

li_Success = 0

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

loo_Message = create oleobject
li_rc = loo_Message.ConnectToNewObject("Chilkat.BinData")
if li_rc < 0 then
    destroy loo_Message
    MessageBox("Error","Connecting to COM object failed")
    return
end if
li_Success = loo_Message.LoadFile("message.eml")
if li_Success <> 1 then
    Write-Debug "Could not read message.eml."
    destroy loo_Message
    return
end if

//  Supply your RSA signing key. For an encrypted PEM, get its password from your credential store.
loo_PrivateKey = create oleobject
li_rc = loo_PrivateKey.ConnectToNewObject("Chilkat.PrivateKey")

li_Success = loo_PrivateKey.LoadAnyFormatFile("dkim-private.pem","")
if li_Success <> 1 then
    Write-Debug loo_PrivateKey.LastErrorText
    destroy loo_Message
    destroy loo_PrivateKey
    return
end if

loo_Signer = create oleobject
li_rc = loo_Signer.ConnectToNewObject("Chilkat.Dkim")

loo_Signer.DkimDomain = "example.com"
loo_Signer.DkimSelector = "mail2026"
loo_Signer.DkimAlg = "rsa-sha256"
li_Success = loo_Signer.SetDkimPrivateKey(loo_PrivateKey)
if li_Success <> 1 then
    Write-Debug loo_Signer.LastErrorText
    destroy loo_Message
    destroy loo_PrivateKey
    destroy loo_Signer
    return
end if

//  DkimCanon takes a single setting and applies it to both headers and body.
loo_Signer.DkimCanon = "relaxed"
loo_Signer.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.
loo_Signer.DkimBodyLengthCount = 0
li_Success = loo_Signer.DkimSign(loo_Message)
if li_Success <> 1 then
    Write-Debug loo_Signer.LastErrorText
    destroy loo_Message
    destroy loo_PrivateKey
    destroy loo_Signer
    return
end if

li_Success = loo_Message.WriteFile("signed.eml")
if li_Success <> 1 then
    Write-Debug "Could not write signed.eml."
    destroy loo_Message
    destroy loo_PrivateKey
    destroy loo_Signer
    return
end if

Write-Debug "Saved signed.eml."


destroy loo_Message
destroy loo_PrivateKey
destroy loo_Signer