Lab 10 - Public key encryption

In this lab we'll do some cool exercises using public key encryption methods for key exchange and data encryption.

Before starting the labs, download openssl 1.1.0 from here. Save the file to some local folder accessible by you, then compile it and install it to some folder. Open the unpacked folder from bash, and run the following commands:

linux$./config --prefix=/home/student/local --openssldir=/home/student/local/openssl linux$ make
linux$make test linux$ make install

(in case of trouble, check also the instructions at the end of lab 8).

While the tools are building/compiling you may start working on some of the exercises.

Exercise 1: Diffie-Hellman key exchange (4p)

As we discussed in class, Diffie and Hellman proposed the first public key exchange mechanism such that two parties, that did not share any previous secret could establish a common secret. This allows the parties to have a shared key that only they know (except if there is an active man in the middle attack, which is usually solved by using TLS/certificates, but we shall not focus on that here).

Download the lab code from here. After unzipping, you'll find the source code for a client (dhe.c) and a server (dhe_server.c), along with a Makefile and fixed Diffie-Hellman p and g params in the files dhparam.pem.

Update the Makefile with the paths relevant to your installation folders

The client and server have a similar structure. Each of them should build a public key, then send it to the other party, receive the public key from the other party and finally compute the secret key. Your task is to complete the missing parts. For this, consult the openssl documentation here. Since they are similar, focus only on one of them and then do similarly on the other one.

The makefile should help you build both. Just type 'make all'. After completing the necessary todo's in the file, you can start the server by typing 'make start_server' and the client with 'make start_client'.

If all goes well, you should see the same secret key on both client and server.

Bonus 1

Perform the DH key exchange between two teams, sending the public key values over the network and verify that you get the same secret key.

Bonus 2

Use the secret key to encrypt some data (see previous labs) and check that the other party can decrypt it.

Exercise 2: RSA parity oracle (4p)

Generate a 1024 bit RSA key pair.

Write an oracle function that uses the private key to answer the question “is the plaintext of this message even or odd” (is the last bit of the message 0 or 1). Imagine for instance a server that accepted RSA-encrypted messages and checked the parity of their decryption to validate them, and spat out an error if they were of the wrong parity.

Anyways: function returning true or false based on whether the decrypted plaintext was even or odd, and nothing else.

Take the following string and un-Base64 it in your code (without looking at it!) and encrypt it to the public key, creating a ciphertext:

VGhhdCdzIHdoeSBJIGZvdW5kIHlvdSBkb24ndCBwbGF5IGFyb3VuZCB3aXRoIHRoZSBGdW5reSBDb2xkIE1lZGluYQ==

With your oracle function, you can trivially decrypt the message.

Here's why:

• RSA ciphertexts are just numbers. You can do trivial math on them. You can for instance multiply a ciphertext by the RSA-encryption of another number; the corresponding plaintext will be the product of those two numbers.
• If you double a ciphertext (multiply it by (2**e)%n), the resulting plaintext will (obviously) be either even or odd.
• If the plaintext after doubling is even, doubling the plaintext didn't wrap the modulus — the modulus is a prime number.

That means the plaintext is less than half the modulus.

You can repeatedly apply this heuristic, once per bit of the message, checking your oracle function each time.

Your decryption function starts with bounds for the plaintext of [0,n].

Each iteration of the decryption cuts the bounds in half; either the upper bound is reduced by half, or the lower bound is.

After log2(n) iterations, you have the decryption of the message.

Print the upper bound of the message as a string at each iteration; you'll see the message decrypt “hollywood style”.

Decrypt the string (after encrypting it to a hidden private key) above.

Exercise 3: Merkle's puzzles (4p)

Alice wants to share a secret with Bob, but she knows that if she explicitly tells it to Bob, Eve somehow will find out (she hears everything). So she and Bob establish a small game which helps them think about the same secret, without saying it. The game goes like this:

• Alice sends to Bot a list of puzzles. A puzzle looks like this:

$\mathsf{Puzzle}_i = \mathsf{AES}(\mathsf{key} = 0^{14} \| i, \mathsf{plaintext = Puzzle} \| i \| secret_i)$ where $secret_i$ represents the $i$-th secret Alice generated (represents 8 randomly generated bytes) and which should be figured out by Bob.

• Bob receives the puzzles and randomly chooses one. He knows the first 14 bytes of the key are 0, so he tries to brute-force the rest of the key until he finds a plain text starting with “Puzzle”. This way, he knows Alice's secret (the last part of the plain text).
• Bob sends the index of the puzzle that he solved, in order to let Alice know which secret they agreed on.

In the end, both Alice and Bob share the same secret, and Eve has no clue about it.

Your job is to implement this mechanism starting from the following skeleton:

merkle.py
import random
import string
from Crypto.Cipher import AES
import os

def aes_enc(k, m):
"""
Encrypt a message m with a key k in ECB mode using AES as follows:
c = AES(k, m)

Args:
m should be a bytestring multiple of 16 bytes (i.e. a sequence of characters such as 'Hello...' or '\x02\x04...')
k should be a bytestring of length exactly 16 bytes.

Return:
The bytestring ciphertext c
"""
aes = AES.new(k)
c = aes.encrypt(m)

return c

def aes_dec(k, c):
"""
Decrypt a ciphertext c with a key k in ECB mode using AES as follows:
m = AES(k, c)

Args:
c should be a bytestring multiple of 16 bytes (i.e. a sequence of characters such as 'Hello...' or '\x02\x04...')
k should be a bytestring of length exactly 16 bytes.

Return:
The bytestring message m
"""
aes = AES.new(k)
m = aes.decrypt(c)

return m

alice_keys = []
bob_key = []

# TODO This is Alice. She generates 2^16 random keys and 2^16 puzzles.
# A puzzle has the following formula:
# puzzle[i] = aes_enc(key = 0..0 + i, plaintext ="Puzzle" + chr(i) + chr(j) + alice_keys[i])
# This function shall fill in the alice_keys list and shall return a list of 2^16 puzzles.
def gen_puzzles():
# TODO

# TODO This is Bob. He tries to solve one random puzzle. His purpose is to solve one random puzzle
# offered by Alice.
# This function shall fill in the bob_key list with the secret discovered by Bob.
# The function shall return the index of the chosen puzzle.
def solve_puzzle(puzzles):
# TODO

def main():
# Alice generates some puzzles
puzzles = gen_puzzles()
# Bob solves one random puzzle and discovers the secret
x = solve_puzzle(puzzles)
print "Bob's secret key: " + bob_key[0]
# Alice receives the puzzle index from Bob and now knows the secret
print "Alice's secret key: " + alice_keys[x]
# The secret should be the same, even if it was not explicitly shared
if bob_key[0] == alice_keys[x]:
print ":)"
else:
print ":("

if __name__ == "__main__":
main()