def Center(key): if (request.headers["Accept-platform"] == "x86"): buf = buf_x86 else: buf = buf_x64 t = time.time() t = int(int(t) / 100) hl = hashlib.md5() hl.update((obs + str(t)).encode(encoding='utf-8')) md5 = hl.hexdigest() if key == md5: global keys print(int(time.time()), keys[0]) if int(time.time()) - keys[0] >= 10: salt = ''.join( random.sample(string.ascii_letters + string.digits, 32)) print(salt) keys[1] = salt keys[0] = int(time.time()) print(keys) return keys[1] elif key == str(int(int(time.time()) / 100)) + ".jpg": arc4 = ARC4(keys[1]) enc = arc4.encrypt(buf) b64 = base64.b64encode(enc) arc3 = ARC4(keys[1]) dec = arc3.decrypt(enc) return b64.decode() return "nothing"
def handle_tcp(decode_arc4, sock, remote): # 处理 client socket 和 remote socket 的数据流 encode_rc4 = ARC4('niceDayIn2020@998') try: fdset = [sock, remote] while True: # 用 IO 多路复用 select 监听套接字是否有数据流 r, w, e = select.select(fdset, [], []) if sock in r: data = sock.recv(4096) if len(data) <= 0: break rdata = decode_arc4.decrypt(data) print(rdata) result = send_data(remote, rdata) if result < len(data): raise Exception('failed to send all data') if remote in r: data = remote.recv(4096) if len(data) <= 0: break result = send_data(sock, encode_rc4.encrypt(data)) if result < len(data): raise Exception('failed to send all data') except Exception as e: raise (e) finally: sock.close() remote.close()
def Main(qname): with open('secret.zip', 'wb') as f: f.write(ARC4(key_).decrypt(decode(qname))) with zipfile.ZipFile('secret.zip', 'r') as zipf: zipf.extractall(".")
def encrypt(self, data: bytes): # Compress to zip data = zlib.compress(bytes(data)) cipher = ARC4(self.password).encrypt(data) encoded = base64.b64encode(cipher) encoded = encoded.replace(b"=", b"").replace(b"/", b"_").replace(b"+", b"-") return encoded
def decrypt_segments(self, addr) -> bool: """ Attempts to decrypt segments :return: Whether the decryption was successful """ try: segments_edited = [ (re.sub("{}\.$".format(client_to_serv["RESP"]), "", i).replace(".", "")) for i in self.commands_for_clients[addr].segments ] flattened = bytes("".join(segments_edited), "utf-8") flattened_replaced = flattened.replace(b"_", b"/").replace(b"-", b"+") replaced_padded = flattened_replaced + b"=" * ( (4 - len(flattened_replaced) % 4) % 4) decoded = base64.b64decode(replaced_padded) deciphered = ARC4(self.password).decrypt(decoded) uncompressed = zlib.decompress(deciphered) self.commands_for_clients[addr].segments = uncompressed.decode( "utf-8") except Exception as e: print("-- Error while processing data from {}: {}".format(addr, e)) return False return True
def cifrar(request): form_cifrado = forms.EsteganografiaCifradoForm() if request.method == 'POST': form_cifrado = forms.EsteganografiaCifradoForm(request.POST, request.FILES) if form_cifrado.is_valid(): datos_imagen = form_cifrado.cleaned_data['imagen'] nombre_imagen = datos_imagen.name llave_secreta = form_cifrado.cleaned_data['llave_secreta'] mensaje_cifrar = form_cifrado.cleaned_data['mensaje_cifrar'] imagen = Image.open(datos_imagen) imagen = imagen.convert("RGB") cifrador = ARC4(llave_secreta) mensaje_cifrado = cifrador.encrypt(mensaje_cifrar) mensaje_cifrado = mensaje_cifrado.decode('unicode-escape') ruta_final = ocultar_texto(mensaje_cifrado, imagen, nombre_imagen) if os.path.exists(ruta_final): with open(ruta_final, 'rb') as fh: response = HttpResponse(fh.read(), content_type="image/png") response[ 'Content-Disposition'] = 'attachment; filename=' + os.path.basename( ruta_final) return response return redirect('esteganografia', form_cifrado=form_cifrado)
def decrypt_payload(encrypted_blob): b64_decoded = base64.b64decode(encrypted_blob) decryption_key = b64_decoded[:0x10] + HARDCODED_SALT sha1hash = hashlib.sha1() sha1hash.update(decryption_key) decryption_key_hash = sha1hash.digest() rc4 = ARC4(decryption_key_hash) return rc4.decrypt(b64_decoded[0x10:])
def data_decrypt(data): """ Sodinokibi decryption routine :param data: :return: """ return ARC4(data[0:32]).decrypt( data[40:40 + struct.unpack('<I', data[36:40])[0] - 1]).decode()
def RC4_crypt(key, buffer): arc4 = ARC4(key) result = list(arc4.decrypt(buffer)) string_result = '' for each in result: if each != 0: string_result += chr(each) return string_result
def decrypt_packet(fname, decompression_rounds=1): with open(fname, "rb") as binfile: data = binfile.read() rc4 = ARC4("FLARE ON 2019\x00") msg = rc4.decrypt(data[4:]) for i in xrange(decompression_rounds): msg = lznt1.decompress_data(msg) return msg
def descifrar(r): file = open("archivo_prueba_cifrada.txt", "rb") contenido = "" plano = "" arc4 = ARC4(bytes(r)) for x in file: contenido += str(x) plano += str(arc4.decrypt(x), "utf-8") print(x) print("\nContenido decifrado:", plano)
def arc4_decoder(key): path = Path('hash_user_information.csv') buffer = [] with open(path, 'rb') as csvfile: reader = csv.reader(csvfile, delimiter=',') data = csvfile.read() arc4 = ARC4(key) cipher = arc4.decrypt(data) buffer.append(str(cipher)) print("расшифруем ", cipher) np.savetxt("user_information1.csv", buffer, delimiter=", ", fmt='% s')
def __rc4_crypt(self, data: bytes, key: bytes) -> bytes: """ Given a data blob and a key blob, perform RC4 encryption/decryption. Parameters: data - Binary string representing data to be encrypted/decrypted key - Binary string representing the key to use Returns: binary string representing the encrypted/decrypted data """ return ARC4(key).decrypt(data)
def decrypt_resource(res_data): """ RC4 Qakbot decryption :param res_data: :return: """ buffer = ARC4(res_data[0:20]).decrypt(res_data[20:]) if QBOT_HEADER in buffer: return qbot_decompress(buffer[20:]) return buffer[20:]
def cifrar(r): file = open("archivo_prueba.txt", "rb") filecipher = open("archivo_prueba_cifrada.txt", "wb") contenido = "" arc4 = ARC4(bytes(r)) for x in file: contenido += str(x) cipher = arc4.encrypt(x) filecipher.write(cipher) print(x) print("\nContenido cifrado:", contenido)
def arc4_encoder(key): path = Path(CONFIG_PATH) buffer = [] with open(path, newline='') as csvfile: reader = csv.reader(csvfile, delimiter=',') for row in reader: arc4 = ARC4(key) cipher = arc4.encrypt(str(row)) buffer.append(cipher) print("шифруем ", cipher) print(type(cipher)) with open('hash_user_information.csv', "wb") as f: for i in range(len(buffer)): f.write(buffer[i])
def fun_que_hace_todo(iteration): k = Random.get_random_bytes(128) # llave compartida m = 'Algun mensaje mamalon super secret con hartos valores que superan el numero de bytes de la llave k para que pueda funcionar el supuesto aplicado' # mensaje a compartir s = Random.get_random_bytes(48) # llave aleatoria # Se aplica el primer OR entre s|k bytes_or = apply_OR(s, k) arc4 = ARC4(k) # Creamos una instancia de RC4 con la llave compartida # Aplicamos el RC4 al OR sería la parte de RC4(s|k) cipher = arc4.encrypt(bytes_or) # Obtenemos la parte RC4(s|k) XOR m c = apply_XOR(cipher, bytes(m, 'utf-8')) parejas_sc.append((iteration, c)) # Aplicamos el inverso del XOR decipher = apply_XOR(cipher, c)
def main(): parser = argparse.ArgumentParser(description='Warzone Config Extractor') parser.add_argument('-f', '--file', action='store', dest='file', required=True, help='Path of Warzone file to unpack') args = parser.parse_args() dataRaw, sectionSize = getData(args.file) key, cipher = getEncodedData(args.file, dataRaw, sectionSize) arc4 = ARC4(key) configBlock = (arc4.decrypt(cipher)) config = extractConfig(configBlock) for k, v in config.items(): print(f"{k}: {v}")
def handle_con(sock, addr): # 活动目标地址和端口 datalen = struct.unpack('>B', sock.recv(1))[0] logging.info('datalen %d' % (datalen)) encode_data = sock.recv(datalen) decode_arc4 = ARC4('niceDayIn2020@998') data = decode_arc4.decrypt(encode_data) print(data) addrLen = struct.unpack('>H', data[0:2])[0] logging.info('addrLen %d' % (addrLen)) target_addr = data[2:addrLen + 2] logging.info('target_addr %s' % (target_addr)) target_port = struct.unpack('>H', data[2 + addrLen:addrLen + 4])[0] logging.info('target_port %d' % (target_port)) addrMd5 = data[4 + addrLen:4 + addrLen + 32] logging.info('addrMd5 %s' % (addrMd5)) md5 = hashlib.md5() md5.update(target_addr) _addrMd5 = md5.hexdigest() logging.info('_addrMd5 %s' % (_addrMd5)) if addrMd5.decode("utf-8") != _addrMd5: print(target_addr) print('addr error') sock.close() return print('addr right') # logging.info('data length %d' % (datalen[0])) # target_addr = sock.recv(datalen[0]) # logging.info('target_addr %s' % (target_addr)) # target_port = struct.unpack('>H', sock.recv(2)) # logging.info('target_port %s' % (target_port)) # 拿到 remote address 的信息后,建立连接 try: remote = socket.create_connection((target_addr, target_port)) logging.info('connecting %s:%d' % (target_addr, target_port)) except socket.error as e: logging.error(e) return handle_tcp(decode_arc4, sock, remote)
def main(): key, cipher_text = resource_load() print("Decrypting RC4 Encrypted first stage...") arc4_key = ARC4(key) string_decrypt = arc4_key.decrypt(cipher_text) print("Loading Second Stage PE") with open('second_stage.bin', 'wb') as file_out: file_out.write(string_decrypt) string_decrypt = extract_and_dump_second() print("PNG Payload decrypted! dumping on disk...") with open('third_stage.bin', 'wb') as file_out: file_out.write(string_decrypt) print("Payload dumped! goodbye!")
def main(): pe = pefile.PE(r"C:\Users\User\Desktop\Analysis\Zero2Auto\Lesson 3\Loaders\new_iced_dump.bin") section_addr = None for section in pe.sections: if(".data" in section.Name.decode()): section_addr = section break print("Virtual Location:", hex(section_addr.VirtualAddress)) keys = section_addr.get_data()[0:8] cipher_text = section_addr.get_data()[8:585] print("Key:", keys) print("Decrypting RC4 Encrypted configuration!") arc4_key = ARC4(keys) string_decrypt = arc4_key.decrypt(cipher_text) print(string_decrypt)
def descifrar(request): form_descifrado = forms.EsteganografiaDescifradoForm() if request.method == 'POST': form_descifrado = forms.EsteganografiaDescifradoForm( request.POST, request.FILES) if form_descifrado.is_valid(): datos_imagen = form_descifrado.cleaned_data['imagen'] llave_secreta = form_descifrado.cleaned_data['llave_secreta'] imagen = Image.open(datos_imagen) mensaje_cifrado = leer(imagen) mensaje_cifrado = mensaje_cifrado.encode(encoding='ISO-8859-1') cifrador = ARC4(llave_secreta) try: mensaje_descifrado = cifrador.decrypt(mensaje_cifrado).decode( 'utf-8') except: mensaje_descifrado = cifrador.decrypt(mensaje_cifrado) return render(request, 'mensaje_revelado.html', {'mensaje_descifrado': mensaje_descifrado}) return redirect('esteganografia', form_descifrado=form_descifrado)
class random_auth(): key = "AAAAAAAAAAAAAAAA" arc4 = ARC4(key) act_connect = "connect" act_disconnect = "disconnect" act_list = "list" tokens = {} def __init__(self, host, port): self.host = host self.port = port def encrypt(data, hex_decode=False): if hex_decode: data = bytes.fromhex(data) return arc4.decrypt(data) def connect(self, user, password): p = remote(self.host, self.port) p.sendline("connect " + user + ":" + password) self.tokens[user] = p.recvline().decode() print(user + " connected.") def disconnect(self, user): p = remote(self.host, self.port) p.sendline("disconnect " + user) print(p.recvline().decode().strip()) p.close() def list(self, user): p = remote(self.host, self.port) p.sendline("list " + user + ":" + self.tokens[user]) print(p.recvline().decode().strip()) p.close()
def get_info(email): arc = ARC4(HKEY) return base64.b64encode(arc.encrypt(email))
#!/usr/bin/env python3 #coding: utf-8 from arc4 import ARC4 KEY = '\x31\xc0\x48\xbb\xd1\x9d\x96\x91\xd0\x8c\x97\xff\x48\xf7\xdb\x53\x54\x5f' with open('secret.csv', 'r') as f: content = f.readlines() for line in content: line = line.split(':') if len(line) > 1: c = ARC4(KEY) mdp = line[1] print(line[0] + ':' + c.encrypt(mdp).hex())
from arc4 import ARC4 """ db 16h, 56h, 0BCh, 86h, 9Eh, 0E1h, 0D1h, 2, 65h, 0C1h .data:000000018001A9F0 ; DATA XREF: Registry_SetFlag+A5↑o .data:000000018001A9F0 db 69h, 9Fh, 10h, 0Ah, 0ACh, 0C1h, 0F6h, 0E9h, 0FDh, 0B4h .data:000000018001A9F0 db 0CDh, 22h, 4Ah, 35h, 9Ch, 12h, 73h, 0BDh, 2Bh, 10h .data:000000018001A9F0 db 54h, 0B9h, 43h, 0D2h, 13h, 9Ah, 84h, 65h, 0ADh, 0B0h .data:000000018001A9F0 db 0BFh, 5Ah, 81h, 10h, 4 dup(0) """ enc = bytes.fromhex( "1656BC869EE1D10265C1699F100AACC1F6E9FDB4CD224A359C1273BD2B1054B943D2139A8465ADB0BF5A8110" ) key = b"H@n $h0t FiRst!" crypt = ARC4(key) print(crypt.decrypt(enc))
def newput(self, *args): # 上传文件,具有断点续传功能 cmd_split = args[0].split() tag = cmd_split[-1] # tag:r代表续传,o代表覆盖,放在最后一位 if tag not in ('o', 'r'): tag = 'unknown' # print(cmd_split,tag) if len(cmd_split) > 1: filename = cmd_split[1] filepath = os.path.join(settings.download_dir, filename) if os.path.isfile(filepath): filesize = os.path.getsize(filepath) # 法1 # filesize = os.stat(filepath).st_size # 法2 # 直接调用系统命令取得MD5值,如果使用hashlib,需要写open打开文件-》read读取文件(可能文件大会很耗时)-》m.update计算三部,代码量更多,效率也低 # filemd5 = os.popen('md5sum %s' % filepath).read().split()[0] filemd5 = 'a' # Windows测试 msg = { "action": 'newput', "filename": filename, "filesize": filesize, "filemd5": filemd5, "tag": tag } # logging.info(msg) self.client.send(json.dumps(msg).encode('utf-8')) # 发送msg server_response1 = self.client.recv( 1024).decode() # 接收文件存在或者文件不存在 # logging.info(server_response) #print(server_response1) if server_response1 == '文件存在': # 再确认一遍tag if tag == 'unknown': tag = input('文件已存在,要覆盖文件请输入o,要断点续传请输入r >>>:').strip() if tag not in ('o', 'r'): tag = 'unknown' else: # 文件不存在时 tag = 'o' self.client.send(tag.encode()) server_response2 = json.loads( self.client.recv(1024).decode('utf-8')) # print('server_response2:', server_response2) content = server_response2['content'] if tag == 'o' or tag == 'r': if content == 'begin': position = server_response2['position'] print(position) f = open(filepath, 'rb') f.seek(position, 0) send_size = position key = getpass.getpass("请输入上传存储此文件的密码>>>:").strip() key = hashmd5(key)[5:-5] + key rc4_ = ARC4(key) rc4_.encrypt(os.urandom(position)) for line in f: line = rc4_.encrypt(line) self.client.send(line) send_size += len(line) processbar(send_size, filesize) else: print('\n', "file uploaded successfully") f.close() server_response3 = self.client.recv(1024).decode( 'utf-8') # 服务端对比md5后发送是否成功接收文件,成功或失败 #print(server_response3) else: print(content) # content:服务器已存在同名文件 或。。。 else: print(content) # content:文件未上传 else: print(filename, 'is not exist') else: self.help()
def sktSend(self, data): arc4 = ARC4(self.password) self.sock.send(struct.pack("<H", len(data)) + arc4.encrypt(data)) self.busy = True
print "Processing - Making remaining string base64 complient..." chunkNumber, chunkData = message.split('.', 1) chunkNumber = int(chunkNumber) # We have only one chunk with index 0 dataChunks = [] dataChunks.append(chunkData.replace(".", "")) filedata = ''.join(dataChunks) filedata = filedata.replace("_", "/").replace("-", "+") filedata += "=" * ((4 - len(filedata) % 4) % 4) filedata = bytearray(filedata, 'utf-8') print "Processing - Undertaking base64 decode..." filedata = base64.urlsafe_b64decode(filedata) print "Processing - Undertaking RC4 decode..." arc4 = ARC4(password) filedata = arc4.decrypt(filedata) print "Processing - Saving data to zipfile..." with open("./secret.zip", 'w') as fileHandle: fileHandle.write(filedata) fileHandle.close() print "Processing - Opening zip file and reading data..." os.system("unzip secret.zip > F1.txt") readline = open(filename).readline().rstrip() print "Processing - Tidying up system files...\n" os.system("rm F1.txt") os.system("rm secret.zip") os.system("rm secret.txt")
for i in range(0, 2): try: hdr_idx = contents.index(b'IDAT', hdr_idx) except ValueError: # Get value error when cant find another header - so were finished print("Finished processing file.") break print("Found IDAT at " + str(hdr_idx)) section_length = int.from_bytes(contents[hdr_idx - 4:hdr_idx], byteorder='big') pt_hash = int.from_bytes(contents[hdr_idx + 4:hdr_idx + 8], byteorder='little') key_len = int(contents[hdr_idx + 8]) print(f"\tSection length: {section_length}") print(f"\tKey length: {key_len}") print(f"\tHash in image: {pt_hash}") key = contents[hdr_idx + 9:hdr_idx + 9 + key_len] print(key) arc4 = ARC4(key) plaintext = arc4.decrypt(contents[hdr_idx + 9 + key_len:hdr_idx + 9 + section_length - 5]) h = calc_hash(plaintext) if h == pt_hash: print("Hash checks out") with open(args.output, 'wb') as output_file: output_file.write(plaintext)