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
| Word | What it means | Example |
|---|---|---|
| Signature | a value only the private key can make and the public key can check | |
| Selector | the name that says which of a domain's keys signed | s1 |
| Body hash | a short fingerprint of the message body | bh= |
| Canonicalisation | tidying text the same way on both sides before hashing | |
| DKIM-Signature | the 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 questionsHow 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
| Tag | Example | Meaning |
|---|---|---|
| a= | rsa-sha256 | The algorithm: RSA with SHA-256 |
| c= | relaxed/relaxed | How headers and body are tidied |
| d= | example.test | The domain that signs |
| s= | s1 | The selector: the key is at s1._domainkey.example.test |
| h= | from:to:subject:date:message-id | The headers covered |
| bh=, b= | base64 text | The body hash and the signature |
The cells students fill in are left blank in this preview.
Check
Have a go
Check
3 questionsWrite the message to sign
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.emlShown here, not run. Press Start lab to type it into your own lab’s terminal.
Make a 2048-bit RSA key
openssl genpkey -quiet -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out mail/dkim.keyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Put the public key in the zone
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.confShown here, not run. Press Start lab to type it into your own lab’s terminal.
Start a practice DNS server
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
dig +short @127.0.0.1 -p 5302 s1._domainkey.example.test TXTShown 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
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.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the signer and checker, part 2
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.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the signer and checker, part 3
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.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the signer and checker, part 4
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.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the signer and checker, part 5
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.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Sign the message
python3 mail/dkim.py sign mail/msg.emlShown here, not run. Press Start lab to type it into your own lab’s terminal.
Check the signature
python3 mail/dkim.py verify mail/signed.emlShown here, not run. Press Start lab to type it into your own lab’s terminal.
Change one word on the way
sed -i 's/Room 4/Room 9/' mail/signed.emlShown here, not run. Press Start lab to type it into your own lab’s terminal.
Check the changed message
python3 mail/dkim.py verify mail/signed.emlShown here, not run. Press Start lab to type it into your own lab’s terminal.
What the Runs printed
| Run | Printed | Why |
|---|---|---|
| dig | v=DKIM1; k=rsa; p=MIIB..., in two quoted parts | One TXT string holds at most 255 characters |
| sign | mail/signed.eml: bh=tom8kaEgkfrWdpf1CQcbYHZ/yW4uR7zqpvbmua60F/w= | The same body gives the same hash in every copy |
| verify | dkim=pass d=example.test s=s1 | The key in DNS checked the signature |
| verify after the change | dkim=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 questionsA 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
# 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
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=.
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