XOR
Last updated
Last updated
XOR and XOR Brute Force
┌─[xor@parrot]─[~]
└──╼ $python
Python 2.7.16+ (default, Jul 8 2019, 09:45:29)
[GCC 8.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s1 = "1c0111001f010100061a024b53535009181c"
>>> s2 = "686974207468652062756c6c277320657965"
>>> xor = hex(int(s1, 16) ^ int(s2, 16))
>>> print xor
0x746865206b696420646f6e277420706c6179L
>>>
# Source: https://laconicwolf.com/2018/05/29/cryptopals-challenge-3-single-byte-xor-cipher-in-python/
def get_english_score(input_bytes):
"""Compares each input byte to a character frequency
chart and returns the score of a message based on the
relative frequency the characters occur in the English
language
"""
# From https://en.wikipedia.org/wiki/Letter_frequency
# with the exception of ' ', which I estimated.
character_frequencies = {
'a': .08167, 'b': .01492, 'c': .02782, 'd': .04253,
'e': .12702, 'f': .02228, 'g': .02015, 'h': .06094,
'i': .06094, 'j': .00153, 'k': .00772, 'l': .04025,
'm': .02406, 'n': .06749, 'o': .07507, 'p': .01929,
'q': .00095, 'r': .05987, 's': .06327, 't': .09056,
'u': .02758, 'v': .00978, 'w': .02360, 'x': .00150,
'y': .01974, 'z': .00074, ' ': .13000
}
return sum([character_frequencies.get(chr(byte), 0) for byte in input_bytes.lower()])
def single_char_xor(input_bytes, char_value):
"""Returns the result of each byte being XOR'd with a single value.
"""
output_bytes = b''
for byte in input_bytes:
output_bytes += bytes([byte ^ char_value])
return output_bytes
def main():
hexstring = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736'
ciphertext = bytes.fromhex(hexstring)
potential_messages = []
for key_value in range(256):
message = single_char_xor(ciphertext, key_value)
score = get_english_score(message)
data = {
'message': message,
'score': score,
'key': key_value
}
potential_messages.append(data)
best_score = sorted(potential_messages, key=lambda x: x['score'], reverse=True)[0]
for item in best_score:
print("{}: {}".format(item.title(), best_score[item]))
if __name__ == '__main__':
main()
convert image1.png image2.png -fx "(((255*u)&(255*(1-v)))|((255*(1-u))&(255*v)))/255" C.png