Skip to content

Instantly share code, notes, and snippets.

@ziot
Created July 12, 2018 20:22
Show Gist options
  • Save ziot/b621c661708e9740998106ce1910009a to your computer and use it in GitHub Desktop.
Save ziot/b621c661708e9740998106ce1910009a to your computer and use it in GitHub Desktop.
Partial Xor Key Bruteforcing
cipher = []
def loadFile(file):
with open(file) as f:
lines = f.read().splitlines()
return lines
def getLetter(pos, letter):
char = cipher[pos]
for x in xrange(0,255):
if char^x == ord(letter):
return x
def getPercentAscii(input):
count = 0
for char in input:
if char.isalnum():
count+=1
return int(100 * float(count)/float(575))
def getKey(keyStr, pos):
expected = list(keyStr)
key = []
for id,char in enumerate(expected):
key.append(getLetter(pos+id, char))
return key
def getCipherData(pos, length):
newCipher = cipher[pos:]
return newCipher[:length]
def isValid(word, key, output):
if len(word)>4 and word in output and word != keyStr and word not in keyStr:
return True
return False
def xorAttempt(key, pos, lenGuess):
out = []
for x in xrange(len(cipher)/lenGuess):
newPos = pos+(x*lenGuess)
cipherData = getCipherData(newPos, lenGuess)
for id,char in enumerate(cipherData):
xorChar = chr(char^key[id%len(key)])
if xorChar.isalnum():
out.append(xorChar)
else:
out.append(".")
out.append(" ")
return "".join(out)
wordDict = loadFile('words.txt')
guessWords = ["cipher","encryption","case","detective"]
for keyStr in guessWords:
percentThreshold = 50
for keyLenGuess in xrange(20,30):
for pos in xrange(len(cipher)-len(keyStr)):
key = getKey(keyStr, pos)
output = xorAttempt(key, pos, keyLenGuess)
percent = getPercentAscii(output)
if percent>percentThreshold:
for word in wordDict:
if isValid(word, keyStr, output):
print "-"*20
print "Word guess: ", keyStr
print "Key Len guess: ", keyLenGuess
print "Position: ", pos
print "Key: ", key
print "Found: ", word
print "-"*20
print output
print "-"*20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment