Ejemplo n.º 1
0
def generateMAC(message, key):
    padding = ""
    endblock = ""
    (K1, K2) = generateSubkeys(key, "\x00\x00\x00\x00\x00\x00\x00\x1b")
    #print K1.encode("hex")
    #print K2.encode("hex")
    if len(message) % 8:
        padLen = 8 - (len(message) % 8)
        padding = "\x80" + ("\x00" * (padLen - 1))
        message = message + padding
        endblock = message[-8:len(message)]
        XORencryptor = XOR.XORCipher(K2)
        endblock = XORencryptor.encrypt(endblock)
    else:
        endblock = message[-8:len(message)]
        XORencryptor = XOR.XORCipher(K1)
        endblock = XORencryptor.encrypt(endblock)
    message = message[0:-8] + endblock
    CMACencryptor = DES3.new(key, DES3.MODE_CBC,
                             '\x00\x00\x00\x00\x00\x00\x00\x00')
    mac = CMACencryptor.encrypt(message)
    #print key.encode("hex")
    #print message.encode("hex")
    #print mac.encode("hex")
    #return mac
    return mac[-8:len(mac)]
Ejemplo n.º 2
0
def encrypt_url(path, dl_filename=None):
    """
    Call this within your client app to generate a URL to query the
    Cryptostream WSGI app server with.
    
    path: (str) The URL path to the internal-flagged location
        on the Nginx server that the files will be served from via
        X-Accel-Redirect.
    dl_filename: (str/None) If specified, the file that the user downloads will
        be named according to the value, instead of from the name on 
        the filesystem.
    """
    # Encrypt the path and the timestamp.
    path = XOR.new(KEY).encrypt(path)
    ts = XOR.new(KEY).encrypt(time.time().__str__())
    # Encode path/ts to base 64.
    path = base64.b64encode(path)
    ts = base64.b64encode(ts)

    # This dict will get urlencoded as GET keywords.
    value_dict = {"path": path, "ts": ts}

    # Check for download filename override.
    if dl_filename:
        value_dict["dl_filename"] = dl_filename

    return urllib.urlencode(value_dict)
Ejemplo n.º 3
0
def initvars():
	global Logueado
	Logueado = False
	config = ConfigParser()
	config.read("conf/config.ini")
	tipo = config.get('CUENTA', 'Tipo')
	ps = b64decode('MjAxMDE3MzMtOTYwOTkyNg==')
	xorps = XOR.new(str(ps))
	global Tipo
	Tipo = xorps.decrypt(b64decode(str(tipo)))
	webserver = config.get('WEB', 'srv')
	ps = b64decode('MjAxMDE3MzMtOTYwOTkyNg==')
	xorps = XOR.new(str(ps))
	global WEBServer
	WEBServer = xorps.decrypt(b64decode(str(webserver)))
	print WEBServer
	global DatosUsuario
	DatosUsuario = {}
	global DictSenales
	DictSenales = {}
	global BD
	BD = BasedeDatos()
	BD.Conectar()
	global DictColaResultados
	DictColaResultados = {}
	t = threading.Thread(target=GetIps)
	t.start()
Ejemplo n.º 4
0
def initvars():
    global Logueado
    Logueado = False
    config = ConfigParser()
    config.read("conf/config.ini")
    tipo = config.get('CUENTA', 'Tipo')
    ps = b64decode('MjAxMDE3MzMtOTYwOTkyNg==')
    xorps = XOR.new(str(ps))
    global Tipo
    Tipo = xorps.decrypt(b64decode(str(tipo)))
    webserver = config.get('WEB', 'srv')
    ps = b64decode('MjAxMDE3MzMtOTYwOTkyNg==')
    xorps = XOR.new(str(ps))
    global WEBServer
    WEBServer = xorps.decrypt(b64decode(str(webserver)))
    print WEBServer
    global DatosUsuario
    DatosUsuario = {}
    global DictSenales
    DictSenales = {}
    global BD
    BD = BasedeDatos()
    BD.Conectar()
    global DictColaResultados
    DictColaResultados = {}
    t = threading.Thread(target=GetIps)
    t.start()
Ejemplo n.º 5
0
def encrypt(hstr, payload, encryptionKey):
    hstr = XOR.new(encryptionKey).encrypt(hstr)
    hstr = base64.b64encode(hstr)

    payload = XOR.new(encryptionKey).encrypt(payload)
    payload = base64.b64encode(payload)

    return [hstr, payload]
Ejemplo n.º 6
0
def xor_encode_dict(dictionary):
    """ Кодирует словарь алгоритмом XOR """
    result = {}
    for key, val in dictionary.iteritems():
        key = base64.encodestring(XOR.new(settings.XOR_KEY).encrypt(key))
        val = base64.encodestring(XOR.new(settings.XOR_KEY).encrypt(val))
        result[key] = val

    return result
Ejemplo n.º 7
0
def main():
  key = b"The secret key"

  # Encryption
  encryption_suite = XOR.new(key)
  cipher_text = encryption_suite.encrypt(b"Hello world!")
  print(cipher_text)

  # Decryption
  decryption_suite = XOR.new(key)
  plain_text = decryption_suite.decrypt(cipher_text)
  print(plain_text)
Ejemplo n.º 8
0
 def _getMAC(self, mac, key):
     modName = self.macMap[mac]
     if not modName:
         return None
     mod = __import__(modName, {}, {}, '')
     if not hasattr(mod, 'digest_size'):
         ds = len(mod.new().digest())
     else:
         ds = mod.digest_size
     key = key[: ds]+'\x00'*(64-ds)
     i = XOR.new('\x36').encrypt(key)
     o = XOR.new('\x5c').encrypt(key)
     return mod, i,o, ds
Ejemplo n.º 9
0
 def _getMAC(self, mac, key):
     modName = self.macMap[mac]
     if not modName:
         return None
     mod = __import__(modName, {}, {}, '')
     if not hasattr(mod, 'digest_size'):
         ds = len(mod.new().digest())
     else:
         ds = mod.digest_size
     key = key[:ds] + '\x00' * (64 - ds)
     i = XOR.new('\x36').encrypt(key)
     o = XOR.new('\x5c').encrypt(key)
     return mod, i, o, ds
Ejemplo n.º 10
0
def app(environ, start_response):
    """
    WSGI app method. You'll want to point your WSGI server at this method.
    """
    data = environ["PATH_INFO"]
    # GET querystring.
    qs = urlparse.parse_qs(environ["QUERY_STRING"])

    # Decode from base64.
    try:
        path = base64.b64decode(qs["path"][0])
        ts = base64.b64decode(qs["ts"][0])
    except:
        return render_error_page(environ, start_response)

    # Decrypt using XOR.
    try:
        path = XOR.new(KEY).decrypt(path)
        ts = datetime.datetime.fromtimestamp(float(XOR.new(KEY).decrypt(ts)))
    except:
        return render_error_page(environ, start_response)

    # Determine what the file will be named for the user's browser.
    if qs.has_key("dl_filename"):
        # Filename was passed as a GET keyword.
        dl_filename = qs["dl_filename"][0]
    else:
        # No filename specified, use the name on the filesystem.
        dl_filename = os.path.basename(path)

    dbg = path
    now = datetime.datetime.now()
    if (now - ts) > LINK_EXPIRE_TDELTA:
        # Expired, show vague error page.
        return render_error_page(environ, start_response)
    else:
        # Everything is good, serve the file through X-Accel-Redirect.
        status = "200 OK"

        response_headers = [
            ("X-Accel-Redirect", path),
            ("Content-Disposition", "attachment; filename=%s" % dl_filename),
        ]

        start_response(status, response_headers)
        # This needs to be an empty string or we'll get premature socket
        # closing errors. The body is ignored by Nginx, and the connection is
        # closed before this returned value can be read, causing the error.
        return ""
Ejemplo n.º 11
0
 def encrypt(self, timerPrinting=False):
     """To give the Order To Encrypt The File"""
     t = time.time()
     #Check If The File is
     if self.extension not in self.path:
         with open(self.path, 'rb') as file:
             file_data = file.read()
         #Start To CHecking The PlatForm
         # if platform.system() == "Windows":
         # 	self.path_dir = self.path.split("\\")[-1]
         # elif platform.system() == "Linux":
         # 	self.path_dir = self.path.split('/')[-1]
         # #End Checking Wich Platform
         # print('Encryption of '+self.path_dir+'...')
         # print('It\'s may take a will')
         ######################### XOR Algorithm #########################
         cipher = XOR.new(self.key)
         self.encoded = base64.b64encode(cipher.encrypt(file_data))
         #################################################################
         #print('writing in you file ...')
         os.remove(self.path)
         with open(str(self.path) + self.extension, "wb") as outfile:
             outfile.write(self.encoded)
         if timerPrinting:
             print('Done In ' + str(time.time() - t))
         else:
             pass
     else:
         print("The File is already encrypt")
Ejemplo n.º 12
0
    def initiate_session(self):
        # Perform the initial connection handshake for agreeing on a shared secret 

        ### TODO: Your code here!
        # This can be broken into code run just on the server or just on the client
        if self.server or self.client:
            my_public_key, my_private_key = create_dh_key()
            # Send them our public key
            self.send(bytes(str(my_public_key), "ascii"))
            # Receive their public key
            their_public_key = int(self.recv())
            # Obtain our shared secret
            shared_hash = calculate_dh_secret(their_public_key, my_private_key, key_len=64)
            print("Shared session key: {}".format(binascii.hexlify(shared_hash)))

            # The first 256 bit from shared hash is the key of hmac
            self.hmac = HMAC.new(shared_hash[:32], digestmod=SHA256)

            # TODO: exchange iv
            # TODO: use a global bloom filter to avoid iv re-use in a reasonable time period,
            # and we can add a time stamp after iv to avoid replay if the iv filter is reset

            # The last 256 bit from shared hash is the key of hmac
            cipher_key = shared_hash[:-32]
            # TODO: init cipher with aes-cfb using cipher_key and iv
            # Default XOR algorithm can only take a key of length 32
            self.cipher = XOR.new(shared_hash[:4])
Ejemplo n.º 13
0
def get_key(request):
	if (request.method != 'POST'):
		return err_GE002()
	form = GetKeyForm(request.POST)
	if (not form.is_valid()):
		return err_GE031(form)
	
	#dbkey = get_user_key(request, ss=form.cleaned_data['secret'])
	db_secret = request.device_assn.db_secret
	xor = XOR.new(base64.b64decode(form.cleaned_data['secret']))
	db_key = xor.encrypt(base64.b64decode(db_secret))
	
	if (not request.device_assn.verify_db_key(db_key)):
		return err_GE022()
	
	# Okay, we need to test the validity of this key before we return it.
	# Otherwise, we could return an invalid key.

	response = {
			'data': {
					'key':base64.b64encode(db_key),
#					'gcm_project_id': settings.GCM_PROJECT_ID
				},
			'warnings':{}
		}
	return HttpResponse(content=json.dumps(response), mimetype='application/json')
Ejemplo n.º 14
0
    def encrypt(self, key, plaintext):
        (input_whitening_key, output_whitening_key) = self.build_whitening_keys(key)

        input_whitener = XOR.new(str(input_whitening_key)).encrypt
        output_whitener = XOR.new(str(output_whitening_key)).encrypt
        ciphertext = bytearray(len(plaintext))

        if (len(plaintext) % 8):
            raise Exception("plaintext length must be a multiple of 8")

        des = DES.new(str(key[0:8]), DES.MODE_CBC, str(bytearray(8))).encrypt
        for i in range(len(plaintext)/8):
            ciphertext[i*8:i*8+8] = bytearray(output_whitener(des(input_whitener(str(plaintext[i*8:i*8+8])))))
            des = DES.new(str(key[0:8]), DES.MODE_CBC, str(bytearray(8))).encrypt

        return ciphertext
Ejemplo n.º 15
0
 def xor_decrypt(raw):
     if cipher[0] is None:
         if len(raw) < AES.block_size:
             return None, 0
         cipher[0] = XOR.new(raw[: AES.block_size])
         return None, AES.block_size
     return cipher[0].decrypt(raw), len(raw)
Ejemplo n.º 16
0
def decifra():
    mensagem = raw_input("Digite aqui a mensagem a ser decifrada: ")
    mensagem1 = mensagem.decode('hex')
    senha = raw_input("Digite a senha: ")
    xor2 = XOR.new(senha)
    mensagem_decifrada = xor2.decrypt(mensagem1)
    print mensagem_decifrada
Ejemplo n.º 17
0
	def ObtenerConexion(self):
		config = ConfigParser()
		config.read("conf/config.ini")
		self.conexion = config.get('REMOTE', 'conexion')
		ps = b64decode('MjAxMDE3MzMtOTYwOTkyNg==')
		xorps = XOR.new(str(ps))
		self.conexion = xorps.decrypt(b64decode(str(self.conexion)))
Ejemplo n.º 18
0
def try_to_find_config(
    data_provider,
    mode=SearchMode.ALL,
    hint_key=None,
):
    """ try all the XOR magic to find data looking like config """

    if mode in (SearchMode.PACKED, SearchMode.ALL):
        logger.debug("MODE == PACKED")
        keys_to_test = range(0xff) if hint_key is None else [hint_key]
        for cur_key in keys_to_test:
            logger.debug(f"TESTING KEY = {cur_key}")
            _xor_array_fn = lambda arr, key=cur_key: XOR.new(bytes([key])
                                                             ).encrypt(arr)
            finder = AlmostLikeYara(CobaltCommons.PACKED_CONFIG_PATTERN,
                                    encoder=_xor_array_fn)
            result = data_provider.find_using_func(finder.smart_search)
            if result != NOT_FOUND:
                data_provider.set_encoder(_xor_array_fn)
                logger.debug(f"Found config @ 0x{result:08X} , key={cur_key}")
                return data_provider, SearchMode.PACKED

    if mode in (SearchMode.UNPACKED, SearchMode.ALL):
        logger.debug("MOD == UNPACKED")
        finder = AlmostLikeYara(CobaltCommons.UNPACKED_CONFIG_PATTERN)
        result = data_provider.find_using_func(finder.smart_search)
        if result != NOT_FOUND:
            logger.debug(f"Found config @ {result}")
            return data_provider, SearchMode.UNPACKED

    return None
Ejemplo n.º 19
0
def derive_transform_iv(src_blk, dst_blk, key):
    # Determine the IV required to encrypt `src_blk` to `dst_blk` using
    # AES-128-CBC with `key`. Assumes src_blk and dst_blk are one block
    # in size (128 bits/16 bytes)
    cipher = AES.new(key, AES.MODE_CBC, '\0' * AES_BLOCK_SIZE)
    dec = cipher.decrypt(dst_blk)
    return XOR.new(src_blk).encrypt(dec)
Ejemplo n.º 20
0
 def decrypt(self, timerPrinting=False):
     t = time.time()
     """To Give The Order To Decrypt The File"""
     if self.extension in self.path:
         with open(self.path, 'rb') as file:
             file_data = file.read()
         #Start To CHecking The PlatForm
         # if platform.system() == "Windows":
         # 	self.path = self.path.split("\\")[-1]
         # elif platform.system() == "Linux":
         # 	self.path = self.path.split('/')[-1]
         # End Checking Wich Platform
         # print("Decrypting of "+str(self.path)+"...")
         ############################################################################
         cipher = XOR.new(self.key)
         self.decoded = cipher.decrypt(base64.b64decode(file_data))
         ############################################################################
         self.path2 = self.path.replace(self.extension, "")
         os.remove(self.path)
         # print('Writing in Your File...')
         with open(self.path2, 'wb') as outfile:
             outfile.write(self.decoded)
         if timerPrinting:
             print('Done In ' + str(time.time() - t))
         else:
             pass
     else:
         print("The File is Not Encrypted To Decrypted")
Ejemplo n.º 21
0
	def InsertarBDRemote(self):
		print 'No existe cliente insertando'
		self.IPPublica = '0'
		try:
			self.IPPublica = urlopen('http://ip.42.pl/raw').read().encode('utf8')
		except:
			pass
		nameempresa = 'Desconocido'
		try:
			config = ConfigParser()
			config.read("conf/config.ini")
			string = config.get('BASE DE DATOS', 'conexion')
			ps = b64decode('MjAxMDE3MzMtOTYwOTkyNg==')
			xorps = XOR.new(str(ps))
			string = xorps.decrypt(b64decode(str(string)))	
			self.cnxn1 = pyodbc.connect(string)
			self.cursor1 = self.cnxn1.cursor()
			self.cursor1.execute("SELECT nombre FROM t365_Empresas WHERE master = 1")
			rows = self.cursor1.fetchall()
			if rows:
				nameempresa = rows[0].nombre
			self.cursor.execute("INSERT INTO [t365_Valid] ([namempresa],[mac],[namepc],[ip]) VALUES (?,?,?,?)",nameempresa,str(':'.join(['{:02x}'.format((uuid.getnode() >> i) & 0xff) for i in range(0,8*6,8)][::-1])),gethostname(),self.IPPublica)
			self.cnxn.commit()
		except:
			pass
Ejemplo n.º 22
0
 async def xorencrypt(self, ctx, data, key):
     """Uses XOR to encipher the given text with the given key."""
     encryption = XOR.new(key)
     encrypted_data = base64.b64encode(
         encryption.encrypt(data)).decode('utf-8')
     await ctx.send(
         f':white_check_mark: **Encrypted data**: {encrypted_data}')
Ejemplo n.º 23
0
def decrypt_list(proc_list, key):
    plain_list = []
    cipher = XOR.new(key)
    for ciphertext in proc_list[:-3]:
        if ciphertext:
            plain_list.append(cipher.decrypt(base64.b64decode(ciphertext)))
    return plain_list
def encrypt_file(filename, key):
    key = get_hashed_key(key.encode('utf-8'))

    try:
        file_handler = open(filename, 'rb')

        out_filename = filename + '.enc'
        out_file_handler = open(out_filename, 'wb')

        symmetric_key = XOR.new(key)

        while True:
            chunk = file_handler.read(1)
            if chunk:
                cipher_text = symmetric_key.encrypt(chunk)
                out_file_handler.write(cipher_text)
            else:
                break

        file_handler.close()
        out_file_handler.close()

    except FileNotFoundError:
        print('A file with this name could not be found !')
        exit(1)
Ejemplo n.º 25
0
 def decrypt(self, data):
     if len(data) % 16 != 0:
         raise ValueError(
             "Input strings must be a multiple of 16 in length")
     result = b''
     x = self.iv[16:32]
     y = self.iv[0:16]
     for i in range((len(data) - 1) // 16 + 1):
         input_block = data[i * 16:(i + 1) * 16]
         output_block = XOR.new(x).decrypt(input_block)
         output_block = self.aes.decrypt(output_block)
         output_block = XOR.new(y).decrypt(output_block)
         result += output_block
         x = output_block
         y = input_block
     return result
Ejemplo n.º 26
0
def decrypt_chunk(secret, fpath, queue):
    """
    @type secret: str
    @type fpath: str
    @type queue: multiprocessing.Queue
    """
    chunk_file = open(fpath.strip())
    chunk_pos_len = int(chunk_file.readline())
    chunk_pos = int(chunk_file.read(chunk_pos_len))
    initialization_vector_len = int(chunk_file.readline())
    initialization_vector = chunk_file.read(initialization_vector_len)
    data_hash_len = int(chunk_file.readline())
    data_hash = chunk_file.read(data_hash_len)
    enc_data_len = int(chunk_file.readline())
    enc_data = chunk_file.read(enc_data_len)
    if 16 != len(initialization_vector):
        raise Exception("initialization_vector len is not 16")

    #cipher = AES.new(secret, AES.MODE_CFB, IV=initialization_vector)
    cipher = XOR.new(secret)
    dec_data = cipher.decrypt(enc_data)
    calculated_hash = make_checksum(dec_data)
    if data_hash != calculated_hash:
        raise EncryptionHashMismatch("decrypt_file -> the decryption went wrong, hash didn't match")

    if queue.qsize() > 20:
        time.sleep(0.5)
    queue.put((chunk_pos, dec_data))
    return True
def decrypt_file(filename, key):
    key = get_hashed_key(key.encode('utf-8'))

    if not filename[len(filename) - 4:] == '.enc':
        print('Incorrect file extension : file must end in .enc')
        exit(1)

    try:
        file_handler = open(filename, 'rb')

        out_filename = 'DEC_' + filename[:-4]
        out_file_handler = open(out_filename, 'wb')

        symmetric_key = XOR.new(key)

        while True:
            chunk = file_handler.read(1)

            if chunk:
                plain_text = symmetric_key.decrypt(chunk)
                out_file_handler.write(plain_text)
            else:
                break

        file_handler.close()
        out_file_handler.close()

    except FileNotFoundError:
        print('A file with this name could not be found !')
Ejemplo n.º 28
0
    def decryptCTR(self, ctext):
        print()
        iv = ctext[:2*AES.block_size]
 #       print('iv:', iv)
        c = ctext[2*AES.block_size:]
        self.count = '0x' + iv
        cipher = AES.new(self.key,AES.MODE_ECB)
        bmsg=[]
        numBlocks = int(len(c)//(2*AES.block_size))
        if len(c)%AES.block_size!=0:
            numBlocks+=1
#        print('numBlocks:', numBlocks)
        msg=''
        for i in range(numBlocks):
            if i!=numBlocks:
                hexDigits = 2*AES.block_size
            else: hexDigits = len(c)%(2*AES.block_size)
            E = cipher.encrypt(bytes.fromhex(self.count[2:]))
  #          print('E:', E.hex())
            ct = c[AES.block_size*i:AES.block_size*i+hexDigits]
  #          print('ct:', ct)
     #       block=xorb(ct, E)
            xor = XOR.new(bytes.fromhex(ct))
            block = xor.decrypt(E)
            bmsg.append(block)
    #        print('block:', block.hex())
   #         print("block: ", block)
#            blocktext = bytes.fromhex(block)
#            print('blocktext:', blocktext)
            for byte in msg:
#                letter = chr(byte)
#               print('ltr:', letter)
                msg +=byte.decode()
            self.incCounter()
        return msg
Ejemplo n.º 29
0
def generateSubkeys(MACKey, constant):
    #create encrptor
    encryptor = DES3.new(MACKey, DES3.MODE_ECB,
                         '\x00\x00\x00\x00\x00\x00\x00\x00')
    XORencryptor = XOR.XORCipher(constant)

    K1 = ""
    K2 = ""
    zeros = "\x00" * 8  #8 bytes of zeros
    S = encryptor.encrypt(zeros)
    #print S.encode("hex")
    if int(S[0].encode("hex"), 16) & 0x80:
        shiftedS = "%016X" % (
            (int(S.encode("hex"), 16) << 1) & 0xFFFFFFFFFFFFFFFF)
        K1 = XORencryptor.encrypt(shiftedS.decode("hex"))
    else:
        shiftedS = "%016X" % (
            (int(S.encode("hex"), 16) << 1) & 0xFFFFFFFFFFFFFFFF)
        K1 = shiftedS.decode("hex")
    if (int(K1[0].encode("hex"), 16) & 0x80):
        #print K1.encode("hex")
        shiftedS = "%016X" % (
            (int(K1.encode("hex"), 16) << 1) & 0xFFFFFFFFFFFFFFFF)
        K2 = XORencryptor.encrypt(shiftedS.decode("hex"))
    else:
        shiftedS = "%016X" % (
            (int(K1.encode("hex"), 16) << 1) & 0xFFFFFFFFFFFFFFFF)
        K2 = shiftedS.decode("hex")
    return K1, K2
Ejemplo n.º 30
0
def encrypt_chunk(secret, fpath, chunksize, initialization_vector):
    """
    @param secret: pkdf2 secre
    @type secret: str
    @type fpath: str
    @type chunksize: tuple
    """
    try:
        f = open(fpath)
        f.seek(chunksize[0])
        chunk = f.read(chunksize[1])

        #cipher = AES.new(secret, AES.MODE_CFB, IV=initialization_vector)
        cipher = XOR.new(secret)
        data_hash = make_checksum(chunk)
        enc_data = cipher.encrypt(chunk)
        ntf = get_named_temporary_file(auto_delete=False)
        chunk_seek = str(chunksize[0])
        ntf.write(str(len(chunk_seek)) + "\n")
        ntf.write(chunk_seek)
        ntf.write(str(len(initialization_vector)) + "\n")
        ntf.write(initialization_vector)
        ntf.write(str(len(data_hash)) + "\n")
        ntf.write(data_hash)
        ntf.write(str(len(enc_data)) + "\n")
        ntf.write(enc_data)
        return ntf.name
    except Exception, e:
        raise e
Ejemplo n.º 31
0
def createciphermsgs_xor(jt65msgcount, stegmsg, key, verbose=False):
# Performs the actual XOR cipher

    ciphermsgs = []

    # Can we fit your hidden message?
    if jt65msgcount * 8 < len(stegmsg):
        print(
            "Length of hidden message exceeds capacity of number of valid JT65 messages provided")
        sys.exit(0)

    originallength = len(stegmsg)
    while len(stegmsg) % 8:
        stegmsg += chr(random.randint(0, 255))

    cryptobj = XOR.new(key)
    cipherdata = cryptobj.encrypt(stegmsg)
    cipherlist = list(bytearray(cipherdata))

    # Is the total length too big to fit into our max number of packets?
    if len(cipherlist) > MAX_MULTI_PACKET_STEG_BYTES_XOR:
        print("Length of hidden message exceeds capacity of multi-packet steg")
        sys.exit(0)
    totalpackets = len(cipherlist) / 8

    if verbose:
        print "Cipher list: " + str(cipherlist)

    createciphermsgs_packer_xor(
        totalpackets, originallength, ciphermsgs, cipherlist, verbose)

    return ciphermsgs
Ejemplo n.º 32
0
 async def xordecrypt(self, ctx, data, key):
     """Uses XOR to decipher the given text with the given key."""
     encryption = XOR.new(key)
     decrypted_data = encryption.decrypt(
         base64.b64decode(data)).decode('utf-8')
     await ctx.send(
         f':white_check_mark: **Decrypted data**: {decrypted_data}')
Ejemplo n.º 33
0
 def token_json(self, uuid):
     crypt = XOR.new(self.password)
     str = "%s\n%s " % ( int(time.mktime(datetime.now().timetuple())), uuid)
     # I hate obfuscation.  Its all I've got
     token = crypt.encrypt(str)
     return dict(token=urllib.quote(token),
                 prefered_protocol=self.smolt_protocol)
Ejemplo n.º 34
0
	def __init__(self):
		self.resultado = None
		#Buscando el archivo INI para saber el String de Conexion
		config = ConfigParser()
		config.read("conf/config.ini")
		self.conexioncifrada = config.get('BASE DE DATOS', 'conexion')
		PASSWORD = XOR.new(base64.b64decode('MjAxMDE3MzMtOTYwOTkyNg=='))
		self.conexion = PASSWORD.decrypt(base64.b64decode(str(self.conexioncifrada)))
Ejemplo n.º 35
0
def encrypt(key, plain_text):
    """
    :param key: 36 byte 길이의 문자열. 나중에 암호를 푸는데 사용된다.
    :param plain_text: 암호화하고 싶은 평문
    :return: 암호화된 byte 타입 데이터
    """
    cipher = XOR.new(key)
    return base64.b64encode(cipher.encrypt(plain_text))
Ejemplo n.º 36
0
def xor(key, data):
    if not isinstance(data, str):
        raise RuntimeError("data value must be a string!")

    if isinstance(key, (int, float)):
        key = chr(key)

    return XOR.new(key).decrypt(data)
Ejemplo n.º 37
0
    def _xor(self, a, b):
        """Performs XOR on two strings a and b"""

        if len(a) != len(b):
            raise ValueError("ERROR: Strings are of different size! %s %s" % (len(a), len(b)))

        xor = XOR.new(a)
        return xor.encrypt(b)
Ejemplo n.º 38
0
    def _xor(self, a, b):
        """Performs XOR on two strings a and b"""

        if len(a) != len(b):
            raise "ERROR: Strings are of different size! %s %s" % (len(a), len(b))

	xor = XOR.new(a)
	return xor.encrypt(b)
Ejemplo n.º 39
0
	def __init__(self):
		self.resultado = None
		#Buscando el archivo INI para saber el String de Conexion
		config = ConfigParser()
		config.read("Conect.dat")
		self.conexioncifrada = config.get('DB', 'StringDB')
		PASSWORD = XOR.new(base64.b64decode('MjAxMDE3MzMtOTYwOTkyNg=='))
		self.conexion = PASSWORD.decrypt(base64.b64decode(str(self.conexioncifrada)))
		self.conexion = 'Driver={SQL Server Native Client 11.0};Server=AXNER-HP\JERMSOFT;Database=365DB_2;Uid=sa;Pwd=jerm'
Ejemplo n.º 40
0
def fixkey(key):
	
	half1= key[:16]
	half2= key[16:]
	
	encryptor = XOR.new(half2)
	
	newkey= encryptor.encrypt(half1)
	return newkey
Ejemplo n.º 41
0
def xorEncrypt(request):
    plain_text = request.POST["message"]
    output = u"Klartext:\n%s\n\n" %(plain_text)
    key = hashlib.sha256(request.POST["key"]).digest()
    output += u"Schlüssel: %s\n\n"%(request.POST["key"])
    output += u"XOR-verschlüsselt:\n"
    xorObject = XOR.new(key)
    cypher = number.bytes_to_long(xorObject.encrypt(plain_text))
    return ( output, cypher )
Ejemplo n.º 42
0
    def _getMAC(self, mac, key):
        """
        Gets a 4-tuple representing the message authentication code.
        (<hash module>, <inner hash value>, <outer hash value>,
        <digest size>)

        @param mac: a key mapping into macMap
        @type mac: C{str}
        @param key: the MAC key.
        @type key: C{str}
        """
        mod = self.macMap[mac]
        if not mod:
            return (None, '', '', 0)
        ds = mod().digest_size
        key = key[:ds] + '\x00' * (64 - ds)
        i = XOR.new('\x36').encrypt(key)
        o = XOR.new('\x5c').encrypt(key)
        return mod, i, o, ds
Ejemplo n.º 43
0
 def check_admin_token(self, token, uuid):
     print "TOKEN CHECK"
     token = urllib.unquote(token)
     crypt = XOR.new(self.password)
     token_plain = crypt.decrypt(token).split('\n')
     if uuid[:7] == token_plain[0]:
         print 'GOT GOOD TOKEN!'
         return token
     else:
         raise ValueError("Critical: %s not a valid token for UUID" % token)
Ejemplo n.º 44
0
def ConvertirDatos(stringbd,lic,cualmodo,dondebd):
    print 'Convirtiendo Datos'
    if dondebd == '1':
        stringbd = stringbd.replace('NOMBREPC',str(gethostname()))
    elif dondebd == '2':
        print 'Indique la direccion donde se encuentra la Base de Datos' 
        direccionremota = raw_input('Indique una direccion IP o un DNS para la conexion a Base de Datos: ')
        stringbd = stringbd.replace('NOMBREPC','mc24.no-ip.net')
    stringbd = stringbd.replace('NOMBREBD','365DB')
    stringbd = stringbd.replace('USUARIOBD','sa')
    stringbd = stringbd.replace('PASSWORDBD','jerm')
    deco = XOR.new(b64decode('MjAxMDE3MzMtOTYwOTkyNg=='))
    stringbd =  b64encode(deco.encrypt(str(stringbd)))
    deco = XOR.new(b64decode('MjAxMDE3MzMtOTYwOTkyNg=='))
    lic =  b64encode(deco.encrypt(str(lic)))
    deco = XOR.new(b64decode('MjAxMDE3MzMtOTYwOTkyNg=='))
    cualmodo =  b64encode(deco.encrypt(str(cualmodo)))
    print 'Datos Convertidos'
    CrearArchivo(stringbd,lic,cualmodo)
Ejemplo n.º 45
0
 def check_token(self, token, uuid):
     token = urllib.unquote(token)
     crypt = XOR.new(self.password)
     token_plain = crypt.decrypt(token).split('\n')
     token_time = int(token_plain[0])
     token_uuid = token_plain[1]
     current_time = int(time.mktime(datetime.now().timetuple()))
     if current_time - token_time > 60:
         raise ValueError("Critical [20]: Invalid Token - Likely A timeout, please try again.")
     if uuid.strip() != token_uuid.strip():
         raise ValueError("Critical [s]: Invalid Token - Likely A timeout, please try again.")
Ejemplo n.º 46
0
def RKXencrypt():
	plainText="Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal"
	key = "ICE"
	cipherText = ""

	for x in range(0,len(plainText)):
		cipherText += util.b16encode(XOR.XORCipher.encrypt(XOR.new(key[x % 3]), plainText[x]))

	print cipherText

	if cipherText == "0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f".upper():
		print "Test Passed"
Ejemplo n.º 47
0
def gen_xor_encrypt():
    init = [False]
    key = Random.new().read(AES.block_size)
    cipher = XOR.new(key)

    def xor_encrypt(raw):
        if init[0] is False:
            init[0] = True
            return key + cipher.encrypt(raw)
        return cipher.encrypt(raw)

    return xor_encrypt
Ejemplo n.º 48
0
def decryption():
	print "Your key: "
	key = raw_input()
	print "Your encrypted password/message: "
	pw = raw_input()
	c = XOR.new(key)
  	dpw = c.decrypt(base64.b64decode(pw))
  	print "Your decrypted password/message is: " + dpw
  	print "Would you like to go again? (y/n)" 
  	an = raw_input()
  	if an == 'y' or an == "Y":
  		main()
Ejemplo n.º 49
0
def encryption():
	print "Your key: (Remember this!) "
	key = raw_input()
	print "Your password/message: "
	pw = raw_input()
	c = XOR.new(key)
  	epw = base64.b64encode(c.encrypt(pw))
  	print "Your encrypted password/message is: " + epw
  	print "Would you like to go again? (y/n)" 
  	an = raw_input()
  	if an == 'y' or an == "Y":
  		main()
Ejemplo n.º 50
0
	def __init__(self):
	#Buscando el archivo INI para saber la configuracion del formato de numeros
		self.config = ConfigParser()
		self.config.read("conf/config.ini")
		self.numsenc = self.config.get('MODEMS', 'nums')
		self.Cipher = XOR.new(base64.b64decode('MjAxMDE3MzMtOTYwOTkyNg=='))
		self.nums = self.Cipher.decrypt(base64.b64decode(str(self.numsenc)))
		self.nums = self.nums.split(",")
		self.dictnums = {}
		letra = 0
		for n in self.nums:
			self.dictnums[str(string.lowercase[letra])]=n
			letra = letra + 1
Ejemplo n.º 51
0
def xor_in_pi(text_bin):
    flen = int(os.stat('pi.bin')[stat.ST_SIZE])
    max_start = flen - len(text_bin)
    some_pi = get_some_pi(max_start, qcrypt.normalize(text_bin))
    xor = XOR.new(some_pi)
    ciphertext = xor.encrypt(text_bin)
    if debug:
        print '\n------xor_in_pi------'
        print qcrypt.normalize(text_bin)
        print qcrypt.normalize(some_pi)
        print qcrypt.normalize(ciphertext)
        print '------xor_in_pi------\n'
    
    return ciphertext
Ejemplo n.º 52
0
 def admin_token_json(self, uuid):
     from hardware.model import *
     crypt = XOR.new(self.password)
     try:
         host_object = session.query(Host).filter_by(uuid=uuid).one()
     except:
         pass
         #raise ValueError("Critical: UUID Not Found - %s" % uuid)
     
     str = "%s" % (uuid[:7])
     # I hate obfuscation.  Its all I've got
     token = crypt.encrypt(str)
     return dict(token=urllib.quote(token),
                 prefered_protocol=self.smolt_protocol)
Ejemplo n.º 53
0
def LicCheckRemote():
	config = ConfigParser()
	config.read("conf/config.ini")
	LicCif = config.get('CUENTA', 'Lic')
	contrasena = base64.b64decode('MjAxMDE3MzMtOTYwOTkyNg==')
	PASSWORD = XOR.new(str(contrasena))
	try:
		#Por si da algun error en la decodificacion
		LicDecif = PASSWORD.decrypt(base64.b64decode(str(LicCif)))
	except:
		LicDecif = None
	if str(xxmx) == str(LicDecif):
		return True
	else:
		return False
Ejemplo n.º 54
0
    def initiate_session(self):
        # Perform the initial connection handshake for agreeing on a shared secret

        ### TODO: Your code here!
        # This can be broken into code run just on the server or just on the client
        if self.server or self.client:
            my_public_key, my_private_key = create_dh_key()
            # Send them our public key
            self.send(bytes(str(my_public_key), "ascii"))
            # Receive their public key
            their_public_key = int(self.recv())
            # Obtain our shared secret
            shared_hash = calculate_dh_secret(their_public_key, my_private_key)
            print("Shared hash: {}".format(shared_hash))

        # Default XOR algorithm can only take a key of length 32
        self.cipher = XOR.new(shared_hash[:4])