Skip to content
KALANBLON
Show contents

Chapter 4 of 6 · 20 min

Digital signatures and certificates

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

  • Sign a document with an RSA private key and verify the signature with the public key
  • Explain why we sign the document's fingerprint and not the whole document
  • Describe the content of a certificate and the chain of trust
  • Check that a certificate really matches the site visited

Signing: the private key "encrypts" the fingerprint

With RSA, the roles of the keys can be swapped: the author computes s = H(m)^d mod n with the private key; anyone checks that s^e mod n gives back H(m) with the public key. H(m) is the document's SHA-256 fingerprint: we sign the fingerprint, small and of fixed size, not the whole document.

import hashlib

# Demonstration key: two well-known Mersenne primes (so NOT secret!).
p, q = 2**521 - 1, 2**607 - 1
n, e = p * q, 65537
d = pow(e, -1, (p - 1) * (q - 1))

def h(document):
    return int.from_bytes(hashlib.sha256(document).digest(), "big")

def sign(document):
    return pow(h(document), d, n)                   # private key

def verify(document, signature):
    return pow(signature, e, n) == h(document)      # public key

contract = b"Awa sells 3 tonnes of cocoa to Kofi for 4,950,000 F CFA."
s = sign(contract)
print("signature:", str(s)[:30], "…")
print("original contract:", verify(contract, s))
print("modified contract:", verify(contract.replace(b"3 tonnes", b"5 tonnes"), s))
signature: 204254691720259578994908363890 …
original contract: True
modified contract: False

A signature provides three guarantees: integrity (the document has not changed), authenticity (it comes from the holder of the private key) and non-repudiation (the author cannot deny signing it, since nobody else has the key). In practice, RSA-PSS is used or, more and more, Ed25519, an elliptic-curve signature that is faster and more compact.

Who does this public key belong to?

The signature proves "signed by the holder of this public key". But if an attacker gives you their public key while claiming to be your bank, all their signatures will be valid. A public key must be tied to an identity: that is the role of the certificate.

A certificate is a small document saying: "the public key X belongs to bank.example, valid until 1 June 2027", signed by a certificate authority (CA). Your browser and your phone contain a list of about 150 trusted root authorities. Root CAs sign intermediate CAs, which sign the sites' certificates: that is the chain of trust.

The site proves it owns the private key by signing the Diffie-Hellman exchange: no more man in the middle.

Step 5 of 5
Text description of the animation
  1. The site presents its certificate at the start of the HTTPS connection.
  2. The browser checks the certificate's signature with the issuer's public key.
  3. We go up the chain to a root present in the device's trust store.
  4. The certificate must be for THIS site, currently valid, and not revoked.
  5. The site proves it owns the private key by signing the Diffie-Hellman exchange: no more man in the middle.

The last step closes the loop from the previous course: in TLS (the protocol behind HTTPS), the server signs its part of the Diffie-Hellman exchange with its certificate's private key. A man in the middle cannot produce this signature: the attack fails.

import hashlib
import json

p, q = 2**521 - 1, 2**607 - 1                     # the authority's key (demonstration)
n_ca, e = p * q, 65537
d_ca = pow(e, -1, (p - 1) * (q - 1))

def h(data):
    return int.from_bytes(hashlib.sha256(data).digest(), "big")

def issue(subject, public_key, expires):
    content = {"subject": subject, "key": public_key, "expires": expires, "issuer": "Kalanblon Demo CA"}
    data = json.dumps(content, sort_keys=True).encode()      # canonical form, always identical
    return {"content": content, "signature": pow(h(data), d_ca, n_ca)}

def valid_signature(cert):
    data = json.dumps(cert["content"], sort_keys=True).encode()
    return pow(cert["signature"], e, n_ca) == h(data)

cert = issue("bank.example", "n=0x9f3c…, e=65537", "2027-06-01")
print("genuine certificate :", valid_signature(cert))
cert["content"]["subject"] = "pirate.example"               # someone changes the subject
print("modified certificate:", valid_signature(cert))
genuine certificate : True
modified certificate: False

We sign a canonical form of the certificate (here, JSON with sorted keys): the issuer and the verifier must produce exactly the same bytes. Real certificates use the X.509 format, encoded in DER, for the same reason.

Mini-lab: a signature cannot be recycledPython 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

Worked exercise: the signed update

A point-of-sale app downloads its updates. The publisher signs them with its private key; the public key is built into the app. Write install(file, signature) that displays installed if the signature is valid, REFUSED otherwise. Test with the genuine update, an update modified by an attacker, and an update signed by the attacker with their own key.

Hint 1
For the attacker's key, take other Mersenne primes: 2**607 - 1 and 2**1279 - 1.
Hint 2
The app only knows (n_publisher, e): it always verifies with that key, whatever the origin of the signature.
Show the solution and common mistakes
import hashlib

e = 65537
def h(doc):
    return int.from_bytes(hashlib.sha256(doc).digest(), "big")

def key_pair(p, q):
    return p * q, pow(e, -1, (p - 1) * (q - 1))

n_publisher, d_publisher = key_pair(2**521 - 1, 2**607 - 1)
n_attacker, d_attacker = key_pair(2**607 - 1, 2**1279 - 1)

def install(file, signature):
    ok = pow(signature, e, n_publisher) == h(file)        # public key built into the app
    print("installed" if ok else "REFUSED")

update = b"till v3.2: fixes the VAT calculation"
sig = pow(h(update), d_publisher, n_publisher)
trap = b"till v3.2: sends the sales to an unknown server"

install(update, sig)                                       # genuine
install(trap, sig)                                         # content modified
install(trap, pow(h(trap), d_attacker, n_attacker))        # signed by the attacker
installed
REFUSED
REFUSED

The attacker's signature is mathematically correct… for their public key. The app, which only accepts the publisher's key, refuses it. All the security relies on the right public key having been built in safely, at installation time.

Common mistakes:

  • Downloading the public key together with the update: the attacker then supplies their key with their file.
  • Checking the signature after having already run part of the file.
  • Signing the file's name or version instead of its complete content.

Summary

  1. 1A signature is computed with the private key and verified with the public key, on the document's fingerprint.
  2. 2It guarantees integrity, authenticity and non-repudiation.
  3. 3A certificate ties a public key to a name, signed by an authority; the chain goes up to a trusted root.
  4. 4A client must check the chain, the name, the dates and revocation: let the standard library do it.

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