Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # files enc/dec using simple rotation algorithm by ayoub sirai
- import time
- from sys import argv, stdout
- from hashlib import md5
- from os import path
- class encryptor:
- def __init__(self, key):
- self.key = key
- self.infile = ''
- self.outfile = ''
- def select_infile(self, fname):
- if not path.isfile(fname):
- return -1
- self.infile = fname
- return 0
- def select_outfile(self, fname):
- if path.lexists(fname):
- return -1 # file already exist
- self.outfile = fname
- return 0
- def encrypt(self, disp_function=None, flush=None):
- if disp_function==None:
- try:
- i = open(self.infile, 'rb')
- o = open(self.outfile, 'wb')
- sz = path.getsize(self.infile)
- while i.tell() < sz:
- rbyte = i.read(1)
- o.write(chr((ord(rbyte)+self.key) & 0xff)) # c = (m+key) mod 256
- o.close()
- i.close()
- return 0
- except IOError as err:
- return err
- else:
- try:
- i = open(self.infile, 'rb')
- o = open(self.outfile, 'wb')
- sz = path.getsize(self.infile)
- while i.tell() < sz:
- prc = 1 + float(i.tell())/sz * 100
- disp_function('\r[' + '#'*int(prc) + ' '*int(100-prc) + ']' + str(int(prc)) + ' %')
- flush()
- rbyte = i.read(1)
- o.write(chr((ord(rbyte)+self.key) & 0xff))
- o.close()
- i.close()
- return 0
- except IOError as err:
- return err
- def set_encfile_hash(self):
- i = open(self.outfile, 'ab+')
- m = md5()
- sz = path.getsize(self.infile)
- while i.tell() < sz:
- m.update(i.read(1024))
- H = m.hexdigest()
- i.write(H)
- m1 = md5()
- m1.update(str(self.key))
- i.write(m1.hexdigest())
- i.close()
- class decrytpor(encryptor):
- def __init__(self, key):
- self.key = key
- self.__key = 0x1F
- self.infile = ''
- self.outfile = ''
- self.log_path = '/'.join(path.abspath('.').split('/')[:3]) + '/.enc_logfile' # /home/username
- if not path.lexists(self.log_path):
- i=open(self.log_path, 'wb')
- i.close()
- def enc(self, msg, __key):
- r = ''
- for c in msg:
- r+=chr((ord(c) + __key) & 0xff)
- return r
- def dec(self, msg, __key):
- r = ''
- for c in msg:
- if ord(c)-__key < 0:
- r+=chr(256 + ord(c)-__key)
- else:
- r+=chr(ord(c)-__key)
- return r
- def save_file_log(self, fname):
- i = open(self.log_path, 'ab+')
- data = i.read()
- data = self.dec(data, self.__key)
- tables = data.split('\n')
- found=[0, None]
- for table in tables:
- if table.split('@')[0][len('fname:'):] == fname:
- found[0], found[1] = 1, table
- break
- if not found[0]:
- i.write(self.enc('fname:'+fname+'@try:1@ftime:'+str(int(time.time()))+'\n', self.__key))
- return
- else:
- t = int(found[1].split('@')[1][len('try:'):])+1
- ndata = ''
- i.truncate(0)
- for table in tables:
- if table == found[1]:
- ndata+=self.enc('fname:'+fname+'@try:'+str(t)+'@ftime:'+found[1].split('@')[2][len('ftime:'):]+'\n', self.__key)
- else:
- ndata+=self.enc(table+'\n', self.__key)
- i.write(ndata)
- i.close()
- def is_blocked(self, fname,):
- i = open(self.log_path, 'rb')
- data = i.read()
- i.close()
- data = self.dec(data, self.__key)
- tables = data.split('\n')
- found=[0, None]
- for table in tables:
- if table.split('@')[0][len('fname:'):] == fname:
- found[0], found[1] = 1, table
- break
- if not found[0]:
- return [-1, 0]
- else:
- dt = time.time() - int(found[1].split('@')[2][len('ftime:'):])
- t = int(found[1].split('@')[1][len('try:'):])
- if t > 3 and dt < 3600:
- return [1, dt] # 1h=3600s
- return [0, 0]
- def calculate_file_hash(self):
- m = md5()
- i = open(self.infile, 'rb')
- sz = path.getsize(self.infile)
- x, y = 0, sz/1024
- while i.tell() < sz-64:
- if x < y:
- m.update(i.read(1024))
- x+=1
- else:
- m.update(i.read(1))
- i.close()
- return m.hexdigest()
- def correct_key(self):
- __in = open(self.infile, 'rb')
- __in.seek(path.getsize(self.infile)-32, 0)
- __Hash = __in.read(32)
- __in.close()
- m = md5()
- m.update(str(self.key))
- if m.hexdigest() != __Hash:
- return 0
- return 1
- def check_file_status(self):
- __in = open(self.infile, 'rb')
- __in.seek(path.getsize(self.infile)-64, 0)
- __Hash = __in.read(32)
- __in.close()
- if self.calculate_file_hash() != __Hash:
- return 0
- return 1
- def decrypt(self, disp_function=None, flush=None):
- if disp_function==None:
- try:
- i = open(self.infile, 'rb')
- o = open(self.outfile, 'wb')
- sz = path.getsize(self.infile)
- while i.tell() < sz-64:
- o.write(self.dec(i.read(1), self.key))
- o.close()
- i.close()
- return 0
- except IOError as err:
- return err
- else:
- try:
- i = open(self.infile, 'rb')
- o = open(self.outfile, 'wb')
- sz = path.getsize(self.infile)
- while i.tell() < sz-64:
- prc = 1 + float(i.tell())/(sz-64) * 100
- disp_function('\r[' + '#'*int(prc) + ' '*int(100-prc) + ']' + str(int(prc)) + ' %')
- flush()
- o.write(self.dec(i.read(1), self.key))
- o.close()
- i.close()
- return 0
- except IOError as err:
- return err
- def uhelp(__argv):
- print 'usage:\n%s <input file> <output file> <option> --key=<key> -v=value'%__argv
- print 'available options:\n-d or --decrypt to decrypt the input file'
- print '-e or --encrypt to encrypt the input file'
- print '-v=value : set \'value\' to true to turn on the verbose mode'
- def main():
- al = len(argv)
- if al != 6 and al != 2:
- print 'Invalid args, use -h or --help'
- elif al == 2:
- if argv[1] != '-h' and argv[1]!= '--help':
- print 'Invalid args, use -h or --help'
- else:
- uhelp(argv[0])
- else:
- if argv[3] not in ['-e', '-d', '--encrypt', '--decrypt'] or argv[5][:2]!='-v' or argv[5][3:] not in ['true', 'false']:
- uhelp(argv[0])
- return -1
- elif int(argv[4][6:]) > 255 or int(argv[4][6:]) < 0:
- print 'Invalid key value'
- return -1
- inf = argv[1]
- outf = argv[2]
- option = argv[3]
- key = int(argv[4][6:])
- verbose = (argv[5][3:] == 'true')
- if option in ['-e', '--encrypt']:
- Encryptor = encryptor(key)
- if Encryptor.select_infile(inf) < 0:
- print 'Cannot open the input file'
- return -1
- elif Encryptor.select_outfile(outf) < 0:
- print 'output file already exist'
- return -1
- if verbose:
- dstatus = Encryptor.encrypt(stdout.write, stdout.flush)
- if dstatus != 0:
- print '\nError : %s'%dstatus
- else:
- print '\nDone!'
- Encryptor.set_encfile_hash()
- else:
- dstatus = Encryptor.encrypt()
- if dstatus != 0:
- print '\nError : %s'%dstatus
- else:
- print '\nDone!'
- Encryptor.set_encfile_hash()
- else:
- Decryptor = decrytpor(key)
- if Decryptor.select_infile(inf) < 0:
- print 'Cannot open the input file'
- return -1
- elif Decryptor.select_outfile(outf) < 0:
- print 'output file already exist'
- return -1
- user_status = Decryptor.is_blocked(Decryptor.infile)
- if user_status[0]==1:
- print 'you should wait %d second before try again!'%(3600 - user_status[1])
- return -1
- if not Decryptor.correct_key():
- print 'Incorrect key'
- Decryptor.save_file_log(Decryptor.infile)
- return -1
- if not Decryptor.check_file_status():
- print 'The encrypted file has been modified!'
- return -1
- if verbose:
- dstatus = Decryptor.decrypt(stdout.write, stdout.flush)
- if dstatus != 0:
- print '\nError : %s'%dstatus
- else:
- print '\nDone!'
- else:
- dstatus = Decryptor.decrypt()
- if dstatus != 0:
- print '\nError : %s'%dstatus
- else:
- print '\nDone!'
- return 0
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement