Advertisement
CSenshi

Cryptography - HW1.4 (Challenge-04)

Jan 10th, 2020
411
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.09 KB | None | 0 0
  1. import re
  2.  
  3.  
  4. # score for being an english word
  5. def score(x):
  6.     # calculate how many characters are english chars
  7.     score = [(1) if (c.isalpha()) else(0) for c in x]
  8.     # multiply result by number of words
  9.     score *= len(x.split(' '))
  10.  
  11.     return score
  12.  
  13.  
  14. def decode(s):
  15.     res = []
  16.     # convert to string
  17.     plain_text_bytes = bytes.fromhex(s)
  18.     # iterate over each character
  19.     for ind in range(256):
  20.         result = ''
  21.         # xor to char
  22.         for t in plain_text_bytes:
  23.             r = t ^ ind
  24.             result += chr(r)
  25.         # check if accomplishes regex
  26.         if re.search("^[a-zA-Z0-9. -_?]*$", result):
  27.             res += [result]
  28.     return res
  29.  
  30.  
  31. if __name__ == "__main__":
  32.     # number of strings
  33.     n = int(input())
  34.  
  35.     # array of strings that are most likely to be words
  36.     found = []
  37.     for i in range(n):
  38.         s = input()
  39.         # decoded array of given input (most likely to be words)
  40.         found += decode(s)
  41.  
  42.     # sort arr
  43.     decrypted_word = max(found, key=lambda x: score(x))
  44.     # print result
  45.     print(decrypted_word)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement