def generate(self): '''Use the function self._gen to generate and write the wordlist.''' msg = "Words' length : {} characters ;".format(self.w_lth) msg += "\nAlphabet's length : {} characters ;".format(self.alf_lth) msg += "\nWordlist's length : {} lines ;".format(space(str(self.wrdlst_lth))) msg += "\nWordlist's size : {} ({} bytes).".format(h_size(self.size), space(str(self.size))) if self.interface == None: print(msg) sure = True elif self.interface == 'console': cl_out(c_output, msg) sure = inp_lst('Generate ? (y/n) :', ('y', 'n')) == 'y' else: msg_ = msg + '\n\nGenerate ?' sure = QMessageBox.question( None, 'Generate ?', msg_, \ QMessageBox.Yes | QMessageBox.Cancel, QMessageBox.Yes) == QMessageBox.Yes if sure : self._gen(self.w_lth, '')
def decrypt(self, pwd): ''' Decrypt 'self.k_name' with AES-256-CBC using the password `pwd` (Hasher('sha256').hash(clear_pwd)), make a file 'self.k_name' + ext and remove encrypted one. - pwd : the password. ''' fn = self.get_fn('pvk') if fn[-4:] != '.enc': raise KeyError(tr('The RSA key is not encrypted !')) old_path = chd_rsa(glb.home) with open(fn, 'r') as f: f_content = f.read() try: f_dec = AES(256, pwd, hexa=True).decryptText(f_content, mode_c='hexa') except UnicodeDecodeError: msg = tr('This is not the good password !') if self.interface == 'gui': QMessageBox.critical(None, '!!! Wrong password !!!', '<h2>{}</h2>'.format(msg)) elif self.interface == 'console': cl_out(c_error, msg) else: print('Cracker: RsaKeys: decrypt: ' + msg) chdir(old_path) return -3 except ValueError: msg = tr('The file is not well formatted !') if self.interface == 'gui': QMessageBox.critical(None, '!!! File error !!!', '<h2>{}</h2>'.format(msg)) elif self.interface == 'console': cl_out(c_error, msg) else: print('Cracker: RsaKeys: decrypt: ' + msg) chdir(old_path) return -2 with open(fn[:-4], 'w') as f: f.write(f_dec) remove(fn) chdir(old_path)
def wordlist_generator_6(alf, dep_lth, lth, f_name, b_word): '''Write a wordlist in a file. Keywords arguments : alf : the alphabet used to write the wordlist dep_lth : the lenth of the words in the wordlist lth : the remaining letters to add to the word f_name : the filename b_word : the begin of the word ''' global file_ global rep global lst_rep len_alf = len(alf) lth_wrdlst = len_alf**int(dep_lth) nb_rep = sum(len_alf**k for k in range(dep_lth - 1)) if lth == dep_lth : #if it is main function (to open only one time) file_ = open(f_name, 'w') print('Processing ...\n') t1 = dt.now() rep = 0 lst_rep = [] if lth == 1: for k in alf: file_.write(b_word + k + '\n') else : for k in alf: wordlist_generator_6(alf, dep_lth, lth-1, f_name, b_word + k) #print the progression rep += 1 rep50 = round(rep/nb_rep*50) color(c_wrdlt) if rep > 1: print('\b'*52, end='') print('|' + '#'*rep50 + ' '*(50-rep50) + '|', end='') color(c_prog) if lth == dep_lth: t2 = dt.now() #calc the time duration t_dif = t2 - t1 cl_out(c_succes, '\nDone in ' + str(t_dif) + ' second(s)') file_.close()
def decrypt(self, msg_c, rm_padding=False): ''' Return the decrypted message. - msg_c : the encrypted message. Should be a tuple or list of the form (AES_key_c, msg_c) ; - rm_padding : Should be a boolean. If True, remove the padding inserted at the end of the message ('\x00'). ''' if rm_padding not in (0, 1): raise ValueError('The argument "rm_padding" should be a boolean, \ but "{}" was found !!!'.format(rm_padding)) if type(msg_c) not in (list, tuple, set): raise ValueError('The argument "msg_c" should be a list, tuple or \ a set, but a "{}" was found !!!'.format(type(msg_c))) else: if len(msg_c) != 2: raise ValueError( 'The argument "msg_c" should have a length of \ 2, but a length of "{}" was found !!!'.format(len(msg_c))) #------AES key AES_key = self.RSA_ciph.decrypt(msg_c[0]) #------decrypt text try: AES_cipher = AES(self.AES_mode, AES_key, False, encoding=self.encod) except ValueError as err: msg = 'You did NOT selected the right RSA key !!!' if self.interface == None: print(msg) elif self.interface == 'console': cl_out(c_error, msg) else: QMessageBox.critical(None, 'Bad RSA key !!!', '<h2>{}</h2>'.format(msg)) raise ValueError(msg) msg = AES_cipher.decryptText(msg_c[1], mode_c='hexa', encoding=self.encod, mode=self.md) if rm_padding: return msg.strip('\x00') return msg
def _get_p_q(self, size, verbose=False): '''Function finding p and q of size `size // 2`.''' if verbose: print('\nCalculating keys ...\n') t1 = dt.now() #------ini progress bar if self.interface == 'gui': pb = GuiProgressBar(title='Generating ... ― Cracker', undetermined=True) elif self.interface == 'console': pb = ConsoleProgressBar() p = 1 while not isSurelyPrime(p): p = randbits(size // 2) if self.interface in ('gui', 'console'): pb.load() print('\b \b', end='') if verbose: t_p = dt.now() - t1 msg1 = 'p found in {} s.'.format(t_p) cl_out(c_succes, msg1 + '\n') t2 = dt.now() q = 1 while not (isSurelyPrime(q) and p != q): q = randbits(size // 2) if self.interface in ('gui', 'console'): pb.load() print('\b \b', end='') if verbose: t_q = dt.now() - t2 t_t = dt.now() - t1 msg = 'q found in {} s.\nTime elapsed : {} s.'.format(t_q, t_t) if self.interface in (None, 'console'): cl_out(c_succes, msg) elif verbose: QMessageBox.about(None, 'Done !', '<h2>{}</h2>\n<h2>{}</h2>'.format(msg1, msg)) return p, q
def inp_lst(prompt, lst): '''Works like input but accepts only values in the list lst, reask if not.''' c = '' c = cl_inp(prompt) while c not in lst: cl_out(c_error, '\nWhat you entered is NOT in list !') c = cl_inp(prompt) return c
def use_open_w(): #todo: move (in the console file) and improve this try: file_name = cl_inp(tr("Enter the wordlist's name :")) wordlist_f = open(file_name, 'r') except FileNotFoundError: cl_out(c_error, tr('No file of this name !!!') + ' \n' + tr('Back menu ...')) else: wordlist_f.close() open_w(file_name)
def use_hasher(): '''Use hasher function in console mode.''' h_str = tuple(algorithms_available) prompt_h = set_prompt(algorithms_available) prompt = 'Hashes :\n\n ' + prompt_h + '\n\nChoose a hash to hash with :' h = inp_lst(prompt, h_str) txt = cl_inp('Word to hash :') prnt = '=====> ' + hasher(h, txt) cl_out(c_output, prnt)
def show_time(self, time): '''Show the time, according to the self.interface arg.''' msg = tr('Done in {} s !').format(time) if self.interface == None: print(msg) elif self.interface == 'console': cl_out(c_succes, msg) else: QMessageBox.about(None, tr('Done !'), msg)
def err_not_well_formated(): msg = tr('The file is not well formatted !') if self.interface == 'gui': QMessageBox.critical(None, '!!! File error !!!', '<h2>{}</h2>'.format(msg)) elif self.interface == 'console': cl_out(c_error, msg) else: print('Cracker: RsaKeys: read: ' + msg) return -2
def inp_int(prompt, type_=int): '''Works like input but accepts only type_, reask if not.''' while True: try: var = cl_inp(prompt) var = type_(var) except ValueError: cl_out(c_error, 'What you entered is NOT an {} !'.format(type_)) else: break return var
def encrypt(self, txt): '''Return the encrypted text txt with the public key self.pb_key.''' if self.pb_key == None: msg_err = 'Cannot encrypt with an empty key !!!' if self.interface == 'console': cl_out(c_error, msg_err) elif self.interface == 'gui': QMessageBox.critical(None, 'Cannot encrypt !!!', '<h2>{}</h2>'.format(msg_err)) raise TypeError(msg_err) #------ini progress bar if self.interface == 'gui': pb = GuiProgressBar(title='Encrypting ... | RSA ― Cracker', verbose=True) elif self.interface == 'console': pb = ConsoleProgressBar() #------ini e, n = self.pb_key grp_size = len(str(n)) - 1 encoded_txt = MsgForm(txt).encode(grp_size) #------crypt l_txt_crypted = [] for j, k in enumerate(encoded_txt): i = int(k) l_txt_crypted.append(pow(i, e, n)) #todo: try the math.pow speed ! if self.interface in ('gui', 'console'): pb.set(j, len(encoded_txt)) ret = '' for k in l_txt_crypted: ret += str(k) + ' ' ret = ret[:-1] #remove last space. return ret
def unsign(self, txt): ''' Unsign the message 'txt'. It decrypt 'txt' using the public key. ''' if self.pb_key == None: msg_err = 'Cannot unsign with an empty key !!!' if self.interface == 'console': cl_out(c_error, msg_err) elif self.interface == 'gui': QMessageBox.critical(None, 'Cannot unsign !!!', '<h2>{}</h2>'.format(msg_err)) raise TypeError(msg_err) return RSA([self.pv_key, self.pb_key], self.interface).decrypt(txt)
def is_valid_file(self): '''Check if the file is reachable with the options. .Return : -1 if the file was not found ; -2 if an encoding error occur. ''' try: md = ('r', 'rb')[self.binary] with open(self.fn, mode=md, encoding=self.encod) as f: char_1 = f.read(1) if self.binary: char_1 = char_1.decode() except FileNotFoundError: ret = -1 except UnicodeDecodeError: ret = -2 else: ret = 0 if ret == -1: msg_err = tr('The file "{}" was NOT found !!!').format(self.fn) elif ret == -2: msg_err = tr('Bad encoding "{}" for the file "{}"').format( self.encod, self.fn) if ret in (-1, -2): if self.interface == None: raise FileNotFoundError(msg_err) elif self.interface == 'console': cl_out(c_error, msg_err) elif self.interface == 'gui': QMessageBox.critical(None, tr('!!! File error !!!'), msg_err) return ret
def sign(self, txt): ''' Sign the message 'txt'. It encrypt 'txt' using the private key. ''' if self.pv_key == None: try: self.keys['d'] = RsaKeys(self.keys_init, interface=self.interface).get_key(1) self.pv_key = self.keys['d'] except TypeError: msg_err = 'Cannot sign with an empty private key !!!' if self.interface == 'console': cl_out(c_error, msg_err) elif self.interface == 'gui': QMessageBox.critical(None, 'Cannot sign !!!', '<h2>{}</h2>'.format(msg_err)) raise TypeError(msg_err) return RSA([self.pv_key, self.pb_key], self.interface).encrypt(txt)
def use_menu(func): global menu_choice try: print('Press ctrl + C to back to menu, anytime.') func() menu_choice = False except KeyboardInterrupt: cl_out(c_error, '\nKeyboard interrupt.\nBack menu ...') menu_choice = False except MemoryError: cl_out(c_error, 'Memory Error.\nBack menu ...') except Exception as ept: cl_out(c_error, 'An error occurred : ' + str(ept) + '.\nBack menu ...') menu_choice = False
def decryptFile(self, fn_in, fn_out): ''' Decrypt the file `fn_in` which was encrypted with self.encryptFile. - fn_in : the name of the file to encrypt ; - fn_out : the name of the output encrypted file. ''' #------Read AES key from file and remove it. with open(fn_in, 'r+b') as f: #https://stackoverflow.com/a/10289740 f.seek(0, os.SEEK_END) pos = f.tell() - 1 while pos > 0 and f.read(1) != b'\n': pos -= 1 f.seek(pos, os.SEEK_SET) if pos > 0: f.seek(pos, os.SEEK_SET) AES_key_c = f.read() f.seek(pos, os.SEEK_SET) f.truncate() #------AES key try: AES_key = self.RSA_ciph.decrypt( (AES_key_c.decode()).replace('\n', '')) except Exception as err: print(err) with open(fn_in, 'ab') as f: f.write(AES_key_c) return -1 #------decrypt text try: AES_cipher = AES(self.AES_mode, AES_key, False, encoding=self.encod) except ValueError as err: msg = 'You did NOT selected the right RSA key !!!' if self.interface == None: print(msg) elif self.interface == 'console': cl_out(c_error, msg) else: QMessageBox.critical(None, 'Bad RSA key !!!', '<h2>{}</h2>'.format(msg)) raise ValueError(msg) AES_cipher.decryptFile(fn_in, fn_out) #------Rewrite the key in the file, for future decryptions with open(fn_in, 'ab') as f: f.write(AES_key_c)
def __init__(self, keys, interface=None): '''Initiate the RSA object. .keys : the keys. Should be of the form ((e, n), (d, n)) i.e. (pb_key, pv_key), or 'name' ; .interface : the interface using this function. Should be None, 'gui', or 'console'. Used to choose the progress bar. If 'keys' is a string, use RsaKeys to read the keys. If a key is unknown, set it to None [i.g. : ((e, n), None)]. Both can't be None. ''' if interface not in (None, 'gui', 'console'): raise ValueError('The argument "interface" should be None, "gui", \ or "console", but {} of type {} was found !!!'.format(interface, type(interface))) self.interface = interface self.keys_init = keys self.keys = {} #will contain the keys if type(keys) == str: try: self.keys['e'] = RsaKeys(keys, interface=self.interface).get_key(0) #self.keys['d'] = RsaKeys(keys, interface=self.interface).get_key(1) self.keys['d'] = None except FileNotFoundError as err: if interface == 'console': cl_out(c_error, err) elif interface == 'gui': QMessageBox.critical(None, 'Keys not found !!!', '<h2>{}</h2>'.format(err)) raise FileNotFoundError(err) except TypeError: #pbk keys self.keys['d'] = None elif type(keys) in (tuple, list, set): #-check the length for j, k in enumerate(keys): if k != None: if len(k) != 2: raise ValueError('The argument "keys" should have two lists of length 2, but "{}", with a length of {} was found !!!'.format(k, len(k))) if j > 1: raise ValueError('The argument "keys" should have a length of 2, but "{}", with a length of {} was found !!!'.format(keys, len(keys))) if keys[0] == keys[1] == None: raise ValueError("Both keys can't be None !!!") self.keys['e'] = keys[0] self.keys['d'] = keys[1] else: raise TypeError('The argument "keys" should be a string or a list, but "{}" of type "{}" was found !!!'.format(keys, type(keys))) self.pb_key = self.keys['e'] self.pv_key = self.keys['d']
def decrypt(self, txt): '''Return the decrypted text txt with the private key self.pv_key.''' if self.pv_key == None: try: self.keys['d'] = RsaKeys(self.keys_init, interface=self.interface).get_key(1) self.pv_key = self.keys['d'] except TypeError: msg_err = 'Cannot decrypt with an empty key !!!' if self.interface == 'console': cl_out(c_error, msg_err) elif self.interface == 'gui': QMessageBox.critical(None, 'Cannot decrypt !!!', '<h2>{}</h2>'.format(msg_err)) raise TypeError(msg_err) #------ini progress bar if self.interface == 'gui': pb = GuiProgressBar(title='Decrypting ... | RSA ― Cracker', verbose=True) elif self.interface == 'console': pb = ConsoleProgressBar() #------ini d, n = self.pv_key grp_size = len(str(n)) - 1 if type(txt) == str: l_txt = txt.split(' ') else: l_txt = txt.split(b' ') #------decrypt l_txt_decrypted = [] for j, k in enumerate(l_txt): i = int(k) l_txt_decrypted.append(pow(i, d, n)) #todo: use math.pow ? #---progress bar if self.interface in ('gui', 'console'): pb.set(j, len(l_txt)) # len(l_txt) - 1 for k in range(len(l_txt_decrypted)): #add 0. ex : 111 -> 0111 l_txt_decrypted[k] = str(l_txt_decrypted[k]) while len(l_txt_decrypted[k]) < grp_size: #% 4 != 0: l_txt_decrypted[k] = '0' + l_txt_decrypted[k] decoded_txt = MsgForm(l_txt_decrypted).decode() ret = '' for k in decoded_txt: ret += str(k) #print(ret) #ret = rest_encod(ret) #print(rest_encod(ret)) #print(ret) # #todo: this don't work : the print works well (if you encrypt "é", and decrypt it it will print "é"), but ret is not "é" return ret.strip('\x00')
def use(cracker=cracker): """Use prima fonctions. Beautiful menu thanks to Lasercata""" c = '' while c not in ('0', 'quit', tr('exit'), 'q'): if cracker: color(c_succes) print('') print('\\' * 50) if cracker: color(c_prog) print('\n' + tr('Prima menu :') + '\n') if cracker: color(c_error) print(' 0.' + tr('Main menu')) else: print(' 0.' + tr('Exit')) if cracker: color(c_succes) print(' ' + '-' * 16) if cracker: color(c_wrdlt) print(' ' + tr('Decomposition of a number as a product of prime factors')) if cracker: color(c_ascii) print(' 1 : ' + tr('Trial division')) print(' 2 : ' + tr('Wheel factorization')) print(' 3 : ' + tr("Fermat's factorization")) print(' 4 : ' + tr("Pollard's rho")) print(' 5 : ' + 'p - 1') if cracker: color(c_succes) print(' ' + '-' * 16) if cracker: color(c_wrdlt) print(' ' + tr("Probabilistic primality's test")) if cracker: color(c_ascii) print(' 6 : ' + tr("Fermat's test")) print(' 7 : ' + tr("Miller-Rabin's test")) if cracker: color(c_succes) print(' ' + '-' * 16) if cracker: color(c_wrdlt) print(' ' + tr('Sieves to find prime numbers')) if cracker: color(c_ascii) print(' 8 : ' + tr('Sieve of Erathostenes')) print(' 9 : ' + tr('Segmented sieve of Erathostenes')) c = '' if cracker: c = cl_inp('\n' + tr('Your choice : ')) else: c = input('\n' + tr('Your choice : ')) if c not in ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'q'): prnt = '"' + c + '" ' + tr('is NOT an option of this menu !') if cracker: cl_out(c_error, prnt) else: print(prnt) if c in ('1', '2', '3', '4', '5', '6', '7'): if cracker: n = inp_int(tr('Enter the integer number : ')) else: n = int(input(tr('Enter the integer number : '))) if c != '0': t1 = datetime.now() dct = { '1': tr('Trial division'), '2': tr('Wheel factorization'), '3': tr("Fermat's factorization"), '4': tr("Pollard's rho"), '5': 'p - 1', '6': tr("Miller-Rabin's test"), '7': tr("Fermat's test"), '8': tr('Sieve of Erathostenes'), '9': tr('Segmented sieve of Erathostenes') } t1 = datetime.now() if c == '7': if cracker: nt = inp_int( tr('Number of tests (Error = 0.25 ^ number of tests) : ' )) else: nt = int( input( tr('Number of tests (Error = 0.25 ^ number of tests) : ' ))) txt = to_str(dct['7'], n, nt) else: if c in ('8', '9'): if cracker: n = inp_int(tr('Limit : ')) else: n = int(input(tr('Limit : '))) if c == '8': f = basic_erathostenes_sieve else: f = segmentation_erathostenes_sieve L = f(n) txt = "" else: txt = to_str(dct[c], n) t = datetime.now() - t1 print(txt) if c in ('1', '2', '3', '4', '5', '6', '7', '8', '9'): if cracker: cl_out(c_succes, tr('Realised in ') + str(t)) else: print(tr('Realised in ') + str(t)) if c in ('8', '9'): print(tr('Length of the list :'), len(L)) ans = input(tr('Write the prime numbers in a file ? ')) if ans in (tr('y'), tr('Y'), tr('yes'), tr('Yes'), tr('YES')): nf = input( tr('Name of the file (a file of the same name will be erase) : ' )) f = open(nf, 'w') for k in L: f.write(str(k) + "\n") f.close() else: if len(L) < 1000: ans = input(tr('Print the list on the screen ? ')) if ans in (tr('y'), tr('Y'), tr('yes'), tr('Yes'), tr('YES')): for k in L: print(k) if cracker: color(c_wrdlt) input(tr('---End---')) if cracker: color(c_prog)
def change_pwd(self, old_pwd, new_pwd): ''' Change the RSA key password for `self.k_name`. Return : -1 if the RSA key is not encrypted ; -2 if the RSA key file is not well formatted ; -3 if the old_pwd is wrong ; None otherwise. ''' fn = self.get_fn('pvk') if fn[-4:] != '.enc': msg = tr('The RSA key is not encrypted !') if self.interface == 'gui': QMessageBox.critical(None, '!!! Not encrypted !!!', '<h2>{}</h2>'.format(msg)) elif self.interface == 'console': cl_out(c_error, msg) else: print('Cracker: RsaKeys: change_pwd: ' + msg) return -1 old_path = chd_rsa(glb.home) with open(fn, 'r') as f: f_content = f.read() try: f_dec = AES(256, old_pwd, hexa=True).decryptText(f_content, mode_c='hexa') except UnicodeDecodeError: msg = tr('This is not the good password !') if self.interface == 'gui': QMessageBox.critical(None, '!!! Wrong password !!!', '<h2>{}</h2>'.format(msg)) elif self.interface == 'console': cl_out(c_error, msg) else: print('Cracker: RsaKeys: change_pwd: ' + msg) chdir(old_path) return -3 except ValueError: msg = tr('The file is not well formatted !') if self.interface == 'gui': QMessageBox.critical(None, '!!! File error !!!', '<h2>{}</h2>'.format(msg)) elif self.interface == 'console': cl_out(c_error, msg) else: print('Cracker: RsaKeys: change_pwd: ' + msg) chdir(old_path) return -2 f_enc = AES(256, new_pwd, hexa=True).encryptText(f_dec, mode_c='hexa') with open(fn, 'w') as f: f.write(f_enc) chdir(old_path)
def crack(self, txt): '''Try to crack 'txt' using some wordlists.''' self.pb_sender = 'crack' #------test 1 self._pb_set(0, 7, 0) if self.verbose: print('Test 1/7 ― Week passwords list ― {} values'.format( len(week_pwd))) for j, k in enumerate(week_pwd): if self.func(k) == txt: return k if self.interface != None: self._pb_set(j, len(week_pwd), 1) #------test 2 if self.verbose: print('Test 2/7 ― Keyboard sequence ― 1300*4 + 8*20 = 5360 values') for alf in ('azertyuiopqsdfghjklmwxcvbn', 'AZERTYUIOPQSDFGHJKLMWXCVBN', 'qwertyuiopasdfghjklzxcvbnm', 'QWERTYUIOPASDFGHJKLZXCVBNM', '0123456789', """"²&é"'(-è_çà)=""", '0123456789°+', 'azertyuiop^$qsdfghjklmù*wxcvbn,;:!'): ret = self._keyboard_seq(txt, alf) if ret != None: return ret self._pb_set(2, 7, 0) #------test 3 if self.verbose: print('Test 3/7 ― 1-4 letters a-z ― 475 255 values') for lth in range(1, 5): ret = self.permutation(txt, lth, 'abcdefghijklmnopqrstuvwxyz') if ret != None: return ret self._pb_set(3, 7, 0) #------test 4 if self.verbose: print('Test 4/7 ― 1-4 letters A-Z ― 475 255 values') for lth in range(1, 5): ret = self.permutation(txt, lth, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') if ret != None: return ret self._pb_set(4, 7, 0) #------test 5 if self.verbose: print('Test 5/7 ― 1-6 numbers ― 1 111 110 values') for lth in range(1, 7): ret = self.permutation(txt, lth, '0123456789') if ret != None: return ret self._pb_set(5, 7, 0) #------test 6 if self.verbose: print('Test 6/7 ― 1-3 all ― 6 895 291 values') for lth in range(1, 4): ret = self.permutation( txt, lth, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 _&é~"#\'\\{([-|è`ç^à @)°]=+}$£¤¨ù%*µ!§:/.;?,<>²' ) if ret != None: return ret self._pb_set(6, 7, 0) #------test 7 if self.verbose: print('Test 7/7 ― Wordlists :') old_path = chd_wrdlst() wlsts = list_files() if len(wlsts) == 0: msg = 'The wordlists were not found !!!' if self.interface == None: print(msg) elif self.interface == 'console': cl_out(c_error, msg) else: QMessageBox.critical(None, '!!! Wordlists not found !!!', '<h2>{}</h2>'.format(msg)) elif self.verbose: for k in wlsts: if k != wlsts[-1]: print("\t- '{}' ;".format(k)) else: print("\t- '{}'.".format(k)) else: for k, w in enumerate(wlsts): try: ret = BruteForce(self.func, w, interface=self.interface).crack(txt) except UnicodeDecodeError: ret = BruteForce(self.func, w, encod='cp437', interface=self.interface).crack(txt) if ret != None: chdir(old_path) return ret self._pb_set(k, len(wlsts), 1) if self.verbose: print('Tests finished ― password not found.') chdir(old_path) self._pb_set(7, 7, 0) self.pb_sender = None
def read(self, mode='all', also_ret_pwd=False): ''' Try to read the content of the file `[self.k_name] + ext`. - mode : the self.get_fn mode. in ('pvk', 'pbk', 'all'). Default is 'all' ; - also_ret_pwd : a bool indicating if also return the password. If True, return the password at the end of the return tuple. Return : (pbk, pvk), (p, q, n, phi, e, d), (n_strth, date_) if it's a *.pvk-* file ; pbk, (n, e), (n_strth, date_) if it's a *.pkb-* file ; -1 if not found ; -2 if file not well formatted ; -3 if password is wrong or if canceled. ''' #------other def err_not_well_formated(): msg = tr('The file is not well formatted !') if self.interface == 'gui': QMessageBox.critical(None, '!!! File error !!!', '<h2>{}</h2>'.format(msg)) elif self.interface == 'console': cl_out(c_error, msg) else: print('Cracker: RsaKeys: read: ' + msg) return -2 #------Get filename try: fn, md = self.get_fn(mode, also_ret_md=True) except FileNotFoundError: msg = tr('File not found !') if self.interface == 'gui': QMessageBox.critical(None, '!!! Not found !!!', '<h2>{}</h2>'.format(msg)) elif self.interface == 'console': cl_out(c_error, msg) else: print('Cracker: RsaKeys: read: ' + msg) return -1 #------Read file old_path = chd_rsa(glb.home) with open(fn, 'r') as f: f_content = f.read() chdir(old_path) #------Decrypt content, if encrypted if fn[-4:] == '.enc': #---Get password if self.interface == 'gui': pwd = AskPwd.use() elif self.interface == 'console': pwd_clear = getpass(tr('RSA key password :'******'sha256').hash(pwd_clear) else: pwd_clear = input('RSA key password :'******'sha256').hash(pwd_clear) if pwd == None: return -3 # Canceled by user #---Decrypt try: f_content_dec = AES(256, pwd, hexa=True).decryptText(f_content, mode_c='hexa') except UnicodeDecodeError: msg = tr('This is not the good password !') if self.interface == 'gui': QMessageBox.critical(None, '!!! Wrong password !!!', '<h2>{}</h2>'.format(msg)) elif self.interface == 'console': cl_out(c_error, msg) else: print('Cracker: RsaKeys: read: ' + msg) return -3 except ValueError: return err_not_well_formated() else: f_content = f_content_dec else: pwd = None try: infos = literal_eval(f_content) except SyntaxError: return err_not_well_formated() #------Read and return infos if md[0] == 'pbk': try: date_, n_strth = infos['date'], infos['n_strenth'] e, n = infos['e'], infos['n'] except KeyError: return err_not_well_formated() if md[1] == 'hexa': #convert in decimal n_strth = str(int(n_strth, 16)) e, n = str(int(e, 16)), str(int(n, 16)) pbk = str(e) + ',' + str(n) if also_ret_pwd: return (pbk,), (n, e), (n_strth, date_), pwd return (pbk,), (n, e), (n_strth, date_) else: try: date_, n_strth = infos['date'], infos['n_strenth'] p, q, n, phi, e, d = infos['p'], infos['q'], infos['n'], infos['phi'], infos['e'], infos['d'] except KeyError: return err_not_well_formated() if md[1] == 'hexa': #convert in decimal n_strth = str(int(n_strth, 16)) p, q, n, phi, e, d = str(int(p, 16)), str(int(q, 16)), \ str(int(n, 16)), str(int(phi, 16)), str(int(e, 16)), str(int(d, 16)) pvk = str(d) + ',' + str(n) pbk = str(e) + ',' + str(n) chdir(old_path) if also_ret_pwd: return (pbk, pvk), (p, q, n, phi, e, d), (n_strth, date_), pwd return (pbk, pvk), (p, q, n, phi, e, d), (n_strth, date_)
def __init__(self, fn, w_lth, alf, binary=True, encod='utf-8', interface=None): ''' Initiate the WordlistGenerator object. fn : the wordlist's file name ; w_lth : the words' length. Should be an int ; alf : the alphabet to use. If type = str and in alfs, use the corresponding alphabet ; binary : Should be a boolean. Correspond to the binary mode while writting ; encod : the file's encoding ; interface : the interface using this function. Should be None, 'gui', or 'console'. Used to choose the progress bar. ''' #------check values if binary not in (True, False): raise ValueError('The argument "binary" should be a boolean, but \ "{}" of type "{}" was found !!!'.format(binary, type(binary))) if interface not in (None, 'gui', 'console'): raise ValueError('The argument "interface" should be None, "gui", \ or "console", but {} of type {} was found !!!'.format(interface, type(interface))) if type(alf) not in (str, list, set, tuple): raise ValueError('The argument "alf" should be an iterable, but a \ "{}" found !!!'.format(type(alf))) if type(w_lth) != int: raise ValueError('The argument "w_lth" should be an int, but a "{}" \ was found !!!'.format(type(w_alf))) #------check if the file already exist if isfile(fn): #os.path.isfile msg = 'The file "{}" already exist !!!'.format(fn) if interface == None: raise FileExistsError(msg) elif interface == 'console': cl_out(c_error, msg) raise FileExistsError(msg) else: QMessageBox.critical(None, '!!! File already exist !!!', '<h2>{}</h2>'.format(msg)) raise FileExistsError(msg) #------initiate the self values if type(alf) == str and alf in alfs: self.alf = alfs[alf] else: self.alf = alf self.fn = fn self.w_lth = w_lth self.binary = binary self.encod = encod self.interface = interface #------others values self.alf_lth = len(self.alf) self.wrdlst_lth = self.alf_lth **self.w_lth self.size = self.wrdlst_lth * (self.w_lth + 2) #the number of characters. +2 bc of the CRLF. self.nb_rep = sum(self.alf_lth**k for k in range(self.w_lth - 1)) self.new_l = ('\n', b'\n')[self.binary]
def __str__(self): '''Return the analysis in a readable string.''' try: ana = self.analysis #don't analyse again if already done except AttributeError: ana = self.ana() if ana == -1: msg_err = tr('The file "{}" was NOT found !!!').format(self.fn) elif ana == -2: msg_err = tr('Bad encoding "{}" for the file "{}"').format( self.encod, self.fn) if ana in (-1, -2, -3): if self.interface == None: raise FileNotFoundError(msg_err) elif self.interface == 'console': cl_out(c_error, msg_err) return ana elif self.interface == 'gui': QMessageBox.critical(None, tr('!!! File error !!!'), msg_err) return ana sizes = ana[0] times = ana[1] infos = ana[2] lib_C = ana[3][0] infosLibC = ana[3][1] ret = tr('Filename : {} ;').format(self.fn) ret += '\n\n' + tr('Size : {} ({}) ;').format(*sizes) ret += '\n\n' + tr('Last modification : {} ;').format(times[0]) ret += '\n' + tr('Last access : {} ;').format(times[1]) ret += '\n' + tr('Creation : {} ;').format(times[2]) if lib_C: ret += '\n\n' + tr('Number of characters : {} ;').format( infosLibC['nb_car']) ret += '\n\n' + tr('Minimum line length : {} characters ;').format( infos['min']) ret += '\n' + tr('Maximum line length : {} characters ;').format( infos['max']) if lib_C: ret += '\n' + tr('Average line length : {} characters ;').format( infosLibC['av_len']) ret += '\n' + tr('Median line length : {} characters ;').format( infosLibC['med_len']) ret += '\n' + tr("Wordlist's length : {} lines ;").format( space_b(infos['nb_lines'])) if lib_C: ret += '\n' + tr('Wordlength repartition :') for k in infosLibC['dct_len_w']: ret += "\n\t'{}': {} ;".format( k, space_b(infosLibC['dct_len_w'][k])) ret += '\n\n' + tr('Length of the alphabet : {} characters ;').format( infos['alf_lth']) ret += '\n' + tr('Alphabets : {} ;').format( set_prompt(infos['lst_alf'])) ret += '\n\n' + tr('Number of differents characters : {} ;').format( infos['nb_occ']) ret += '\n' + tr("Characters' repartition :") for k in infos['dct_occ']: ret += "\n\t'{}': {} ;".format(k, space_b(infos['dct_occ'][k])) ret = ret[:-2] + '.' #replace ' ;' by '.' at the last line. return ret
def _calc_nb(self, p, q, verbose=False): ''' Return n, phi, e, d. p and q are prime numbers. ''' if verbose: print('\nCalculating numbers ...') t1 = dt.now() #------ini progress bar if self.interface == 'gui': pb = GuiProgressBar(title='Generating ... ― Cracker', undetermined=True) elif self.interface == 'console': pb = ConsoleProgressBar() if p > q: p, q = q, p # p will be smaller than q (p < q). n = p * q phi = (p - 1) * (q - 1) if verbose: cl_out(c_succes, 'n found !\n') i = 0 # e : p, q < e < phi, pgcd(n, e) = 1 if verbose: print('\nSearching e ...\n') e = 0 while math.gcd(e, phi) != 1: e = randint(q, phi) if self.interface in ('gui', 'console'): pb.load() print('\b \b') if verbose: t_e = dt.now() - t1 msg1 = 'e found in {} s.'.format(t_e) cl_out(c_succes, msg1 + '\n') print('\nSearching d ...\n') t2 = dt.now() d = mult_inverse(e, phi) if verbose: t_d = dt.now() - t2 t_t = dt.now() - t1 msg = 'd found in {} s.\nTime elapsed : {} s.'.format(t_d, t_t) cl_out(c_succes, msg) if self.interface == 'gui' and verbose: QMessageBox.about(None, 'Done !', '<h2>{}</h2>\n<h2>{}</h2>'.format(msg1, msg)) return n, phi, e, d