Skip to content
KALANBLON
Show contents

Chapter 5 of 6 · 25 min

Project: an encrypted messaging app

By the end of this chapter, you'll be able to

  • Derive several independent keys from a shared secret with HKDF
  • Build an encrypted then authenticated packet, with a counter as the nonce
  • Reject a modified or replayed packet before decrypting it
  • Separate the keys of the two directions of communication

The plan of the messaging app

The recipient rejects any modified packet, then any packet already seen, and only then decrypts.

Step 5 of 5
Text description of the animation
  1. Awa and Kofi have made an authenticated Diffie-Hellman exchange.
  2. A key is never reused for two purposes: we derive two.
  3. The counter increases with every message: it is a unique nonce, with no randomness to manage.
  4. The tag covers the counter AND the ciphertext: neither can be modified.
  5. The recipient rejects any modified packet, then any packet already seen, and only then decrypts.

Step 1: deriving keys with HKDF

HKDF (RFC 5869) turns a shared secret into as many keys as needed. It has two phases, both made of HMAC: extract concentrates the secret into a uniform key, expand draws bytes from it for each purpose, told apart by an info label.

import hashlib
import hmac

def hkdf(secret, info, length=32, salt=b""):
    """HKDF-SHA256 (RFC 5869): extract then expand."""
    prk = hmac.new(salt or bytes(32), secret, hashlib.sha256).digest()      # extract
    output, block, i = b"", b"", 1
    while len(output) < length:                                             # expand
        block = hmac.new(prk, block + info + bytes([i]), hashlib.sha256).digest()
        output += block
        i += 1
    return output[:length]

secret = (123456789).to_bytes(16, "big")       # for real: the Diffie-Hellman secret
enc_key = hkdf(secret, b"cooperative encryption")
mac_key = hkdf(secret, b"cooperative authentication")
print(enc_key.hex()[:32])
print(mac_key.hex()[:32])
print("different keys:", enc_key != mac_key)
9600eac59635fe10b27a97fafb9108f0
e52956f2ae9b21db81ed5f2db02e529c
different keys: True

Two different info labels give two unrelated keys: if one leaks, the other stays safe.

Step 2: sending and receiving

import hashlib
import hmac

def hkdf(secret, info, length=32):
    prk = hmac.new(bytes(32), secret, hashlib.sha256).digest()
    output, block, i = b"", b"", 1
    while len(output) < length:
        block = hmac.new(prk, block + info + bytes([i]), hashlib.sha256).digest()
        output += block
        i += 1
    return output[:length]

def keystream(key, nonce, n):
    s, i = b"", 0
    while len(s) < n:
        s += hashlib.sha256(key + nonce + i.to_bytes(8, "big")).digest()
        i += 1
    return s[:n]

class Channel:
    def __init__(self, secret):
        self.enc_key = hkdf(secret, b"encryption")
        self.mac_key = hkdf(secret, b"authentication")
        self.sent = 0              # send counter
        self.last_received = 0     # highest counter accepted

    def send(self, text):
        self.sent += 1
        nonce = self.sent.to_bytes(8, "big")
        data = text.encode()
        encrypted = bytes(d ^ s for d, s in zip(data, keystream(self.enc_key, nonce, len(data))))
        tag = hmac.new(self.mac_key, nonce + encrypted, hashlib.sha256).digest()
        return {"nonce": nonce, "encrypted": encrypted, "tag": tag}

    def receive(self, packet):
        expected = hmac.new(self.mac_key, packet["nonce"] + packet["encrypted"], hashlib.sha256).digest()
        if not hmac.compare_digest(expected, packet["tag"]):
            return "REJECTED: packet modified"
        counter = int.from_bytes(packet["nonce"], "big")
        if counter <= self.last_received:
            return "REJECTED: packet replayed"
        self.last_received = counter
        s = keystream(self.enc_key, packet["nonce"], len(packet["encrypted"]))
        return bytes(c ^ x for c, x in zip(packet["encrypted"], s)).decode()

secret = (987654321).to_bytes(16, "big")
awa, kofi = Channel(secret), Channel(secret)

p1 = awa.send("price accepted: 1,650 F CFA per kilo")
p2 = awa.send("delivery of 2 tonnes on Thursday")
modified = dict(p2, encrypted=bytes([p2["encrypted"][0] ^ 1]) + p2["encrypted"][1:])

print(kofi.receive(p1))
print(kofi.receive(modified))
print(kofi.receive(p2))
print(kofi.receive(p2))          # a spy resends the same packet
price accepted: 1,650 F CFA per kilo
REJECTED: packet modified
delivery of 2 tonnes on Thursday
REJECTED: packet replayed

The order of the checks matters: the tag first (we trust nothing that is not authenticated, not even the counter), the counter next, decryption last.

Mini-lab: attack the messaging appPython 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Project: a two-way conversation

Modify the Channel class so that it takes a parameter me ("awa" or "kofi") and derives four keys: encryption and HMAC for sending, encryption and HMAC for receiving. Awa's sending keys must be Kofi's receiving keys, and vice versa. Test a conversation: Awa sends two messages, Kofi replies with one message, then a spy replays Kofi's reply.

Hint 1
Build the labels from the two names: for Awa, sending uses b"awa->kofi" and receiving b"kofi->awa". For Kofi, it is the reverse.
Hint 2
hkdf(secret, direction + b" encryption") and hkdf(secret, direction + b" hmac") give the two keys of one direction.
Show the solution and common mistakes
import hashlib
import hmac

def hkdf(secret, info, length=32):
    prk = hmac.new(bytes(32), secret, hashlib.sha256).digest()
    output, block, i = b"", b"", 1
    while len(output) < length:
        block = hmac.new(prk, block + info + bytes([i]), hashlib.sha256).digest()
        output += block
        i += 1
    return output[:length]

def keystream(key, nonce, n):
    s, i = b"", 0
    while len(s) < n:
        s += hashlib.sha256(key + nonce + i.to_bytes(8, "big")).digest()
        i += 1
    return s[:n]

class Channel:
    def __init__(self, secret, me):
        other = "kofi" if me == "awa" else "awa"
        out, inc = f"{me}->{other}".encode(), f"{other}->{me}".encode()
        self.sending = (hkdf(secret, out + b" encryption"), hkdf(secret, out + b" hmac"))
        self.receiving = (hkdf(secret, inc + b" encryption"), hkdf(secret, inc + b" hmac"))
        self.sent, self.last_received = 0, 0

    def send(self, text):
        k_e, k_m = self.sending
        self.sent += 1
        nonce, data = self.sent.to_bytes(8, "big"), text.encode()
        encrypted = bytes(d ^ s for d, s in zip(data, keystream(k_e, nonce, len(data))))
        return {"nonce": nonce, "encrypted": encrypted, "tag": hmac.new(k_m, nonce + encrypted, hashlib.sha256).digest()}

    def receive(self, p):
        k_e, k_m = self.receiving
        if not hmac.compare_digest(hmac.new(k_m, p["nonce"] + p["encrypted"], hashlib.sha256).digest(), p["tag"]):
            return "REJECTED: packet modified"
        counter = int.from_bytes(p["nonce"], "big")
        if counter <= self.last_received:
            return "REJECTED: packet replayed"
        self.last_received = counter
        return bytes(c ^ s for c, s in zip(p["encrypted"], keystream(k_e, p["nonce"], len(p["encrypted"])))).decode()

secret = (987654321).to_bytes(16, "big")
awa, kofi = Channel(secret, "awa"), Channel(secret, "kofi")

print("Kofi reads:", kofi.receive(awa.send("buyer confirmed for Thursday")))
print("Kofi reads:", kofi.receive(awa.send("final price 1,650 F CFA")))
reply = kofi.send("perfect, I am preparing the bags")
print("Awa reads :", awa.receive(reply))
print("Awa reads :", awa.receive(reply))
print("same key in both directions?", awa.sending[0] == kofi.sending[0])
Kofi reads: buyer confirmed for Thursday
Kofi reads: final price 1,650 F CFA
Awa reads : perfect, I am preparing the bags
Awa reads : REJECTED: packet replayed
same key in both directions? False

Awa's sending keys are exactly Kofi's receiving keys, but never the ones Kofi uses to send. Each direction has its own counter, its own key, and therefore its own nonces.

Common mistakes:

  • Using the same order of names on both sides ("awa->kofi" everywhere): the two directions share the same keys again.
  • Updating last_received before checking the tag: a spy can then send a fake packet with a huge counter and block all following messages.
  • Accepting packets out of order without a window: on a real network, slight reordering must be tolerated, which complicates replay protection.

Summary

  1. 1HKDF derives from a shared secret as many independent keys as there are purposes.
  2. 2A safe packet contains a unique nonce, the ciphertext and an HMAC tag covering both.
  3. 3On receipt: check the tag, then the counter, and only then decrypt.
  4. 4Each direction of the conversation has its own keys, otherwise the nonces repeat.
  5. 5In production, you do not assemble these blocks yourself: you use TLS or the Signal protocol.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.