Advertisement
DanFloyd

Affine Cipher Exploit

Aug 18th, 2015
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.81 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. # This script will violate every message enciphered with an affine cipher
  4. # it does a simple 'brute force' attack
  5.  
  6. import sys
  7. import os
  8.  
  9. # This function calculates the modular inverse of a number
  10. def mod_inv (num, mod):
  11.     for x in range(0,mod + 1):
  12.         if ((num*x)%mod == 1):
  13.             return x
  14.     sys.exit('[!!!] ERROR: modulo %d inverse of %d does not exists!' % (mod, num))
  15.  
  16. # Checking arguments
  17. if not len(sys.argv) == 2:
  18.     sys.exit('Usage: %s [FILE PATH]\nExecutes a brute force attack on the ciphered message contained into the file.' % sys.argv[0])
  19.  
  20. if sys.argv[1] == '-h' or sys.argv[1] == '--help':
  21.     sys.exit('Usage: %s [FILE PATH]\nExecutes a brute force attack on the ciphered message contained into the file.' % sys.argv[0])
  22.  
  23. if not os.path.exists(sys.argv[1]):
  24.     sys.exit('[!!!] ERROR: File %s was not found!' % sys.argv[1])
  25.  
  26. # Reading file and setting output file
  27. msg_file = open(sys.argv[1],'r')
  28. exploit = open('exploit.dat','w')
  29. exploit.write('### EXPLOITING %s FILE ###\n' % sys.argv[1]);
  30.  
  31. # Brute force algorithm
  32. for i in range(0,26):
  33.     if (i%2 != 0) and (i != 13):
  34.         for j in range(0,26):
  35.             exploit.write('\n# TRYING KEY <%d,%d>\n# MESSAGE :\n' % (i,j))
  36.             inv = mod_inv(i,26)
  37.             for c in msg_file.read():
  38.                 v = ord(c)
  39.                 if (v >= 65) and (v <= 90):
  40.                     # uppercase
  41.                     cip = ((v - 65 - j)*inv + 26)%26 + 65
  42.                 elif (v >= 97) and (v <= 122):
  43.                     # lowercase
  44.                     cip = ((v - 97 - j)*inv + 26)%26 + 97
  45.                 else:
  46.                     # other characters
  47.                     cip = v
  48.                 # writing deciphered character
  49.                 exploit.write('%c' % cip)
  50.             msg_file.seek(0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement