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

Java
import com.chilkatsoft.chilkat2.BinData;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Dkim;
import com.chilkatsoft.chilkat2.PrivateKey;

public class ChilkatExample {

    public static void main(String[] args) {
        // Assumes Chilkat is unlocked. See Global Unlock Sample.

        BinData message = new BinData();
        try {
            message.loadFile("message.eml");
        } catch (ChilkatException e) {
            System.out.println("Could not read message.eml.");
            return;
        }

        // Supply your RSA signing key. For an encrypted PEM, get its password from your credential store.
        PrivateKey privateKey = new PrivateKey();
        try {
            privateKey.loadAnyFormatFile("dkim-private.pem", "");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        Dkim signer = new Dkim();
        signer.setDkimDomain("example.com");
        signer.setDkimSelector("mail2026");
        signer.setDkimAlg("rsa-sha256");
        try {
            signer.setDkimPrivateKey(privateKey);

            // DkimCanon takes a single setting and applies it to both headers and body.
            signer.setDkimCanon("relaxed");
            signer.setDkimHeaders("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.
            signer.setDkimBodyLengthCount(0);
            signer.dkimSign(message);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        try {
            message.writeFile("signed.eml");
        } catch (ChilkatException e) {
            System.out.println("Could not write signed.eml.");
            return;
        }

        System.out.println("Saved signed.eml.");
    }
}