Advertisement
Guest User

Xorowanie boba

a guest
Jul 19th, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.01 KB | None | 0 0
  1. def get_english_score(input_bytes):
  2.     """Compares each input byte to a character frequency
  3.    chart and returns the score of a message based on the
  4.    relative frequency the characters occur in the English
  5.    language
  6.    """
  7.  
  8.     # From https://en.wikipedia.org/wiki/Letter_frequency
  9.     # with the exception of ' ', which I estimated.
  10.     character_frequencies = {
  11.         'a': .08167, 'b': .01492, 'c': .02782, 'd': .04253,
  12.         'e': .12702, 'f': .02228, 'g': .02015, 'h': .06094,
  13.         'i': .06094, 'j': .00153, 'k': .00772, 'l': .04025,
  14.         'm': .02406, 'n': .06749, 'o': .07507, 'p': .01929,
  15.         'q': .00095, 'r': .05987, 's': .06327, 't': .09056,
  16.         'u': .02758, 'v': .00978, 'w': .02360, 'x': .00150,
  17.         'y': .01974, 'z': .00074, ' ': .13000
  18.     }
  19.     return sum([character_frequencies.get(chr(byte), 0) for byte in input_bytes.lower()])
  20.  
  21.  
  22. def single_char_xor(input_bytes, char_value):
  23.     """Returns the result of each byte being XOR'd with a single value.
  24.    """
  25.     output_bytes = b''
  26.     for byte in input_bytes:
  27.         output_bytes += bytes([byte ^ char_value])
  28.     return output_bytes
  29.  
  30.  
  31. def main():
  32.     hexstring = '18283b3b3b3b3b2d357b7a0d333e203f7a203f7a2f3e3b36357a19337a29333f7a2835202920233c28352d3b397a2e3f31292e7a203b2920233c28352d3b34237a2a35303f3e2334392023377a383b302e3f37747a14357a3e3538283b767a3c363b3d3b7a2e35607a0815000d1b1605210933343d363f02352818232e3f19332a323f2827'
  33.     ciphertext = bytes.fromhex(hexstring)
  34.     potential_messages = []
  35.     for key_value in range(256):
  36.         message = single_char_xor(ciphertext, key_value)
  37.         score = get_english_score(message)
  38.         data = {
  39.             'message': message,
  40.             'score': score,
  41.             'key': key_value
  42.             }
  43.         potential_messages.append(data)
  44.     best_score = sorted(potential_messages, key=lambda x: x['score'], reverse=True)[0]
  45.     for item in best_score:
  46.         print("{}: {}".format(item.title(), best_score[item]))
  47.  
  48. if __name__ == '__main__':
  49.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement