Advertisement
Guest User

encryptor.py

a guest
Mar 20th, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.44 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3.  
  4. # files enc/dec using simple rotation algorithm by ayoub sirai
  5.  
  6. import time
  7. from sys import argv, stdout
  8. from hashlib import md5
  9. from os import path
  10.  
  11. class encryptor:
  12.     def __init__(self, key):
  13.         self.key = key
  14.         self.infile = ''
  15.         self.outfile = ''
  16.     def select_infile(self, fname):
  17.         if not path.isfile(fname):
  18.             return -1
  19.         self.infile = fname
  20.         return 0
  21.     def select_outfile(self, fname):
  22.         if path.lexists(fname):
  23.             return -1 # file already exist
  24.         self.outfile = fname
  25.         return 0
  26.     def encrypt(self, disp_function=None, flush=None):
  27.         if disp_function==None:
  28.             try:
  29.                 i = open(self.infile, 'rb')
  30.                 o = open(self.outfile, 'wb')
  31.                 sz = path.getsize(self.infile)
  32.                 while i.tell() < sz:
  33.                     rbyte = i.read(1)
  34.                     o.write(chr((ord(rbyte)+self.key) & 0xff)) # c = (m+key) mod 256
  35.                 o.close()
  36.                 i.close()
  37.                 return 0
  38.             except IOError as err:
  39.                 return err
  40.         else:
  41.             try:
  42.                 i = open(self.infile, 'rb')
  43.                 o = open(self.outfile, 'wb')
  44.                 sz = path.getsize(self.infile)
  45.                 while i.tell() < sz:
  46.                     prc = 1 + float(i.tell())/sz * 100
  47.                     disp_function('\r[' + '#'*int(prc) + ' '*int(100-prc) + ']' + str(int(prc)) + ' %')
  48.                     flush()
  49.                     rbyte = i.read(1)
  50.                     o.write(chr((ord(rbyte)+self.key) & 0xff))
  51.                 o.close()
  52.                 i.close()
  53.                 return 0
  54.             except IOError as err:
  55.                 return err
  56.     def set_encfile_hash(self):
  57.         i = open(self.outfile, 'ab+')
  58.         m = md5()
  59.         sz = path.getsize(self.infile)
  60.         while i.tell() < sz:
  61.             m.update(i.read(1024))
  62.         H = m.hexdigest()
  63.         i.write(H)
  64.         m1 = md5()
  65.         m1.update(str(self.key))
  66.         i.write(m1.hexdigest())
  67.         i.close()
  68.  
  69. class decrytpor(encryptor):
  70.     def __init__(self, key):
  71.         self.key = key
  72.         self.__key = 0x1F
  73.         self.infile = ''
  74.         self.outfile = ''
  75.         self.log_path = '/'.join(path.abspath('.').split('/')[:3]) + '/.enc_logfile' # /home/username
  76.         if not path.lexists(self.log_path):
  77.             i=open(self.log_path, 'wb')
  78.             i.close()
  79.     def enc(self, msg, __key):
  80.         r = ''
  81.         for c in msg:
  82.             r+=chr((ord(c) + __key) & 0xff)
  83.         return r
  84.     def dec(self, msg, __key):
  85.         r = ''
  86.         for c in msg:
  87.             if ord(c)-__key < 0:
  88.                 r+=chr(256 + ord(c)-__key)
  89.             else:
  90.                 r+=chr(ord(c)-__key)
  91.         return r
  92.     def save_file_log(self, fname):
  93.         i = open(self.log_path, 'ab+')
  94.         data = i.read()
  95.         data = self.dec(data, self.__key)
  96.         tables = data.split('\n')
  97.         found=[0, None]
  98.         for table in tables:
  99.             if table.split('@')[0][len('fname:'):] == fname:
  100.                 found[0], found[1] = 1, table
  101.                 break
  102.         if not found[0]:
  103.             i.write(self.enc('fname:'+fname+'@try:1@ftime:'+str(int(time.time()))+'\n', self.__key))
  104.             return
  105.         else:
  106.             t = int(found[1].split('@')[1][len('try:'):])+1
  107.             ndata = ''
  108.             i.truncate(0)
  109.             for table in tables:
  110.                 if table == found[1]:
  111.                     ndata+=self.enc('fname:'+fname+'@try:'+str(t)+'@ftime:'+found[1].split('@')[2][len('ftime:'):]+'\n', self.__key)
  112.                 else:
  113.                     ndata+=self.enc(table+'\n', self.__key)
  114.             i.write(ndata)
  115.         i.close()
  116.     def is_blocked(self, fname,):
  117.         i = open(self.log_path, 'rb')
  118.         data = i.read()
  119.         i.close()
  120.         data = self.dec(data, self.__key)
  121.         tables = data.split('\n')
  122.         found=[0, None]
  123.         for table in tables:
  124.             if table.split('@')[0][len('fname:'):] == fname:
  125.                 found[0], found[1] = 1, table
  126.                 break
  127.         if not found[0]:
  128.             return [-1, 0]
  129.         else:
  130.             dt = time.time() - int(found[1].split('@')[2][len('ftime:'):])
  131.             t = int(found[1].split('@')[1][len('try:'):])
  132.             if t > 3 and dt < 3600:
  133.                 return [1, dt] # 1h=3600s
  134.             return [0, 0]
  135.     def calculate_file_hash(self):
  136.         m = md5()
  137.         i = open(self.infile, 'rb')
  138.         sz = path.getsize(self.infile)
  139.         x, y = 0, sz/1024
  140.         while i.tell() < sz-64:
  141.             if x < y:
  142.                 m.update(i.read(1024))
  143.                 x+=1
  144.             else:
  145.                 m.update(i.read(1))
  146.         i.close()
  147.         return m.hexdigest()
  148.     def correct_key(self):
  149.         __in = open(self.infile, 'rb')
  150.         __in.seek(path.getsize(self.infile)-32, 0)
  151.         __Hash = __in.read(32)
  152.         __in.close()
  153.         m = md5()
  154.         m.update(str(self.key))
  155.         if m.hexdigest() != __Hash:
  156.             return 0
  157.         return 1
  158.     def check_file_status(self):
  159.         __in = open(self.infile, 'rb')
  160.         __in.seek(path.getsize(self.infile)-64, 0)
  161.         __Hash = __in.read(32)
  162.         __in.close()
  163.         if self.calculate_file_hash() != __Hash:
  164.             return 0
  165.         return 1
  166.     def decrypt(self, disp_function=None, flush=None):
  167.         if disp_function==None:
  168.             try:
  169.                 i = open(self.infile, 'rb')
  170.                 o = open(self.outfile, 'wb')
  171.                 sz = path.getsize(self.infile)
  172.                 while i.tell() < sz-64:
  173.                     o.write(self.dec(i.read(1), self.key))
  174.                 o.close()
  175.                 i.close()
  176.                 return  0
  177.             except IOError as err:
  178.                 return err
  179.         else:
  180.             try:
  181.                 i = open(self.infile, 'rb')
  182.                 o = open(self.outfile, 'wb')
  183.                 sz = path.getsize(self.infile)
  184.                 while i.tell() < sz-64:
  185.                     prc = 1 + float(i.tell())/(sz-64) * 100
  186.                     disp_function('\r[' + '#'*int(prc) + ' '*int(100-prc) + ']' + str(int(prc)) + ' %')
  187.                     flush()
  188.                     o.write(self.dec(i.read(1), self.key))
  189.                 o.close()
  190.                 i.close()
  191.                 return 0
  192.             except IOError as err:
  193.                 return err
  194. def uhelp(__argv):
  195.     print 'usage:\n%s <input file> <output file> <option> --key=<key> -v=value'%__argv
  196.     print 'available options:\n-d or --decrypt to decrypt the input file'
  197.     print '-e or --encrypt to encrypt the input file'
  198.     print '-v=value : set \'value\' to true to turn on the verbose mode'
  199.  
  200. def main():
  201.     al = len(argv)
  202.     if al != 6 and al != 2:
  203.         print 'Invalid args, use -h or --help'
  204.     elif al == 2:
  205.         if argv[1] != '-h' and argv[1]!= '--help':
  206.             print 'Invalid args, use -h or --help'
  207.         else:
  208.             uhelp(argv[0])
  209.     else:
  210.         if argv[3] not in ['-e', '-d', '--encrypt', '--decrypt'] or argv[5][:2]!='-v' or argv[5][3:] not in ['true', 'false']:
  211.             uhelp(argv[0])
  212.             return -1
  213.         elif int(argv[4][6:]) > 255 or int(argv[4][6:]) < 0:
  214.             print 'Invalid key value'
  215.             return -1
  216.         inf = argv[1]
  217.         outf = argv[2]
  218.         option = argv[3]
  219.         key = int(argv[4][6:])
  220.         verbose = (argv[5][3:] == 'true')
  221.         if option in ['-e', '--encrypt']:
  222.             Encryptor = encryptor(key)
  223.             if Encryptor.select_infile(inf) < 0:
  224.                 print 'Cannot open the input file'
  225.                 return -1
  226.             elif Encryptor.select_outfile(outf) < 0:
  227.                 print 'output file already exist'
  228.                 return -1
  229.             if verbose:
  230.                 dstatus = Encryptor.encrypt(stdout.write, stdout.flush)
  231.                 if dstatus != 0:
  232.                     print '\nError : %s'%dstatus
  233.                 else:
  234.                     print '\nDone!'
  235.                     Encryptor.set_encfile_hash()
  236.             else:
  237.                 dstatus = Encryptor.encrypt()
  238.                 if dstatus != 0:
  239.                     print '\nError : %s'%dstatus
  240.                 else:
  241.                     print '\nDone!'
  242.                     Encryptor.set_encfile_hash()
  243.         else:
  244.             Decryptor = decrytpor(key)
  245.             if Decryptor.select_infile(inf) < 0:
  246.                 print 'Cannot open the input file'
  247.                 return -1
  248.             elif Decryptor.select_outfile(outf) < 0:
  249.                 print 'output file already exist'
  250.                 return -1
  251.             user_status = Decryptor.is_blocked(Decryptor.infile)
  252.             if user_status[0]==1:
  253.                 print 'you should wait %d second before try again!'%(3600 - user_status[1])
  254.                 return -1
  255.             if not Decryptor.correct_key():
  256.                 print 'Incorrect key'
  257.                 Decryptor.save_file_log(Decryptor.infile)
  258.                 return -1
  259.             if not Decryptor.check_file_status():
  260.                 print 'The encrypted file has been modified!'
  261.                 return -1
  262.             if verbose:
  263.                 dstatus = Decryptor.decrypt(stdout.write, stdout.flush)
  264.                 if dstatus != 0:
  265.                     print '\nError : %s'%dstatus
  266.                 else:
  267.                     print '\nDone!'
  268.             else:
  269.                 dstatus = Decryptor.decrypt()
  270.                 if dstatus != 0:
  271.                     print '\nError : %s'%dstatus
  272.                 else:
  273.                     print '\nDone!'
  274.         return 0
  275. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement