def test_encrypt_dotenv(self): env_file_path = os.path.dirname(os.path.realpath(__file__)) env_file_name = "test.env" env_file = env_file_path + "/" + env_file_name enc_env_file_path = env_file_path enc_env_file_name = "test.enc.env" enc_env_file = enc_env_file_path + "/" + enc_env_file_name password_file = env_file_path + "/test.password" decrypted_test_file = enc_env_file_path + "/decrypted.enc" # decrypted_ = pyAesCrypt.decryptStream(enc_env_file_path, ) encrypt_dotenv(env_file, enc_env_file, password_file) # test decrypted file from here with open(password_file, 'r') as f_key: enc_password = f_key.read() pyAesCrypt.decryptFile(enc_env_file, decrypted_test_file, enc_password, __BUFFER__SIZE__) test_keys = ['SOME_SETTING_1', 'SOME_SETTING_2', 'INT_SETTING'] for test_key in test_keys: self.assertEqual( dotenv.get_key(env_file, test_key), dotenv.get_key(decrypted_test_file, test_key), )
def decrypt(file): import pyAesCrypt password="******" bufferSize = 512*1024 pyAesCrypt.decryptFile(str(file), str(os.path.splitext(file)[0]), password, bufferSize) print("[decrypted] '"+str(os.path.splitext(file)[0])+"'") os.remove(file)
def decrypting(self, file, crypt_path): file_name = file + ".aes" file_path = os.path.join(crypt_path, file) file_name_path = os.path.join(crypt_path, file_name) pyAesCrypt.decryptFile(file_name_path, file_path, en_pass, bufferSize) complete_path = os.path.join(crypt_path, file_name) os.remove(complete_path)
def decrypt_aes(*args: str, mod: str) -> None: buffer_size = 512 * 2048 file2 = args[0][:-4] + '.bin' file = args[0] password = args[1] if mod == '1pas': pyAesCrypt.decryptFile(file, str(file2[:-4]), password, buffer_size) os.remove(file) elif mod == '2pas': password2 = args[2] pyAesCrypt.decryptFile(file, file2, password2, buffer_size) pyAesCrypt.decryptFile(file2, str(file[:-4]), password, buffer_size) os.remove(file) os.remove(file2) elif mod == 'fkey': fileKey = args[2] with open(fileKey, "rb") as in_file: in_file.seek(0) if len(in_file.read()) > 315: file_b = str(in_file.read(315)) + str(sha1OfFile(fileKey)) elif len(in_file.read()) < 315: file_b = str(in_file.read()) + str(sha1OfFile(fileKey)) in_file.close() pyAesCrypt.decryptFile(file, file2, file_b, buffer_size) os.remove(file) pyAesCrypt.decryptFile(file2, str(file[0:-4]), password, buffer_size) os.remove(file2)
def decrypterFile(dir): password = input("Введите пароль: ") buffersize = 512 * 1024 dirnoaes = os.path.splitext(dir)[0] pas.decryptFile(dir, dirnoaes, password, buffersize) print(Fore.GREEN + dir + " расшифровано!") os.remove(dir)
def register(username, password, auth_level, key): #Set variables credentials = {} #Decrypt storage file pyAesCrypt.decryptFile("data.txt.aes", "dataout.txt", key, buffer_size) #Open decrypted file with open('dataout.txt', 'r+') as file: #Get datas for line in file: username_read, password_read, auth_level_read = line.strip().split( ' ') credentials[username_read] = password_read #If there is already an user if username in credentials: raise UserAlreadyExist(username) #Else register the new user else: file.write(username + ' ' + password + ' ' + auth_level) #Close file file.close() #Crypt and delete pyAesCrypt.encryptFile("dataout.txt", "data.txt.aes", key, buffer_size) os.remove("dataout.txt")
def decrypt_file(): secure_key = secure_session() user_key = str( input("Enter your Master Password to access your Password Vault : ")) # ENCODE USER ENTERED MASTER PASSWORD IN SHA-256 hash_obj = hashlib.sha256(user_key.encode()) hashed = hash_obj.hexdigest() if hashed == secure_key: if os.path.exists("./engine/6ZFOjBhPwG.csv.aes"): print("Decrypting your data...") pyAesCrypt.decryptFile("engine/6ZFOjBhPwG.csv.aes", "engine/say_shazam.csv", secure_key, buff_size) print( "Your passwords have been securely decrypted. \nPROTIP :: KEEP THAT MASTER PASSWORD IN MIND!" ) else: print( "We did not find the secure database that contained your saved passwords. If this is your first run, this is normal." ) else: print("THE PASSWORD THAT YOU ENTERED IS INVALID. Please try again.") print( "The password that was just generated has NOT been added to your vault." ) exit(9)
def decrypt(): try: Cry.decryptFile(str(file), str(os.path.splitext(file)[0]), password, bufferSize) os.remove(file) except: pass
def decrypt_file(file, buffersize, password): print("decrypt_file called!") out_file_name = file.name[:-4] try: pyAesCrypt.decryptFile(file.name, out_file_name, password, buffersize) except FileExistsError: "error"
def fileDecrypt(dir, file): orig = dir + "\\" + file + ".txt.aes" fin = dir + "\\" + file + ".txt" bufferSize = 64 * 1024 password = "******" pyAesCrypt.decryptFile(orig, fin, password, bufferSize) os.remove(orig)
def file_view(request): fs = FileSystemStorage("secure_file\\media\\") fs1 = FileSystemStorage("secure_file\\enc\\") fs2 = FileSystemStorage("secure_file\\dec\\") location = os.getcwd() print(os.listdir(location+"/"+fs.base_location)) # encryption/decryption buffer size - 64K bufferSize = 1024 * 1024*1024 if request.method=="POST": id = request.POST["download"] password =request.POST["key"] j = models.FileData.objects.get(id=id) print("enc happend") file1 = fs1.open(j.file_title) print(location+"\\"+fs2.base_location+j.file_title+".aes") # decrypt try: pyAesCrypt.decryptFile(fs1.base_location + j.file_title,fs2.base_location + j.file_title[:-3], password, bufferSize) file1 = fs2.open(j.file_title) response = HttpResponse(file1, content_type='application') return response except Exception as e: return HttpResponse(e) #return j = models.FileData.objects.all() return render(request,"fileview.html",{"files":j})
async def markov(self, ctx, *, string: str = ""): """Generate a Markov chain sequence""" # Load model if not loaded if self.markov_model is None: # Decrypt JSON file key = os.getenv("MARKOV_MODEL_KEY") pyAesCrypt.decryptFile("markov_model.json.aes", "markov_model.json", key) # Load model from JSON (expects str, not dict) with open("markov_model.json") as f: self.markov_model = markovify.Text.from_json( json.dumps(json.load(f))) # Generate sentence try: sentence = self.markov_model.make_sentence_with_start( beginning=random.choice(string.split(" ")), tries=1000, min_words=20) except (markovify.text.ParamError, KeyError): sentence = self.markov_model.make_short_sentence(max_chars=2000, min_chars=150, tries=1000) # Return sentence if sentence: await ctx.send(sentence) else: msg = await ctx.send("Failed generating sentence.") await msg.add_reaction(basic_emoji.get("Si"))
def main(input_file_path): bufferSize = 64 * 1024 password = "******" pyAesCrypt.decryptFile("encryp.json.aes", "myriad_key.json", password, bufferSize) os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = os.getcwd( ) + '/myriad_key.json' timeout_val = 180 files_dict = { 'train': input_file_path, 'test': input_file_path, 'dev': input_file_path } my_model = BioBert() data = my_model.read_dataset(file_dict=files_dict) test_labels = my_model.convert_ground_truth(data=data['test']) with timeout(timeout_val + 10): with timeout(timeout_val + 5): with timeout(timeout_val): my_model.train(data=data) pred_vals = my_model.predict(data=data['test']) my_model.evaluate(predictions=pred_vals, ground_truths=test_labels) cmd = "rm -f myriad_key.json" os.system(cmd) output_file_path = my_model.output_dir + "/predicted_output.txt" return output_file_path
def decifra(): global pattern_linux files = [] piattaforma = platform.system() if piattaforma == 'Linux': path = pattern_linux elif piattaforma == 'Windows': path = pattern_windows for r, d, f in os.walk(path): for file in f: files.append(os.path.join(r, file)) for f in files: f = str(f) bufferSize = 64 * 1024 key = password.get() pyAesCrypt.decryptFile(f, f + ".decrypt", key, bufferSize) print("File decriptati perfettamente") try: pyAesCrypt.decryptFile(f, f + ".decrypt", key, bufferSize) print("File decriptati perfettamente") app1 = Tk() Input_step = Label(app1, text="The password is correct", font="Arial 12 bold italic").pack() submit = Button(app1, text='Finish', command=finish).pack() app1.mainloop() except Exception as e: pass
def decrypt (filename, password): filename = filename + '.CRYPT' if "CRYPT" in filename: pe.decryptFile(filename,filename[:-6],password,buff) os.remove(filename) else: return
def decryptFolder(): gui_passwd = pwd_input.get() if gui_passwd == "": popUpEmptyPassword() else: passwd = str(gui_passwd) filename = str(filedialog.askdirectory()) gui.update() files = [] if filename: try: for r, d, f in os.walk(filename): for file in f: files.append(os.path.join(r, file)) for enc_file in files: try: pyAesCrypt.decryptFile(enc_file, enc_file.replace(".enc", ""), passwd, bufferSize) os.remove(enc_file) except Exception: pass popUpSuccessToDecrypt() except: popUpFailedToDecrypt() else: popUpNoFileSelected()
def decrypt_results_to_dir(self, dir, from_subdir): # type: (str, str) -> list """ Having an already encrypted directory, decrypt all files, then move plain files to the location specified by :param dir """ password = self._read_password(self.get_password_file()) if not os.path.isdir(dir): os.makedirs(dir) encrypted_dir = self.get_encrypted_dir() if from_subdir: encrypted_dir = os.path.join(encrypted_dir, from_subdir) plain_files = [] for encrypted_file in os.listdir(encrypted_dir): plain_file = self._determine_plain_filename(dir, encrypted_file) encrypted_file_full = os.path.join(encrypted_dir, encrypted_file) try: pyAesCrypt.decryptFile(encrypted_file_full, plain_file, password, self.buffer_size) plain_files.append(plain_file) except ValueError: LOGGER.info('Could not decrypt file {}'.format(encrypted_file)) return plain_files
def islem(self): sender = self.sender().text() bufferSize = 64 * 1024 if sender == 'Şifrele': dosya = (self.ui.dosya.text()) passs = (self.ui.sifre.text()) pyAesCrypt.encryptFile(dosya, dosya + ".aes", passs, bufferSize) time.sleep(1) msg = QMessageBox() msg.setWindowTitle("Şifrele") msg.setText("Dosya başarıyla Şifrelendi!") msg.setIcon(QMessageBox.Information) x = msg.exec_() os.system("cls") elif sender == 'ŞifreÇöz': dosya = (self.ui.dosya.text()) passs = (self.ui.sifre.text()) uzanti = dosya[:-4] pyAesCrypt.decryptFile(dosya, "out" + uzanti, passs, bufferSize) time.sleep(1) msg = QMessageBox() msg.setWindowTitle("Şifrele") msg.setText("Dosya başarıyla (decrypt) edildi!") msg.setIcon(QMessageBox.Information) x = msg.exec_() os.system("cls")
def decrypt(path): encrypted_file = open(path) encrypted_file_path = path # user selects folder to put a new decrypted file in Tk().withdraw() messagebox.showinfo("byteMe: INFO", "SELECT DIRECTORY FOR NEW DECRYPTED FILE") folder = askdirectory(title='byteMe') name_str = simpledialog.askstring("FILENAME", "NAME OF NEW DECRYPTED FILE:") filename = os.path.join(folder, name_str + ".txt") exists = os.path.isfile(filename) if not exists: output_file = open(filename, "w") else: output_file = open(filename) output_file_path = filename with open(path) as input_file: input_file_path = path # encryption/decryption buffer size - 64K bufferSize = 64 * 1024 password = "******" pyAesCrypt.decryptFile(encrypted_file_path, output_file_path, password, bufferSize) output_file.close() encrypted_file.close() return output_file_path
def aesnew(cryptMode): import pyAesCrypt from os import remove from os.path import splitext fileName = input("Write the file: ") paswFile = input("Write the password: "******"" if cryptMode == 'E': try: pyAesCrypt.encryptFile(str(fileName), str(fileName) + ".crp", paswFile, bufferSize) remove(fileName) except FileNotFoundError: return "[x] File not found!" else: return "[+] File '" + str(fileName) + "' overwritten!" else: try: pyAesCrypt.decryptFile(str(fileName), str(splitext(fileName)[0]), paswFile, bufferSize) remove(fileName) except FileNotFoundError: return "[x] File not found!" except ValueError: return "[x] Password is False!" else: return "[+] File '" + str( splitext(fileName)[0]) + ".crp' overwritten!" print(final)
def login(username, password, key): #Set variables credentials = {} #Decrypt pyAesCrypt.decryptFile("data.txt.aes", "dataout.txt", key, buffer_size) #Open file with open('dataout.txt', 'r+') as file: #Get datas for line in file: username_read, password_read, auth_level_read = line.strip().split( ' ') credentials[username_read] = password_read #If username wrong password correct if username not in credentials: raise UserNotFound(username) # If username correct password wrong if credentials[username] != password: raise WrongPassword(password) #Everything correct else: auth_level = auth_level_read #Close file file.close() #Crypt and delete pyAesCrypt.encryptFile("dataout.txt", "data.txt.aes", key, buffer_size) os.remove("dataout.txt") return int(auth_level)
def cryptFile(): clearScreen() keepLogo() # Get filename from path fileNameWithExtension = os.path.basename(selectPrompt) fileName, fileExtension = os.path.splitext(fileNameWithExtension) path, fileName = os.path.split(selectPrompt) stubPrompt = input("\t\t\tCrypt file (Y/N) > ") bufferSize = 64 * 1024 if stubPrompt == "Y" or "Yes": # Crypt file data (Using AES) clearScreen() keepLogo() pyAesCrypt.encryptFile(selectPrompt, outputPrompt + "\\" + fileName + ".aes", str(key), bufferSize) print(colors.GREEN + "\t\t\t\tEncrypting file using 256-bit AES" + colors.END) # Encode encrypted file contents encryptedPath = outputPrompt + "\\" + fileName + ".aes" encryptedFile = open(encryptedPath, 'rb') temp = encryptedFile.read() encryptedHex = binascii.hexlify(temp) time.sleep(1.5) clearScreen() keepLogo() # Create Stub in Python File print(colors.GREEN + "\t\t\t\t Creating stub file" + colors.END) print(r"") finalPath = outputPrompt + "\\" + fileName + ".py" finalFilename = outputPrompt + "\\" + fileName stubPy = open(finalPath,'w') stubContents = "import pyAesCrypt\n" stubContents += "import binascii\n" stubContents += "key = \"" + key + "\"\n" stubContents += "bufferSize = \"" + str(bufferSize) + "\"\n" stubContents += "encryptedHex = \"" + str(encryptedHex) + "\"\n" stubContents += """ # Decode the hexed encrypted file temp = binascii.unhexlify(bytes(encryptedHex)) # Decrypt the decoded data pyAesCrypt.decryptFile(temp, "dataout.png", key, int(bufferSize)) # Execute payload import subprocess proc = subprocess.Popen("dataout.png", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) """ stubPy.write(stubContents) stubPy.close() time.sleep(1.5) clearScreen() keepLogo() # Combine stub with payload print(colors.GREEN + "\t\t\t\t Combining stub with payload" + colors.END) os.system("pyinstaller -F -w --log-level INFO --distpath " + outputPrompt + " --clean " + finalPath) print(r"") time.sleep(1.5) enterToBegin = input(colors.BLUE + "\t\t\t\t Press ENTER to exit " + colors.END) else: print("Error!") encrypting()
def test_enc_pyAesCrypt_dec_pyAesCrypt(self): for pt, ct, ou in zip(filenames, encfilenames, decfilenames): # encrypt file pyAesCrypt.encryptFile(pt, ct, password, bufferSize) # decrypt file pyAesCrypt.decryptFile(ct, ou, password, bufferSize) # check that the original file and the output file are equal self.assertTrue(filecmp.cmp(pt, ou))
def decryptFiles(files, password): for file in files: try: decryptFile(file, ".".join(file.split(".")[:-1]), password, 64 * 1024) os.remove(file) except: pass
def AES_decrypt(file_aes: str, file_txt: str, key: str, buffsize=512 * 1024): # 1. Файл который рашифровываеться, # 2. Файл куда записываеться расшифрованный текст # 3. Ключ по которому расшифровывают, # 4. (Стандартное значение 512 * 1024) Буффер # file_txt = file_aes.rstrip('.aes') pyAesCrypt.decryptFile(file_aes, file_txt, key, buffsize) return file_txt
def test_enc_AesCrypt_dec_pyAesCrypt(self): for pt, ct, ou in zip(filenames, encfilenames, decfilenames): # encrypt file subprocess.call(["aescrypt", "-e", "-p", password, "-o", ct, pt]) # decrypt file pyAesCrypt.decryptFile(ct, ou, password, bufferSize) # check that the original file and the output file are equal self.assertTrue(filecmp.cmp(pt, ou))
def DecryptFile(filePath, encryptPass): pyAesCrypt.decryptFile((filePath + ".aes"), filePath, encryptPass) secure_delete.secure_random_seed_init() secure_delete.secure_delete( (filePath + ".aes")) #deletes the encrypted file after decrypting print("File decrypted") RevealData() sys.exit("Completed")
def main(): if len(sys.argv) < 3: help_menu() sys.exit(0) password = str(open(sys.argv[1]).read()) encrypted_file = sys.argv[2] decrypted_file = sys.argv[3] pyAesCrypt.decryptFile(encrypted_file, decrypted_file, password)
def decrypt(self): try: pyAesCrypt.decryptFile(self.path, self.path[:-4], self.password, 64 * 1024) Snackbar(text="Completed !").show() except: Snackbar(text="error try again correctly !").show( ) # error for incorrect password or any other things
def decrypt(ext, file, password): if not file.__contains__('.aes'): mes = (decor.red + "File has no '.aes' end" + decor.reset) return mes symbs = len(ext) out = file[:-symbs] pyAesCrypt.decryptFile(file, out, password, bufferSize) print(decor.green + "[+] Completed" + decor.reset)