Writing a TLS client/server
Transport Layer Security (TLS) provides end-to-end encryption without revealing the encryption key to prevent man-in-the-middle attacks. It also provides authentication of peers and message integrity guarantees. This recipe shows how to set up a TLS server for securing network communications. However, first, a few words on public key cryptography can be useful.
A cryptographic key pair contains a private key and a public key. The private key is kept secret and the public key is published.
This is how a key pair is used to encrypt messages: Since the public key of a party is published, anybody can create a message and encrypt it using the public key, then send it to the party that has the private key. Only the private key owner can decrypt that message. That also means that if the private key is revealed, anybody with that private key can eavesdrop on such messages.
This is how a key pair is used to ensure message integrity: The owner of a private...