Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

DKIM: signing email with a domain key

After this lesson: I can sign an email with DKIM and check its signature against the key in DNS.

75 min lesson15 commandsDHCP and DNS lab: configure dnsmasq for a small network in your browser

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

A seal proving where an email came from

DomainKeys Identified Mail (DKIM) adds a digital signature to an email. The sending domain signs some headers and the body, and publishes the key to check it in DNS.

It matters because SPF breaks when a message is forwarded. A signature travels with the message, so it can still be checked after any number of servers.

By the end of this lesson

Note

I can sign an email with DKIM and check its signature against the key in DNS.

Key words

WordWhat it meansExample
Signaturea value only the private key can make and the public key can check
Selectorthe name that says which of a domain's keys signeds1
Body hasha short fingerprint of the message bodybh=
Canonicalisationtidying text the same way on both sides before hashing
DKIM-Signaturethe header that carries the signature and its tags

The cells students fill in are left blank in this preview.

Starter

Have a go

Starter

4 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

How a DKIM signature works

The sending server hashes the body into a body hash. It then signs the chosen headers plus its own DKIM-Signature header with a private key.

The receiver reads d= (the domain) and s= (the selector), and asks DNS for the TXT record at s1._domainkey.example.test. The public key there checks the signature.

Worked example: the tags of a DKIM-Signature

TagExampleMeaning
a=rsa-sha256The algorithm: RSA with SHA-256
c=relaxed/relaxedHow headers and body are tidied
d=example.testThe domain that signs
s=s1The selector: the key is at s1._domainkey.example.test
h=from:to:subject:date:message-idThe headers covered
bh=, b=base64 textThe body hash and the signature

The cells students fill in are left blank in this preview.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Write the message to sign

Command
mkdir -p mail && printf '%s\n' 'From: Exams Office <[email protected]>' 'To: Sam Lee <[email protected]>' 'Subject: Your exam timetable' 'Date: Mon, 16 Nov 2026 09:00:00 +0000' 'Message-ID: <[email protected]>' '' 'Your exam timetable is ready.' 'Room 4, Tuesday at 10:00.' > mail/msg.eml

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Make a 2048-bit RSA key

Command
openssl genpkey -quiet -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out mail/dkim.key

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Put the public key in the zone

Command
printf 'txt-record=s1._domainkey.example.test,"v=DKIM1; k=rsa; p=%s"\n' "$(openssl pkey -in mail/dkim.key -pubout -outform DER | base64 -w0)" > mail/dkim.conf

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Start a practice DNS server

Command
sudo dnsmasq --conf-file=$HOME/mail/dkim.conf --no-hosts --no-resolv --port=5302 --listen-address=127.0.0.1 --bind-interfaces --local=/test/ --local=/example.com/

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Ask DNS for the key

Command
dig +short @127.0.0.1 -p 5302 s1._domainkey.example.test TXT

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Both sides tidy the text the same way

Servers on the way may change spaces or fold a long header onto two lines. With relaxed canonicalisation, both sides lower-case header names, squeeze runs of spaces into one and drop blank lines at the end.

So harmless changes keep the signature valid. Any change of a word does not.

Write the signer and checker, part 1

Command
mkdir -p mail && printf '%s\n' 'import base64' 'import hashlib' 'import subprocess' 'import sys' '' 'CRLF = chr(13) + chr(10)' 'SIGNED = ["from", "to", "subject", "date", "message-id"]' '' '' 'def split(text):' '    head, gap, body = text.partition(chr(10) + chr(10))' '    headers = []' '    for line in head.split(chr(10)):' '        if line[:1] in [" ", chr(9)] and headers:' '            headers[-1][1] = headers[-1][1] + CRLF + line' '        else:' '            name, colon, value = line.partition(":")' '            headers.append([name, value])' '    return headers, body' '' '' 'def canon_header(name, value):' '    return name.strip().lower() + ":" + " ".join(value.split())' '' '' 'def canon_body(body):' '    lines = []' '    for line in body.split(chr(10)):' '        line = line.replace(chr(9), " ")' '        while "  " in line:' '            line = line.replace("  ", " ")' '        lines.append(line.rstrip(" "))' '    while lines and lines[-1] == "":' > mail/dkim.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the signer and checker, part 2

Command
printf '%s\n' '        lines.pop()' '    if not lines:' '        return ""' '    return CRLF.join(lines) + CRLF' '' '' 'def body_hash(body):' '    return base64.b64encode(hashlib.sha256(canon_body(body).encode()).digest()).decode()' '' '' 'def tags(value):' '    found = {}' '    for part in value.split(";"):' '        name, eq, text = part.partition("=")' '        if eq:' '            found[name.strip()] = "".join(text.split())' '    return found' '' '' 'def signed_data(headers, names, sig_value):' '    data = ""' '    for want in names:' '        for name, value in headers:' '            if name.strip().lower() == want:' '                data = data + canon_header(name, value) + CRLF' '                break' '    parts = []' '    for part in sig_value.split(";"):' '        if part.strip().startswith("b="):' '            part = part[:part.index("b=") + 2]' '        parts.append(part)' '    return data + canon_header("DKIM-Signature", ";".join(parts))' '' '' >> mail/dkim.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the signer and checker, part 3

Command
printf '%s\n' 'def openssl(args, data):' '    return subprocess.run(["openssl"] + args, input=data, capture_output=True)' '' '' 'def sign(path):' '    text = open(path).read()' '    headers, body = split(text)' '    value = (" v=1; a=rsa-sha256; c=relaxed/relaxed; d=example.test; s=s1; h="' '             + ":".join(SIGNED) + "; bh=" + body_hash(body) + "; b=")' '    data = signed_data(headers, SIGNED, value)' '    sig = openssl(["dgst", "-sha256", "-sign", "mail/dkim.key"], data.encode()).stdout' '    out = "DKIM-Signature:" + value + base64.b64encode(sig).decode() + chr(10) + text' '    open("mail/signed.eml", "w").write(out)' '    print("mail/signed.eml: bh=" + body_hash(body))' '' '' 'def key_text(selector, domain):' '    out = subprocess.run(["dig", "+short", "@127.0.0.1", "-p", "5302",' '                          selector + "._domainkey." + domain, "TXT"], capture_output=True, text=True).stdout' '    return "".join(out.split(chr(34))[1::2])' '' '' >> mail/dkim.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the signer and checker, part 4

Command
printf '%s\n' 'def verify(path):' '    headers, body = split(open(path).read())' '    value = ""' '    for name, text in headers:' '        if name.lower() == "dkim-signature":' '            value = text' '    sig = tags(value)' '    if not body_hash(body) == sig["bh"]:' '        return "dkim=fail (body hash)"' '    key = tags(key_text(sig["s"], sig["d"])).get("p", "")' '    if not key:' '        return "dkim=fail (no key at " + sig["s"] + "._domainkey." + sig["d"] + ")"' '    pem = "-----BEGIN PUBLIC KEY-----" + chr(10)' '    for at in range(0, len(key), 64):' '        pem = pem + key[at:at + 64] + chr(10)' '    open("mail/key.pem", "w").write(pem + "-----END PUBLIC KEY-----" + chr(10))' '    open("mail/sig.bin", "wb").write(base64.b64decode(sig["b"]))' '    data = signed_data(headers, sig["h"].split(":"), value)' '    ok = openssl(["dgst", "-sha256", "-verify", "mail/key.pem", "-signature", "mail/sig.bin"], data.encode())' '    if ok.returncode:' >> mail/dkim.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the signer and checker, part 5

Command
printf '%s\n' '        return "dkim=fail (signature)"' '    return "dkim=pass d=" + sig["d"] + " s=" + sig["s"]' '' '' 'if sys.argv[1] == "sign":' '    sign(sys.argv[2])' 'else:' '    print(verify(sys.argv[2]))' >> mail/dkim.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Sign the message

Command
python3 mail/dkim.py sign mail/msg.eml

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Check the signature

Command
python3 mail/dkim.py verify mail/signed.eml

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Change one word on the way

Command
sed -i 's/Room 4/Room 9/' mail/signed.eml

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Check the changed message

Command
python3 mail/dkim.py verify mail/signed.eml

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

What the Runs printed

RunPrintedWhy
digv=DKIM1; k=rsa; p=MIIB..., in two quoted partsOne TXT string holds at most 255 characters
signmail/signed.eml: bh=tom8kaEgkfrWdpf1CQcbYHZ/yW4uR7zqpvbmua60F/w=The same body gives the same hash in every copy
verifydkim=pass d=example.test s=s1The key in DNS checked the signature
verify after the changedkim=fail (body hash)"Room 9" gives a different hash

The cells students fill in are left blank in this preview.

Check the Run

Have a go

Check the Run

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

A common mistake

Warning

Many people think a DKIM pass means the sender is who the From line says. It proves only that the domain in d= signed it. A forger can sign with their own domain, so lesson 3 checks that d= matches the From line.

Try it: tidy a header

Code: python
# Relaxed canonicalisation of one header, as DKIM does before hashing.
def relaxed_header(name, value):
    # Lower-case name, no space round the colon, runs of spaces made one.
    return name.strip().lower() + ":" + " ".join(value.split())

print(relaxed_header("Subject", "  Your   exam timetable "))
print(relaxed_header("SUBJECT", "Your exam\ttimetable"))
# Both lines print the same, so both give the same hash.
# Change "exam" to "Exam" in one of them, then press Run.

Make a free account to save your work and track your progress.

Stop the practice server

Command
sudo pkill -f '[-]-port=5302'

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Assignment: tags and the body hash

Write three parts of a DKIM checker.

tags(value) splits a DKIM-Signature or key record on ; and returns a dictionary from each tag name to its value, with every space and new line taken out of the value. A value may itself contain =.

relaxed_body(body) takes a body whose lines end in \n and returns it canonicalised the relaxed way: tabs become spaces, runs of spaces become one, spaces at a line end go, blank lines at the end go, and every line ends in \r\n. A body with nothing left is "".

body_hash(body) returns the base64 of the SHA-256 of the relaxed body. The lab's message must give the lab's bh=.

Code: python
import base64
import hashlib


def tags(value):
    return {}


def relaxed_body(body):
    return body


def body_hash(body):
    return ""

Make a free account to save your work and track your progress.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.