Be careful when copy and paste from stackoverflow!
My write-up for a crypto task in SHA2017 CTF.
Stackoverflow (100)
I had some issues implementing strong encryption, luckily I was able to find a nice example on stackoverflow that showed me how to do it.
File: stackoverflow.tgz
b245e83f0fb65763b3c1b346813cb2d3
Extract the given tar, we have a quite simple Python code:
It will encrypt our file (argv[1]) by using AES Counter Mode, but there is a problem: it uses a static counter!
Let see how AES Counter Mode works:
More detail: Wikipedia
So, look at above pictures, we can see: if we use a static counter, because the key and the counter don’t change, and don’t affect to the result after block cipher encryption
, our CTR mode will be like ECB mode.
And how to crack ECB mode? Luckily, we know that our encrypted file is a PDF file, and PDF have a header and some special signatures, so we can make a chosen-plaintext attack.
According to the PDF Reference, we know that the header of PDF file is %PDF-1.x\n
, with x
is in [0, 7].
XORing the given ciphertext bytes with the assuming plaintext bytes (the header), we have a partial key (of course, this key
is what we have when the counter and the real key going through block cipher encryption
), like this:
>>> from Crypto.Util.strxor import strxor
>>> f = open("flag.pdf.enc").read()
>>> a = open("test.pdf").read()
>>> k = strxor(a[:16], f[:16])
>>> strxor(k*5, f[:80])
'%PDF-1.5\r\n%\xb5\xb5\xb5\xb5\rj\n<<\n/PgJeg\xb5\xb7\xb5\xeaOR\n/Type&\x02Cu\xe1\xe4\xf9\xb5\x08\n>>\nendiOj\x1e\xa7\xa5\xa5\xfa\x00bj\n<<\n/RTpq\xb5\xaa\xc5\xbb\x08'
>>>
Now take some guessing, the string endiOj
looks like endobj
in a correct PDF. Find the index and fix the key to have our wanted string, repeatly. Final, we have the right k
in hex: f3bafd331d2844a82520deb7de0c6fb9
. Use k
to XOR with the encoded file, we can have the flag: