# Demo entry 6493533

Writeup: CC13 Crypto 4 by Parker Garrison

Submitted by anonymous on May 30, 2017 at 02:28
Language: Python. Code size: 3.2 kB.

```#!/usr/bin/env python

# 1. Analyze the given code including existing xor function -- it behaves as expected.

fixed_length_key = "" # Key should be the length of 8 bytes
def xor(data, key): #, key=fixed_length_key):
# 2. Remove the default argument to avoid potential logic errors

from itertools import izip, cycle
import base64
xored = ''.join(chr(ord(x) ^ ord(y)) for (x,y) in izip(data, cycle(key)))
return xored #base64.encodestring(xored).strip()
# 3. Edit the function to not base-64 encode the result, for ease of use.

# 4. Import useful libraries.
import string
import base64
import re

# 5. Test the xor function.
print " ".join(c.encode('hex') for c in xor("\x03\x02\x01\x6f", "\x00\x42"))

# 6. Read the encrypted data, remembering to base-64 decode it.
fin = open("encrypted.txt")
data = ''.join(e for e in fin.readlines())
data = base64.b64decode(data)
print len(data)
K = 8

#print data
#print ','.join(str(ord(c)) for c in data)

# 7. Create sets to hold potential keys for each of the K=8 indexes.
pkeys = [set() for i in range(K)]

for h in range(K):

# 8. Obtain all the characters that are encrypted by bit h of the key, using a slice.
slic = data[h:len(data):K]

#print h, ','.join(str(ord(c)) for c in slic)

for keyint in range(256): # Check all possible keys.
key = chr(keyint)
decd = xor(slic, key)
# 9. Decode the current slice with the current potential key.

valid = string.ascii_uppercase+string.ascii_lowercase+'0123456789'+'./!@#\$%^&*()\'"-=-+ '
# some characters that are likely to be in the leet decoded message text, and more
# 10. Check whether all the characters are valid.
if all(ch in valid for ch in decd):
print "Potential key for index"+str(h)+": "+str(key)+" "+decd
else:
pass

def recdec(pkeys, ind, key):
# 11. Recursive function to generate all keys from the possible keys

if ind < len(pkeys):
for e in pkeys[ind]:
recdec(pkeys, ind+1, key+e)
else:
# 12. Decrypt the data with the complete key, and write the result.
cdecrypted = xor(data, key)
towrite = key+" "+cdecrypted+"\n"
fout.write(towrite) # global variables ftw!

# 13. When a 12 step program isn't enough, we need another step to filter
#     through the results.  Is this key a likely candidate?
#     From this output, many potential keys are generated but it's clear
#     that  passw0rd  is a likely candiate.
numwords = re.findall(" [a-z]{2,9} ", cdecrypted) # lowercase words, 2-9 chars
if len(numwords) > 10:
print towrite

fout = open('crypto4.out', 'w')
print pkeys
recdec(pkeys, 0, "") # Call (11)

print xor(data, 'passw0rd') # From (13)

# Result: The moon hangs like the blade of an axe tonight and it's poised to drop sometime soon enough on this dump truck where I lie mixed up with the morning's trash. 4llImL0singIsM3
# Flag: 4llImL0singIsM3