Home
Writeups Misc About
Bit by Bit

Bit by Bit

I solve this challenge with some misinterpretations, but in the end I got the correct overall theme: Legendre Symbols. I guess I got lucky with the local testing and derive the correct relation.

The challenge, as suggested by the category, is about the ElGamal construction. More information can be found at this Wikipedia link, or any textbook in cryptography should cover this.

The very first observation is that each iteration of the while loop is operating 1 bit of the flag at a time, starting from the last bit of the flag.

We are given the public key h=gx, the two ciphertexts c1=gy and c2=mgxy. However, the message m encrypted is the result of the padding with a bit of the flag. The first observation is that the padding is of the form 256r=28r, where r is some randomly chosen value. The message me generated is of the form me = padding << 1 + m % 2. What's interesting (and what I misinterpreted after solving the challenge) is that << takes precedence before the addition. In other words, me can be written as me = padding << (1 + m % 2).

Hence, if m % 2 == 0, padding is equal to 28r+1, and if m % 2 == 1, padding is equal to 28r+2. We can think of using the Legendre symbol here, as the Legendre symbol when m % 2 == 1 is 1 (the padding is a quadratic residue) and not 1 when m % 2 == 0 (the padding is not a quadratic residue). Luckily, from the parameters given, g is a quadratic residue mod q, by calculating the Legendre symbol.

Hence, if the bit of the flag is 1, c2=mgxy is a quadratic residue, and if the bit of the flag is 0, c2 is not a quadratic residue. With this, we should be able to recover each bit of the flag.

Python Implementation:

This challenge may be extended (have not really verified this) even when g is not a quadratic residue. We can figure out whether gxy is a quadratic residue or not by observing the Legendre symbol of h=gx and c1=gy. If any h and c1 is not a quadratic residue, then gxy is not a quadratic residue (x,y are both odd if that happens). If that is the case, then c1g1 will be a quadratic residue (using the same reasoning above) if m % 2 == 0, and not a quadratic residue otherwise.