Advertisement
Guest User

Untitled

a guest
Jan 16th, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. #!/usr/bin/python
  2. #
  3. # Simple XOR brute-force Key recovery script - given a cipher text, plain text and key length
  4. # it searches for proper key that could decrypt cipher into text.
  5. #
  6. # Mariusz B., 2016
  7. #
  8.  
  9. import sys
  10.  
  11. def xorstring(s, k):
  12. out = [0 for c in range(len(s))]
  13. key = []
  14. if type(k) == type(int):
  15. key = [k,]
  16. else:
  17. key = [ki for ki in k]
  18.  
  19. for i in range(len(key)):
  20. for j in range(i, len(s), len(key)):
  21. out[j] = chr(ord(s[j]) ^ key[i])
  22.  
  23. return ''.join(out)
  24.  
  25.  
  26. def brute(input_xored, expected_output, key_len):
  27. key = []
  28.  
  29. if len(input_xored) != len(expected_output):
  30. print '[!] Input xored and expected output lengths not match!'
  31. return False
  32.  
  33. for i in range(key_len):
  34. cipher_letters = [ input_xored[x] for x in range(i, len(input_xored), key_len)]
  35. plaintext_letters = [ expected_output[x] for x in range(i, len(input_xored), key_len)]
  36.  
  37. found = False
  38. for k in range(256):
  39. found = True
  40. for j in range(key_len):
  41. if chr(ord(cipher_letters[j]) ^ k) != plaintext_letters[j]:
  42. found = False
  43. break
  44.  
  45. if found:
  46. key.append(k)
  47. break
  48. found = False
  49.  
  50. if not found:
  51. print '[!] Could not found partial key value.'
  52. break
  53.  
  54. return key, xorstring(input_xored, key) == expected_output
  55.  
  56. def main(argv):
  57. if len(argv) < 4:
  58. print 'Usage: %s <cipher> <plain> <key-len>'
  59. return False
  60.  
  61. cipher = argv[1]
  62. plain = argv[2]
  63. keylen = int(argv[3])
  64.  
  65. if len(cipher) != len(plain):
  66. print '[!] Cipher text and plain text must be of same length!'
  67. return False
  68.  
  69. if len(cipher) % keylen != 0:
  70. print '[!] Cipher text and plain text lengths must be divisble by keylen!'
  71. return False
  72.  
  73. print "Cipher text:\t%s" % cipher
  74. print "Plain text:\t%s" % plain
  75. print "Key length:\t%d" % keylen
  76. key, status = brute(cipher, plain, keylen)
  77.  
  78. if status:
  79. print '[+] Key recovered!'
  80. print '\tKey:\t\t\t', str(key)
  81. print '\tDecrypted string:\t' + xorstring(cipher, key)
  82. else:
  83. print '[!] Key not found.'
  84.  
  85. if __name__ == '__main__':
  86. main(sys.argv)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement