Esempio n. 1
0
        public MainForm(FAES_File faesFile = null)
        {
            InitializeComponent();
            autoDetect.BringToFront();

            titleLabel.Text += Program.GetVersion();
            base.Text        = titleLabel.Text;

            DateTime buildDate = Program.GetBuildDate();

            copyrightLabel.Text   = $"© - {buildDate:yyyy} | mullak99";
            longVersionLabel.Text = $"FileAES {Program.GetVersion()} | Built on {buildDate:dd/MM/yyyy} at {buildDate:hh:mm:ss tt}";

            if (FileAES_Utilities.GetVerboseLogging())
            {
                _devForm = new DevForm();
                _devForm.SetCheckUpdateAction(InvokeCheckUpdate);

                // Hacky solution to the RichTextBox Console.SetOut causing issues if the DevForm is not opened at least once before encryption/decryption (otherwise it hangs)
                _devForm.Show();
                _devForm.Hide();
            }

            autoSelectMenuButton.registerDetoggles(new[] { encryptMenuButton, decryptMenuButton, settingsMenuButton, aboutMenuButton });
            encryptMenuButton.registerDetoggles(new[] { autoSelectMenuButton, decryptMenuButton, settingsMenuButton, aboutMenuButton });
            decryptMenuButton.registerDetoggles(new[] { autoSelectMenuButton, encryptMenuButton, settingsMenuButton, aboutMenuButton });
            settingsMenuButton.registerDetoggles(new[] { autoSelectMenuButton, encryptMenuButton, decryptMenuButton, aboutMenuButton });
            aboutMenuButton.registerDetoggles(new[] { autoSelectMenuButton, encryptMenuButton, decryptMenuButton, settingsMenuButton });

            aboutPanel.SetIsUpdateAction(() => aboutMenuButton_Click(null, null));
            aboutPanel.CheckForUpdate();

            if (faesFile != null)
            {
                encryptPanel.setCloseAfterOperationSuccessful(true);
                decryptPanel.setCloseAfterOperationSuccessful(true);
                FAESMenuHandler(faesFile);
            }
        }
Esempio n. 2
0
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);

            if (e.CloseReason == CloseReason.WindowsShutDown)
            {
                return;
            }
            if (e.CloseReason == CloseReason.ApplicationExitCall)
            {
                return;
            }

            if (_inProgress)
            {
                if (MessageBox.Show(this, "Are you sure you want to stop encrypting?", "Closing", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    backgroundEncrypt.CancelAsync();
                    try
                    {
                        FileAES_Utilities.PurgeInstancedTempFolders();
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("This action is currently unsupported!", "Error");
                        e.Cancel = true;
                    }
                }
                else
                {
                    e.Cancel = true;
                }
                update.Dispose();
            }
            else
            {
                FileAES_Utilities.PurgeInstancedTempFolders();
            }
        }
Esempio n. 3
0
        private void decryptFileDrop_Click(object sender, EventArgs e)
        {
            string fileToDecrypt = "";

            if (openFileToDecrypt.ShowDialog() == DialogResult.OK)
            {
                if (!FileAES_Utilities.isFileDecryptable(openFileToDecrypt.FileName))
                {
                    MessageBox.Show("Please select a valid filetype.", "Invalid Filetype");
                }
                else
                {
                    fileToDecrypt     = openFileToDecrypt.FileName;
                    Program.doDecrypt = true;
                    using (FileAES_Decrypt decrypt = new FileAES_Decrypt(fileToDecrypt.Replace(@"\\", @"\")))
                    {
                        decrypt.StartPosition = FormStartPosition.CenterParent;
                        decrypt.ShowDialog();
                        decrypt.Focus();
                    }
                }
            }
        }
Esempio n. 4
0
        private void decryptFileDrop_DragDrop(object sender, DragEventArgs e)
        {
            string[] FileList = (string[])e.Data.GetData(DataFormats.FileDrop, false);

            if (FileList.Length > 1)
            {
                MessageBox.Show("You may only decrypt a single file at a time.", "Multiple Files Unsupported");
            }
            else if (!FileAES_Utilities.isFileDecryptable(FileList[0]))
            {
                MessageBox.Show("Please select a valid filetype.", "Invalid Filetype");
            }
            else
            {
                Program.doDecrypt = true;
                using (FileAES_Decrypt decrypt = new FileAES_Decrypt(FileList[0].Replace(@"\\", @"\")))
                {
                    decrypt.StartPosition = FormStartPosition.CenterParent;
                    decrypt.ShowDialog();
                    decrypt.Focus();
                }
            }
        }
Esempio n. 5
0
        private void InitSSM()
        {
            _ssm.Open();
            _ssm.AddString("CreatedVersion-FAES_GUI", Program.GetVersion(), "The version of FileAES_GUI used when the SSM file was created", "FAES_MetaData");
            _ssm.AddString("CreatedVersion-FAES", FileAES_Utilities.GetVersion(), "The version of FAES used when the SSM file was created.", "FAES_MetaData");

            _ssm.AddString("LastAccessedVersion-FAES_GUI", Program.GetVersion(), "The version of FileAES_GUI used when the SSM file was created", "FAES_MetaData");
            _ssm.AddString("LastAccessedVersion-FAES", FileAES_Utilities.GetVersion(), "The version of FAES used when the SSM file was created.", "FAES_MetaData");

            _ssm.AddBoolean("FullInstall", false, "If the current FAES_GUI install is a 'Full Install'", "FAES_Install");
            _ssm.AddBoolean("AssociateFileTypes", false, "Associate file types with FileAES_GUI.", "FAES_Install");
            _ssm.AddBoolean("StartMenuShortcuts", false, "Create Start Menu shortcut for FileAES_GUI.", "FAES_Install");
            _ssm.AddBoolean("ContextMenus", false, "Add FileAES_GUI to context menus.", "FAES_Install");

            _ssm.AddString("LogPath", "log\\{default}", "The path of the log file. '{default}' will be replaced with the auto-generated log filename.", "FAES_GUI-Paths");
            _ssm.AddUInt32("CryptoStreamBufferSize", 1048576, "The size of the CryptoStream Buffer.", "FAES_Configs");
            _ssm.AddBoolean("LogToFile", false, "Always output FAES log to a file.", "FAES_Configs");
            _ssm.AddBoolean("DeveloperMode", false, "Toggle verbose logging and ability to open the Developer Console.", "FAES_Configs");
            _ssm.AddString("Branch", Program.GetBuild(), "The branch used to determine updates.", "FAES_Configs");
            _ssm.AddBoolean("SkipUpdates", false, "Toggles whether a new update warning should be shown.", "FAES_Configs");
            _ssm.AddBoolean("UseOSTempPath", false, "Toggles whether the OS' Temp path should be used for encryptions.", "FAES_Configs");
            _ssm.Close();
        }
Esempio n. 6
0
        public static void Log(string log, Severity severity = Severity.INFO)
        {
            if (FileAES_Utilities.GetVerboseLogging())
            {
                switch (severity)
                {
                case Severity.DEBUG:
                {
                    Console.WriteLine("[DEBUG] {0}", log);
                    break;
                }

                case Severity.WARN:
                {
                    Console.WriteLine("[WARN] {0}", log);
                    break;
                }

                case Severity.ERROR:
                {
                    Console.WriteLine("[ERROR] {0}", log);
                    break;
                }

                case Severity.INFO:
                default:
                {
                    Console.WriteLine("[INFO] {0}", log);
                    break;
                }
                }
            }
            else if (severity > 0)
            {
                Console.WriteLine(log);
            }
        }
Esempio n. 7
0
        public void Folder_EncryptDecrypt(bool testCompression, FAES.Packaging.CompressionMode compressionMode, FAES.Packaging.CompressionLevel compressionLevel)
        {
            string encFolder            = "TestFolder";
            string encFilePath          = "TestFile.txt";
            string encPath              = Path.Combine(encFolder, encFilePath);
            string originalFileContents = "Hello World!\r\nTest";
            string finalFileContents    = string.Empty;
            string password             = "******";
            string hint = "Example Hint";

            try
            {
                FileAES_Utilities.SetVerboseLogging(true);

                Directory.CreateDirectory(encFolder);
                File.WriteAllText(encPath, originalFileContents);

                FAES_File encFile = new FAES_File(encPath);

                FileAES_Encrypt encrypt = new FileAES_Encrypt(encFile, password, hint);

                if (testCompression)
                {
                    encrypt.SetCompressionMode(compressionMode, compressionLevel);
                }

                bool encryptSuccess = encrypt.encryptFile();

                if (!encryptSuccess)
                {
                    throw new Exception("Encryption Failed! 'encryptFile' was false.");
                }

                string    decFilePath = Path.ChangeExtension(encPath, FileAES_Utilities.ExtentionFAES);
                FAES_File decFile     = new FAES_File(decFilePath);

                FileAES_Decrypt decrypt        = new FileAES_Decrypt(decFile, password);
                bool            decryptSuccess = decrypt.decryptFile();

                if (!decryptSuccess)
                {
                    throw new Exception("Decryption Failed! 'decryptFile' was false.");
                }

                finalFileContents = File.ReadAllText(encPath).TrimEnd('\n', '\r', ' ');

                if (finalFileContents != originalFileContents)
                {
                    throw new Exception("Final file contents does not match original!");
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.ToString());
            }
            finally
            {
                if (Directory.Exists(encFolder))
                {
                    Directory.Delete(encFolder, true);
                }

                Console.WriteLine("\r\n=== Test Values ===\r\n");
                Console.WriteLine("encFolder: {0}", encFolder);
                Console.WriteLine("encFilePath: {0}", encFilePath);
                Console.WriteLine("encPath: {0}", encPath);
                Console.WriteLine("Initial Contents: {0}", originalFileContents.Replace("\r\n", "\\r\\n"));
                Console.WriteLine("Final Contents: {0}", finalFileContents.Replace("\r\n", "\\r\\n"));
            }
        }
Esempio n. 8
0
        private void Decrypt()
        {
            string password    = passTextbox.Text;
            bool   delAfterEnc = deleteOriginal.Checked;
            bool   ovDup       = overwriteDuplicate.Checked;

            Logging.Log("FAES_GUI(Decrypt): Started!'", Severity.DEBUG);

            SetNote("Decrypting... Please wait.", 0);

            _inProgress        = true;
            _decryptSuccessful = false;

            _mainDecryptThread = new Thread(() =>
            {
                try
                {
                    FileAES_Utilities.SetCryptoStreamBuffer(Program.programManager.GetCryptoStreamBufferSize());
                    FileAES_Decrypt decrypt = new FileAES_Decrypt(_fileToDecrypt, password, delAfterEnc, ovDup);
                    decrypt.DebugMode       = FileAES_Utilities.GetVerboseLogging();

                    _faesThread = new Thread(() =>
                    {
                        try
                        {
                            _decryptSuccessful = decrypt.DecryptFile();
                        }
                        catch (Exception e)
                        {
                            SetNote(FileAES_Utilities.FAES_ExceptionHandling(e, Program.IsVerbose()).Replace("ERROR:", ""), 3);
                        }
                    });
                    _faesThread.Start();

                    while (_faesThread.ThreadState == ThreadState.Running)
                    {
                        _progress = decrypt.GetPercentComplete();
                    }

                    {
                        _inProgress = false;

                        Invoke(new MethodInvoker(() => Locked(false)));

                        if (_decryptSuccessful)
                        {
                            Logging.Log("FAES_GUI(Decrypt): Finished successfully!'", Severity.DEBUG);
                            SetNote("Decryption Complete", 0);
                            progressBar.CustomText = "Done";
                            progressBar.VisualMode = CustomControls.ProgressBarDisplayMode.TextAndPercentage;
                            if (_closeAfterOp)
                            {
                                Application.Exit();
                            }
                            else
                            {
                                ResetFile();
                            }
                        }
                        else
                        {
                            decryptionTimer.Stop();
                            progressBar.ProgressColor = Color.Red;
                            progressBar.Value         = progressBar.Maximum;

                            Logging.Log("FAES_GUI(Decrypt): Finished unsuccessfully!'", Severity.DEBUG);
                            if (!statusInformation.Text.ToLower().Contains("error"))
                            {
                                SetNote("Password Incorrect!", 3);
                                progressBar.CustomText = "Password Incorrect!";
                                progressBar.VisualMode = CustomControls.ProgressBarDisplayMode.TextAndPercentage;
                                Invoke(new Action(() => passTextbox.Focus()));
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    SetNote(FileAES_Utilities.FAES_ExceptionHandling(e, Program.IsVerbose()).Replace("ERROR:", ""), 3);
                }
            });
            _mainDecryptThread.Start();
        }
Esempio n. 9
0
        private void SetMetaData()
        {
            long   timestamp   = _fileToDecrypt.GetEncryptionTimeStamp();
            string version     = _fileToDecrypt.GetEncryptionVersion();
            string compression = _fileToDecrypt.GetEncryptionCompressionMode();

            encryptedFileMetaData.ResetText();

            if (timestamp >= 0)
            {
                encryptedFileMetaData.Text += $"Encrypted on {FileAES_Utilities.UnixTimeStampToDateTime(timestamp):dd/MM/yyyy} at {FileAES_Utilities.UnixTimeStampToDateTime(timestamp):hh:mm:ss tt}.";
            }
            else
            {
                encryptedFileMetaData.Text += "This file does not contain a encryption date. This is likely due to this file being encrypted using an older FAES version.";
            }

            encryptedFileMetaData.Text += (Environment.NewLine + $"FAES {version} was used.");

            if (compression == "LGYZIP")
            {
                encryptedFileMetaData.Text += (Environment.NewLine + "Compressed with LEGACYZIP.");
            }
            else
            {
                encryptedFileMetaData.Text += (Environment.NewLine + $"Compressed with {compression}.");
            }

            passHintTextbox.Text = _fileToDecrypt.GetPasswordHint();
        }
Esempio n. 10
0
        private void Decrypt()
        {
            Logging.Log("FAES_GUI(Decrypt): Started!'", Severity.DEBUG);
            string pathOverride = Path.Combine(Path.GetDirectoryName(_fileToPeek.GetPath()) ?? string.Empty, "faesPeekFilePath_" + new Random().Next(), "peekFile" + FileAES_Utilities.ExtentionUFAES);
            string dirName      = Path.GetDirectoryName(pathOverride);
            string password     = passTextbox.Text;
            string finalPath    = Path.Combine(dirName ?? string.Empty, _fileToPeek.GetOriginalFileName());

            DirectoryInfo di = Directory.CreateDirectory(dirName ?? string.Empty);

            di.Attributes = FileAttributes.Directory | FileAttributes.Hidden;

            SetNote("Decrypting... Please wait.", 0);

            _inProgress        = true;
            _decryptSuccessful = false;

            _mainDecryptThread = new Thread(() =>
            {
                try
                {
                    FileAES_Utilities.SetCryptoStreamBuffer(Program.programManager.GetCryptoStreamBufferSize());
                    FileAES_Decrypt decrypt = new FileAES_Decrypt(_fileToPeek, password, false);
                    decrypt.DebugMode       = FileAES_Utilities.GetVerboseLogging();

                    _faesThread = new Thread(() =>
                    {
                        try
                        {
                            _decryptSuccessful = decrypt.DecryptFile(pathOverride);
                        }
                        catch (Exception e)
                        {
                            SetNote(FileAES_Utilities.FAES_ExceptionHandling(e, Program.IsVerbose()).Replace("ERROR:", ""), 3);
                        }
                    });
                    _faesThread.Start();

                    while (_faesThread.ThreadState == ThreadState.Running)
                    {
                        _progress = decrypt.GetPercentComplete();
                    }

                    {
                        _inProgress = false;
                        Invoke(new MethodInvoker(() => Locked(false)));

                        if (_decryptSuccessful)
                        {
                            Logging.Log("FAES_GUI(Decrypt): Finished successfully!'", Severity.DEBUG);
                            SetNote("Decryption Complete", 0);
                            progressBar.CustomText = "Done";
                            progressBar.VisualMode = CustomControls.ProgressBarDisplayMode.TextAndPercentage;

                            Invoke(new MethodInvoker(() =>
                            {
                                fileContentsTextbox.Text = File.ReadAllText(finalPath);
                            }));
                            Delete(pathOverride);
                        }
                        else
                        {
                            decryptionTimer.Stop();
                            progressBar.ProgressColor = Color.Red;
                            progressBar.Value         = progressBar.Maximum;

                            Logging.Log("FAES_GUI(Decrypt): Finished unsuccessfully!'", Severity.DEBUG);
                            if (!statusInformation.Text.ToLower().Contains("error"))
                            {
                                SetNote("Password Incorrect!", 3);
                                progressBar.CustomText = "Password Incorrect!";
                                progressBar.VisualMode = CustomControls.ProgressBarDisplayMode.TextAndPercentage;
                                Invoke(new Action(() => passTextbox.Focus()));
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    SetNote(FileAES_Utilities.FAES_ExceptionHandling(e, Program.IsVerbose()).Replace("ERROR:", ""), 3);
                }
                finally
                {
                    Delete(pathOverride);
                }
            });
            _mainDecryptThread.Start();
        }
Esempio n. 11
0
        private void CommandInput(RichTextBox textbox)
        {
            string[] input = textbox.Text.Split(' ');
            input[0] = input[0].ToLower();

            if (input[0] == "cryptostreambuffer" || input[0] == "csbuffer" || input[0] == "buffer")
            {
                if (input.Length > 1 && !string.IsNullOrEmpty(input[1]) && uint.TryParse(input[1], out uint csBufferTmp))
                {
                    Logging.Log($"CryptoStream Buffer set to {csBufferTmp} bytes");
                    FileAES_Utilities.SetCryptoStreamBuffer(csBufferTmp);
                }
                else
                {
                    TooFewArgsError(textbox.Text);
                }
            }
            else if (input[0] == "getcryptostreambuffer" || input[0] == "getcsbuffer" || input[0] == "getbuffer")
            {
                Logging.Log($"CryptoStream Buffer is {FileAES_Utilities.GetCryptoStreamBuffer()} bytes");
            }
            else if (input[0] == "getfaestempfolder" || input[0] == "gettemp" || input[0] == "gettempfolder")
            {
                Logging.Log($"FAES Temp Folder is: {FileAES_Utilities.GetFaesTempFolder()}");
            }
            else if (input[0] == "getfaesversion" || input[0] == "getfaesver" || input[0] == "faesver")
            {
                Logging.Log($"FAES Version: {FileAES_Utilities.GetVersion()}");
            }
            else if (input[0] == "getfaesuiversion" || input[0] == "getfaesguiversion" || input[0] == "getfaesuiver" || input[0] == "getfaesguiver" || input[0] == "ver" || input[0] == "guiver" || input[0] == "faesguiver")
            {
                Logging.Log($"FAES_GUI Version: {Program.GetVersion()}");
            }
            else if (input[0] == "getssmversion" || input[0] == "getssmver" || input[0] == "ssmver")
            {
                Logging.Log($"SSM Version: {SimpleSettingsManager.SSM.GetVersion()}");
            }
            else if (input[0] == "getlatestversiononbranch" || input[0] == "latestver" || input[0] == "latestversion" || input[0] == "latestvercheck")
            {
                Thread updateCheckThread = new Thread(() =>
                {
                    try
                    {
                        string branch = Program.programManager.GetBranch();

                        if (input.Length > 1 && !string.IsNullOrEmpty(input[1]))
                        {
                            string rawBranchRequest = input[1];

                            if (rawBranchRequest.ToLower() == "stable" || rawBranchRequest.ToLower() == "beta" || rawBranchRequest.ToLower() == "dev")
                            {
                                branch = rawBranchRequest.ToLower();
                            }
                        }

                        string verCheck =
                            $"https://api.mullak99.co.uk/FAES/IsUpdate.php?app=faes_gui&ver=latest&branch={branch}&showver=true";

                        Logging.Log($"Getting the latest FAES_GUI version number on branch '{branch}'.");
                        Logging.Log("This process may take a few seconds...");

                        WebClient webClient = new WebClient();
                        string latestVer    = webClient.DownloadString(new Uri(verCheck));

                        if (!string.IsNullOrWhiteSpace(latestVer))
                        {
                            Logging.Log($"Latest FAES_GUI Version on branch '{branch}' is '{latestVer}'.");
                        }
                        else
                        {
                            Logging.Log($"The branch '{branch}' does not contain any versions!", Severity.WARN);
                        }
                    }
                    catch
                    {
                        Logging.Log("Unable to connect to the update server! Please check your internet connection.", Severity.WARN);
                    }
                });
                updateCheckThread.Start();
            }
            else if (input[0] == "checkupdate" || input[0] == "check" || input[0] == "updatecheck")
            {
                try
                {
                    string latestVer  = GetLatestVersion();
                    string currentVer = ConvertVersionToNonFormatted(Program.GetVersion());

                    Program.programManager.GetBranch();
                    string compareVersions =
                        $"https://api.mullak99.co.uk/FAES/CompareVersions.php?app=faes_gui&branch={"dev"}&version1={currentVer}&version2={latestVer}";

                    WebClient    client = new WebClient();
                    byte[]       html   = client.DownloadData(compareVersions);
                    UTF8Encoding utf    = new UTF8Encoding();
                    string       result = utf.GetString(html).ToLower();

                    if (string.IsNullOrEmpty(result) || result == "null")
                    {
                        Logging.Log("Unable to connect to the update server! Please check your internet connection.", Severity.WARN);
                    }
                    else if (result.Contains("not exist in the database!") || result == "version1 is newer than version2")
                    {
                        Logging.Log($"You are on a private build. ({currentVer} is newer than {latestVer}).");
                    }
                    else if (result == "version1 is older than version2")
                    {
                        Logging.Log($"You are on an outdated build. ({currentVer} is older than {latestVer}).");
                    }
                    else if (result == "version1 is equal to version2")
                    {
                        Logging.Log($"You are on the latest build. ({currentVer} is equal to {latestVer}).");
                    }
                    else
                    {
                        Logging.Log("Unable to connect to the update server! Please check your internet connection.", Severity.WARN);
                    }
                }
                catch
                {
                    Logging.Log("Unable to connect to the update server! Please check your internet connection.", Severity.WARN);
                }

                DoCheckUpdate();
            }
            else if (input[0] == "spoofversion" || input[0] == "spoof")
            {
                if (input.Length > 1 && !string.IsNullOrEmpty(input[1]))
                {
                    string verToSpoof = "";

                    if (input[1].Contains("\"") || input[1].Contains("\'"))
                    {
                        for (int i = 1; i < input.Length; i++)
                        {
                            verToSpoof += input[i].Replace("\"", "").Replace("\'", "");
                            verToSpoof += " ";
                        }
                        verToSpoof = verToSpoof.TrimEnd(' ');
                    }
                    else
                    {
                        verToSpoof = input[1];
                    }

                    if (verToSpoof.ToLower() == "reset" || verToSpoof.ToLower() == "off" || verToSpoof.ToLower() == "false")
                    {
                        Logging.Log("Disabled Version Spoofing.");
                        Program.SetSpoofedVersion(false);
                    }
                    else
                    {
                        Logging.Log($"Enabled Version Spoofing. Spoofing Version: {verToSpoof}");
                        Program.SetSpoofedVersion(true, verToSpoof);
                    }
                }
                else
                {
                    Logging.Log("Disabled Version Spoofing.");
                    Program.SetSpoofedVersion(false);
                }
            }
            else if (input[0] == "getselectedbranch" || input[0] == "branch" || input[0] == "getbranch")
            {
                Logging.Log($"FAES_GUI Branch: {Program.programManager.GetBranch()}");
            }
            else if (input[0] == "setselectedbranch" || input[0] == "setbranch")
            {
                if (input.Length > 1 && !string.IsNullOrEmpty(input[1]))
                {
                    string rawBranchRequest = input[1];
                    string validBranch;

                    if (rawBranchRequest.ToLower() == "stable" || rawBranchRequest.ToLower() == "beta" || rawBranchRequest.ToLower() == "dev")
                    {
                        validBranch = rawBranchRequest.ToLower();
                        Program.programManager.SetBranch(validBranch);
                        Logging.Log($"FAES_GUI Branch changed to: {validBranch}");
                    }
                    else
                    {
                        Logging.Log($"'{rawBranchRequest}' is not a valid branch!", Severity.WARN);
                    }
                }
                else
                {
                    TooFewArgsError(textbox.Text);
                }
            }
            else if (input[0] == "exportlog" || input[0] == "export" || input[0] == "log")
            {
                ExportLog_Click(null, null);
            }
            else if (input[0] == "setlogpath")
            {
                if (input.Length > 1 && !string.IsNullOrEmpty(input[1]))
                {
                    _overrideLogPath = input[1].Replace("\"", string.Empty).Replace("\'", string.Empty);
                    Program.programManager.SetLogPath(_overrideLogPath);

                    Logging.Log($"Log path changed to: {_overrideLogPath}");
                }
                else
                {
                    TooFewArgsError(textbox.Text);
                }
            }
            else if (input[0] == "getlogpath" || input[0] == "logpath")
            {
                _overrideLogPath = Program.programManager.GetLogPath();
                Logging.Log($"Log path set to: {_overrideLogPath}");
            }
            else if (input[0] == "resetlogpath")
            {
                Program.programManager.ResetLogPath();
                Logging.Log("Log path reset!");
            }
            else if (input[0] == "setdevmode" || input[0] == "setdevelopermode" || input[0] == "setdebugmode" || input[0] == "setdebug" || input[0] == "setdev" || input[0] == "setdeveloper")
            {
                if (input.Length > 1 && !string.IsNullOrEmpty(input[1]))
                {
                    bool dev = false;
                    if (input[1] == "1" || input[1] == "true" || input[1] == "t" || input[1] == "y" || input[1] == "yes")
                    {
                        dev = true;
                    }

                    Program.programManager.SetDevMode(dev);

                    Logging.Log(
                        $"Developer Mode {(dev ? "Enabled" : "Disabled")}! (Setting will be applied next launch)");
                }
                else
                {
                    TooFewArgsError(textbox.Text);
                }
            }
            else if (input[0] == "getdevmode" || input[0] == "getdevelopermode" || input[0] == "getdebugmode" || input[0] == "getdebug" || input[0] == "getdev" || input[0] == "getdeveloper" || input[0] == "developer" || input[0] == "dev" || input[0] == "debug")
            {
                Logging.Log($"Developer Mode is {(Program.programManager.GetDevMode() ? "Enabled" : "Disabled")}!");
            }
            else if (input[0] == "resetdevmode" || input[0] == "resetdevelopermode" || input[0] == "resetdebugmode" || input[0] == "resetdebug" || input[0] == "resetdev" || input[0] == "resetdeveloper")
            {
                Program.programManager.ResetDevMode();
                Logging.Log("Developer Mode reset!");
            }
            else if (input[0] == "clear" || input[0] == "cls")
            {
                clearConsole.PerformClick();
            }
            else
            {
                Logging.Log($"Unknown command: {textbox.Text}", Severity.WARN);
            }

            textbox.Clear();
        }
Esempio n. 12
0
        static void Main(string[] args)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            for (int i = 0; i < args.Length; i++)
            {
                string strippedArg = args[i].ToLower();

                if (Directory.Exists(args[i]))
                {
                    _directory = args[i];
                }
                else if (File.Exists(args[i]))
                {
                    _directory = args[i];
                }

                strippedArg = strippedArg.TrimStart('-', '/', '\\');

                if (strippedArg == "verbose" || strippedArg == "v" || strippedArg == "developer" || strippedArg == "dev" || strippedArg == "debug")
                {
                    _verbose = true;
                }
                else if (strippedArg == "password" || strippedArg == "p" && !string.IsNullOrEmpty(args[i + 1]))
                {
                    _password = args[i + 1];
                }
                else if (string.IsNullOrEmpty(_passwordHint) && (strippedArg == "hint" || strippedArg == "passwordhint" || strippedArg == "h") && !string.IsNullOrEmpty(args[i + 1]))
                {
                    _passwordHint = args[i + 1];
                }
                else if (strippedArg == "purgetemp" || strippedArg == "deletetemp")
                {
                    _purgeTemp = true;
                }
                else if (strippedArg == "headless" || strippedArg == "cli" || strippedArg == "commandline")
                {
                    _headless = true;
                }
                else if (strippedArg == "showprogress" || strippedArg == "progress" || strippedArg == "prog")
                {
                    if (!string.IsNullOrEmpty(args[i + 1]) && UInt16.TryParse(args[i + 1], out _progressSleep))
                    {
                    }
                    _showProgress = true;
                }
                else if (strippedArg == "faesversion" || strippedArg == "faes" || strippedArg == "faesver")
                {
                    _getFaesVersion = true;
                }
                else if (strippedArg == "faesguiversion" || strippedArg == "faesguiver" || strippedArg == "faesgui" || strippedArg == "guiver" || strippedArg == "ver")
                {
                    _getVersion     = true;
                    _getFaesVersion = true;
                }
                else if (string.IsNullOrEmpty(_compressionMethod) && (strippedArg == "compression" || strippedArg == "compressionmethod" || strippedArg == "c") && !string.IsNullOrEmpty(args[i + 1]))
                {
                    _compressionMethod = args[i + 1].ToUpper();
                }
                else if ((strippedArg == "level" || strippedArg == "compressionlevel" || strippedArg == "l") && !string.IsNullOrEmpty(args[i + 1]))
                {
                    Int32.TryParse(args[i + 1], out _compressionLevel);
                }
                else if (strippedArg == "overwrite" || strippedArg == "overwriteduplicates" || strippedArg == "o")
                {
                    _overwriteDuplicates = true;
                }
                else if (strippedArg == "preserveoriginal" || strippedArg == "original" || strippedArg == "po")
                {
                    _deleteOriginalFile = false;
                }
                else if (strippedArg == "genfullinstallconfig")
                {
                    _genFullInstallConfig = true;
                }
                else if (strippedArg == "associatefiletypes" || strippedArg == "filetypes")
                {
                    _associateFileTypes = true;
                }
                else if (strippedArg == "startmenushortcuts" || strippedArg == "startmenu")
                {
                    _startMenuShortcuts = true;
                }
                else if (strippedArg == "contextmenus" || strippedArg == "context")
                {
                    _contextMenus = true;
                }
                else if (strippedArg == "installbranch" && !string.IsNullOrEmpty(args[i + 1]))
                {
                    _installBranch = args[i + 1];
                }
                else if (strippedArg == "peek" || strippedArg == "filepeek")
                {
                    _doFilePeek = true;
                }

                _strippedArgs.Add(strippedArg);
            }
            FileAES_Utilities.SetVerboseLogging(_verbose);
            SSM.SetVerboseLogging(_verbose);

            try
            {
                if (File.Exists("FAES-Updater.exe"))
                {
                    File.Delete("FAES-Updater.exe");
                }
            }
            catch
            {
                // ignored
            }

            if (_purgeTemp)
            {
                FileAES_Utilities.PurgeTempFolder();
            }

            if (_getVersion)
            {
                Console.WriteLine("Current FileAES Version: {0}", GetVersion());
                Console.WriteLine("Current FileAES Build Date: {0}", GetBuildDateFormatted());
            }

            if (_getFaesVersion)
            {
                Console.WriteLine("Current FAES Version: {0}", FileAES_Utilities.GetVersion());
            }

            if (!string.IsNullOrEmpty(_directory) && !string.IsNullOrEmpty(_password) && _headless)
            {
                faesFile = new FAES_File(_directory);

                Console.WriteLine("FileAES-GUI (FileAES) only has basic command-line support. Use FileAES-CLI for improved command-line functionality.");

                try
                {
                    if (_compressionLevel < 0 || _compressionLevel > 9)
                    {
                        Console.WriteLine("You have not specified a valid compression level! Please choose a value between 0 and 9.");
                    }
                    else
                    {
                        if (faesFile.IsFileEncryptable())
                        {
                            FileAES_Encrypt encrypt = new FileAES_Encrypt(faesFile, _password, _passwordHint, Optimise.Balanced, null, _deleteOriginalFile, _overwriteDuplicates);

                            if (!string.IsNullOrEmpty(_compressionMethod))
                            {
                                switch (_compressionMethod)
                                {
                                case "ZIP":
                                    encrypt.SetCompressionMode(CompressionMode.ZIP, _compressionLevel);
                                    break;

                                case "TAR":
                                    encrypt.SetCompressionMode(CompressionMode.TAR, _compressionLevel);
                                    break;

                                case "LZMA":
                                    encrypt.SetCompressionMode(CompressionMode.LZMA, _compressionLevel);
                                    break;

                                case "GZIP":
                                    encrypt.SetCompressionMode(CompressionMode.GZIP, _compressionLevel);
                                    break;

                                case "LGYZIP":
                                case "LEGACYZIP":
                                case "LEGACY":
                                    encrypt.SetCompressionMode(CompressionMode.LGYZIP, _compressionLevel);
                                    break;

                                default:
                                    Console.WriteLine("Unknown Compression Method: {0}", _compressionMethod);
                                    return;
                                }
                            }

                            Thread progressThread = new Thread(() =>
                            {
                                while (_showProgress)
                                {
                                    ushort percentComplete = Convert.ToUInt16(encrypt.GetEncryptionPercentComplete());
                                    Console.WriteLine(_verbose ? "[INFO] Progress: {0}%" : "Progress: {0}%", percentComplete);
                                    Thread.Sleep(_progressSleep);
                                }
                            });

                            Thread eThread = new Thread(() =>
                            {
                                try
                                {
                                    if (encrypt.EncryptFile())
                                    {
                                        if (_showProgress)
                                        {
                                            Console.WriteLine(_verbose ? "[INFO] Progress: 100%" : "Progress: 100%");
                                        }

                                        Console.WriteLine("Encryption on {0} succeeded!", faesFile.getFaesType().ToLower());
                                    }
                                    else
                                    {
                                        Console.WriteLine("Encryption on {0} failed!", faesFile.getFaesType().ToLower());
                                    }
                                }
                                catch (Exception e)
                                {
                                    progressThread.Abort();
                                    HandleException(e);
                                }
                            });

                            if (_showProgress)
                            {
                                progressThread.Start();
                            }
                            eThread.Start();

                            while (eThread.ThreadState == ThreadState.Running)
                            {
                            }

                            progressThread.Abort();
                        }
                        else
                        {
                            FileAES_Decrypt decrypt = new FileAES_Decrypt(faesFile, _password, _deleteOriginalFile, _overwriteDuplicates);

                            Thread progressThread = new Thread(() =>
                            {
                                while (_showProgress)
                                {
                                    ushort percentComplete = Convert.ToUInt16(decrypt.GetDecryptionPercentComplete());

                                    Console.WriteLine(_verbose ? "[INFO] Progress: {0}%" : "Progress: {0}%", percentComplete);
                                    Thread.Sleep(_progressSleep);
                                }
                            });

                            Thread dThread = new Thread(() =>
                            {
                                try
                                {
                                    if (decrypt.DecryptFile())
                                    {
                                        if (_showProgress)
                                        {
                                            Console.WriteLine(_verbose ? "[INFO] Progress: 100%" : "Progress: 100%");
                                        }

                                        Console.WriteLine("Decryption on {0} succeeded!", faesFile.getFaesType().ToLower());
                                    }
                                    else
                                    {
                                        Console.WriteLine("Decryption on {0} failed!", faesFile.getFaesType().ToLower());
                                        Console.WriteLine("Ensure that you entered the correct password!");
                                        Console.WriteLine("Password Hint: {0}", faesFile.GetPasswordHint());
                                    }
                                }
                                catch (Exception e)
                                {
                                    progressThread.Abort();
                                    HandleException(e);
                                }
                            });

                            if (_showProgress)
                            {
                                progressThread.Start();
                            }
                            dThread.Start();

                            while (dThread.ThreadState == ThreadState.Running)
                            {
                            }

                            progressThread.Abort();
                        }
                    }
                }
                catch (Exception e)
                {
                    HandleException(e);
                }
            }
            else if (_genFullInstallConfig)
            {
                programManager = new ProgramManager(ProgramManager.InstallType.FullInstall);
                programManager.SetBranch(_installBranch);
                programManager.SetAssociateFileTypes(_associateFileTypes);
                programManager.SetStartMenuShortcuts(_startMenuShortcuts);
                programManager.SetContextMenus(_contextMenus);

                Application.Exit();
            }
            else
            {
                programManager = new ProgramManager();
                if (!FileAES_Utilities.GetVerboseLogging())
                {
                    FileAES_Utilities.SetVerboseLogging(programManager.GetDevMode());
                }

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                if (!string.IsNullOrEmpty(_directory))
                {
                    faesFile = new FAES_File(_directory);

                    if (faesFile.IsFileEncryptable())
                    {
                        Application.Run(new EncryptForm(faesFile));
                    }
                    else if (faesFile.IsFileDecryptable())
                    {
                        if (_doFilePeek && IsFileValidForPeek(faesFile))
                        {
                            Application.Run(new PeekForm(faesFile));
                        }
                        else
                        {
                            Application.Run(new DecryptForm(faesFile));
                        }
                    }
                }
                else
                {
                    Application.Run(new MainForm());
                }
            }
        }
Esempio n. 13
0
        static void Main(string[] args)
        {
            tempPathInstance = Path.Combine(Path.GetTempPath(), "FileAES");
            List <string> arguments = new List <string>();

            arguments.AddRange(args);
            if (File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), _fullInstallPath)))
            {
                arguments.AddRange(ReadLaunchParams());
            }
            if (File.Exists(_localInstallPath))
            {
                arguments.AddRange(ReadLaunchParams(true));
            }

            string[] param = arguments.ToArray();

            for (int i = 0; i < param.Length; i++)
            {
                param[i].ToLower();

                if (File.Exists(param[i]) && FileAES_Utilities.isFileDecryptable(param[i]) && !doEncryptFile && !doEncryptFolder)
                {
                    doDecrypt = true;
                    fileName  = param[i];
                }
                else if (Directory.Exists(param[i]) && !doDecrypt && !doEncryptFile)
                {
                    doEncryptFolder = true;
                    fileName        = param[i];
                }
                else if (File.Exists(param[i]) && !doDecrypt && !doEncryptFolder)
                {
                    doEncryptFile = true;
                    fileName      = param[i];
                }

                if (param[i].Equals("-fullinstall") || param[i].Equals("--fullinstall") || param[i].Equals("-f") || param[i].Equals("--f"))
                {
                    _fullInstall = true;
                }
                else if (param[i] == "--associatefiletypes")
                {
                    _associateFileTypes = true;
                }
                else if (param[i] == "--startmenushortcuts")
                {
                    _startMenuShortcuts = true;
                }
                else if (param[i] == "--contextmenus")
                {
                    _contextMenus = true;
                }
                else if (param[i] == "--dev")
                {
                    _branch = "dev";
                }
                else if (param[i] == "--beta")
                {
                    _branch = "beta";
                }
                else if (param[i] == "--stable")
                {
                    _branch = "stable";
                }
                else if (param[i] == "--skipupdate" || param[i] == "-skipupdate")
                {
                    _skipUpdate = true;
                }
                else if (param[i].Equals("-cleanupdates") || param[i].Equals("--cleanupdates") || param[i].Equals("-c") || param[i].Equals("--c"))
                {
                    _cleanUpdates = true;
                }
                else if (param[i].Equals("-update") || param[i].Equals("--update") || param[i].Equals("-u") || param[i].Equals("--u"))
                {
                    FileAES_Update.UpdateSelf(_cleanUpdates);
                }
                else if (param[i].Equals("-password") || param[i].Equals("--password") || param[i].Equals("-p") || param[i].Equals("--p") && !String.IsNullOrEmpty(param[i + 1]))
                {
                    _autoPassword = param[i + 1];
                }
                else if (param[i].Equals("-purgetemp") || param[i].Equals("--purgetemp") || param[i].Equals("-deletetemp") || param[i].Equals("--deletetemp"))
                {
                    _purgeTemp = true;
                }
                else if (param[i].Equals("-debug") || param[i].Equals("--debug") || param[i].Equals("-developer") || param[i].Equals("--developer"))
                {
                    _debugMode = true;
                }
                else if (param[i].Equals("-peek") || param[i].Equals("--peek") || param[i].Equals("-filepeek") || param[i].Equals("--filepeek"))
                {
                    _doFilePeek = true;
                }
                else if (param[i].Equals("-tempencrypt") || param[i].Equals("--tempencrypt") || param[i].Equals("-temp") || param[i].Equals("--temp"))
                {
                    _useLocalEncrypt = false;
                }
            }
            if (String.IsNullOrEmpty(_branch))
            {
                _branch = "stable";
            }

            if (_purgeTemp)
            {
                FileAES_Utilities.PurgeTempFolder();
            }
            if (File.Exists("FAES-Updater.exe"))
            {
                File.Delete("FAES-Updater.exe");
            }

            Core core = new Core();

            if (_branch == "stable" && (core.IsBetaBuild() || core.IsDevBuild()))
            {
                _branch = core.GetBuild();
            }
            else if (_branch == "beta" && core.IsDevBuild())
            {
                _branch = core.GetBuild();
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            if (doEncryptFile || doEncryptFolder)
            {
                Application.Run(new FileAES_Encrypt(fileName, _autoPassword));
            }
            else if (doDecrypt)
            {
                if (_doFilePeek && IsFileValidForPeek(new FAES_File(fileName)))
                {
                    Application.Run(new FileAES_Peek(fileName, _autoPassword));
                }
                else
                {
                    Application.Run(new FileAES_Decrypt(fileName, _autoPassword));
                }
            }
            else
            {
                Application.Run(new FileAES_Main());
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Decrypts the selected file using the given password
        /// </summary>
        /// <param name="faesMetaData">Formatted Metadata used at the start of a file</param>
        /// <param name="inputFilePath">File path for encrypted file</param>
        /// <param name="outputFilePath">File path for unencrypted file</param>
        /// <param name="encryptionPassword">Encryption Password</param>
        /// <param name="percentComplete">Percent completion of the encryption process</param>
        /// <returns>If the decryption was successful</returns>
        internal bool Decrypt(MetaData faesMetaData, string inputFilePath, string outputFilePath, string encryptionPassword, ref decimal percentComplete)
        {
            CipherMode cipher = CipherMode.CBC;

            byte[] metaData      = new byte[faesMetaData.GetLength()];
            byte[] salt          = new byte[32];
            byte[] passwordBytes = Encoding.UTF8.GetBytes(encryptionPassword);

            FileStream inputDataStream = new FileStream(inputFilePath, FileMode.Open);

            inputDataStream.Read(metaData, 0, faesMetaData.GetLength());
            inputDataStream.Read(salt, 0, salt.Length);

            const int          keySize   = 256;
            const int          blockSize = 128;
            Rfc2898DeriveBytes key       = new Rfc2898DeriveBytes(passwordBytes, salt, 51200);
            RijndaelManaged    AES       = new RijndaelManaged
            {
                KeySize   = blockSize,
                BlockSize = 128,
                Key       = key.GetBytes(keySize / 8),
                IV        = key.GetBytes(blockSize / 8),
                Padding   = PaddingMode.PKCS7,
                Mode      = cipher
            };

            try
            {
                CryptoStream crypto           = new CryptoStream(inputDataStream, AES.CreateDecryptor(), CryptoStreamMode.Read);
                FileStream   outputDataStream = new FileStream(outputFilePath, FileMode.Create);

                try
                {
                    byte[] buffer           = new byte[FileAES_Utilities.GetCryptoStreamBuffer()];
                    long   expectedComplete = salt.Length + AES.KeySize + AES.BlockSize;

                    try
                    {
                        Logging.Log("Beginning writing decrypted data...", Severity.DEBUG);
                        int read;
                        while ((read = crypto.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            try
                            {
                                percentComplete = Math.Ceiling((decimal)((Convert.ToDouble(outputDataStream.Length) / Convert.ToDouble(expectedComplete)) * 100));
                                if (percentComplete > 100)
                                {
                                    percentComplete = 100;
                                }
                            }
                            catch
                            {
                                // ignored
                            }

                            outputDataStream.Write(buffer, 0, read);
                        }
                        Logging.Log("Finished writing decrypted data.", Severity.DEBUG);
                    }
                    catch
                    {
                        outputDataStream.Close();
                    }

                    crypto.Close();
                    outputDataStream.Close();
                    inputDataStream.Close();

                    bool doesHashMatch = false;

                    switch (faesMetaData.GetHashType())
                    {
                    case Checksums.ChecksumType.SHA1:
                        doesHashMatch = Checksums.CompareHash(faesMetaData.GetOrigHash(), Checksums.GetSHA1(outputFilePath));
                        break;

                    case Checksums.ChecksumType.SHA256:
                        doesHashMatch = Checksums.CompareHash(faesMetaData.GetOrigHash(), Checksums.GetSHA256(outputFilePath));
                        break;

                    case Checksums.ChecksumType.SHA512:
                        doesHashMatch = Checksums.CompareHash(faesMetaData.GetOrigHash(), Checksums.GetSHA512(outputFilePath));
                        break;

                    case Checksums.ChecksumType.SHA384:
                        doesHashMatch = Checksums.CompareHash(faesMetaData.GetOrigHash(), Checksums.GetSHA384(outputFilePath));
                        break;
                    }
                    if (!doesHashMatch)
                    {
                        Logging.Log("Invalid Checksum detected! Assuming password is incorrect.", Severity.DEBUG);
                        return(false);
                    }
                    Logging.Log("Valid Checksum detected!", Severity.DEBUG);
                    return(true);
                }
                catch
                {
                    crypto.Close();
                    inputDataStream.Close();
                    outputDataStream.Close();

                    return(false);
                }
            }
            catch (CryptographicException)
            {
                inputDataStream.Close();

                return(false);
            }
        }
Esempio n. 15
0
        static void Main(string[] args)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            for (int i = 0; i < args.Length; i++)
            {
                string strippedArg = args[i].ToLower();

                if (Directory.Exists(args[i]))
                {
                    _directory = args[i];
                }
                else if (File.Exists(args[i]))
                {
                    _directory = args[i];
                }

                strippedArg = strippedArg.TrimStart('-', '/', '\\');

                if (strippedArg == "verbose" || strippedArg == "v")
                {
                    _verbose = true;
                    FileAES_Utilities.SetVerboseLogging(_verbose);
                }
                else if (string.IsNullOrEmpty(_password) && (strippedArg == "password" || strippedArg == "p") && !string.IsNullOrEmpty(args[i + 1]))
                {
                    _password = args[i + 1];
                }
                else if (strippedArg == "purgetemp" || strippedArg == "deletetemp")
                {
                    _purgeTemp = true;
                }
                else if (strippedArg == "help")
                {
                    _help = true;
                }
                else if (string.IsNullOrEmpty(_passwordHint) && (strippedArg == "hint" || strippedArg == "passwordhint" || strippedArg == "h") && !string.IsNullOrEmpty(args[i + 1]))
                {
                    _passwordHint = args[i + 1];
                }
                else if (strippedArg == "gethint" || strippedArg == "getpasswordhint")
                {
                    _getHint = true;
                }
                else if (strippedArg == "gettimestamp" || strippedArg == "timestamp" || strippedArg == "encryptiondate")
                {
                    _getEncryptTimestamp = true;
                }
                else if (strippedArg == "getcompression" || strippedArg == "getcompressionmethod")
                {
                    _getEncryptCompression = true;
                }
                else if (strippedArg == "showprogress" || strippedArg == "progress" || strippedArg == "prog")
                {
                    if (!string.IsNullOrEmpty(args[i + 1]) && UInt16.TryParse(args[i + 1], out _progressSleep))
                    {
                    }
                    _showProgress = true;
                }
                else if (strippedArg == "faesversion" || strippedArg == "faes" || strippedArg == "faesver")
                {
                    _getFaesVersion = true;
                }
                else if (strippedArg == "faescliversion" || strippedArg == "faescliver" || strippedArg == "faescli" || strippedArg == "cliver" || strippedArg == "ver" || strippedArg == "version")
                {
                    _getVersion     = true;
                    _getFaesVersion = true;
                }
                else if (string.IsNullOrEmpty(_compressionMethod) && (strippedArg == "compression" || strippedArg == "compressionmethod" || strippedArg == "c") && !string.IsNullOrEmpty(args[i + 1]))
                {
                    _compressionMethod = args[i + 1].ToUpper();
                }
                else if ((strippedArg == "level" || strippedArg == "compressionlevel" || strippedArg == "l") && !string.IsNullOrEmpty(args[i + 1]))
                {
                    Int32.TryParse(args[i + 1], out _compressionLevel);
                }
                else if (strippedArg == "buffer" || strippedArg == "cryptostreambuffer" || strippedArg == "csbuffer" && !string.IsNullOrEmpty(args[i + 1]))
                {
                    UInt32.TryParse(args[i + 1], out _csBuffer);
                }
                else if (strippedArg == "overwrite" || strippedArg == "overwriteduplicates" || strippedArg == "o")
                {
                    _overwriteDuplicates = true;
                }
                else if (strippedArg == "preserveoriginal" || strippedArg == "original" || strippedArg == "po")
                {
                    _deleteOriginalFile = false;
                }
                else if (strippedArg == "showallmetadata" || strippedArg == "showmetadata" || strippedArg == "metadata")
                {
                    _showAllMetadata = true;
                }
                else if (strippedArg == "showallutf8metadata" || strippedArg == "showutf8metadata" || strippedArg == "utf8metadata")
                {
                    _showAllMetadataString = true;
                }
                else if (strippedArg == "" || strippedArg == "showutf8metadata" || strippedArg == "utf8metadata")
                {
                    _showAllMetadataString = true;
                }
                else if (strippedArg == "tempencrypt" || strippedArg == "temp")
                {
                    _useLocalEncrypt = false;
                }
                else if (strippedArg == "localencrypt" || strippedArg == "local")
                {
                    _useLocalEncrypt = true;
                }
                else if (strippedArg == "showlatest" || strippedArg == "getlatest" || strippedArg == "getlatestversion" || strippedArg == "latestversion" || strippedArg == "latest")
                {
                    _showLatestVer = true;

                    if (args.Length > (i + 1) && !string.IsNullOrEmpty(args[i + 1]))
                    {
                        string arg = args[i + 1];

                        if (arg.ToLower() == "dev" || arg.ToLower() == "developer" || arg.ToLower() == "d")
                        {
                            _showLatestBranch = "dev";
                        }
                        else if (arg.ToLower() == "beta" || arg.ToLower() == "b")
                        {
                            _showLatestBranch = "beta";
                        }
                        else if (arg.ToLower() == "stable" || arg.ToLower() == "s" || arg.ToLower() == "release" || arg.ToLower() == "r")
                        {
                            _showLatestBranch = "stable";
                        }
                    }
                }
                else if (strippedArg == "noupdatecheck" || strippedArg == "nocheck" || strippedArg == "offline" || strippedArg == "noupdate")
                {
                    _checkForUpdate = false;
                }
                else if (strippedArg == "update" || strippedArg == "u")
                {
                    string branch  = "";
                    string version = "";

                    if (args.Length > (i + 1) && !string.IsNullOrEmpty(args[i + 1]))
                    {
                        string arg = args[i + 1];

                        {
BranchFinder:
                            switch (arg.ToLower())
                            {
                            case "dev":
                            case "developer":
                            case "d":
                                branch = "dev";
                                break;

                            case "beta":
                            case "b":
                                branch = "beta";
                                break;

                            case "stable":
                            case "s":
                            case "release":
                            case "r":
                                branch = "stable";
                                break;

                            default:
                            {
                                if (args.Length > (i + 2) && !string.IsNullOrEmpty(args[i + 2]) && string.IsNullOrWhiteSpace(version))
                                {
                                    version = args[i + 1];
                                    arg     = args[i + 2];
                                    goto BranchFinder;
                                }
                                break;
                            }
                            }
                        }

                        if (string.IsNullOrEmpty(branch) && string.IsNullOrEmpty(version) && args.Length > (i + 1) && !string.IsNullOrEmpty(args[i + 1]))
                        {
                            version = args[i + 1];
                        }
                    }

                    if (args.Length > (i + 1) && string.IsNullOrEmpty(args[i + 1]) && args[i + 1].ToLower() == "force")
                    {
                        _forceUpdate = true;
                    }
                    else if (args.Length > (i + 2) && string.IsNullOrEmpty(args[i + 2]) && args[i + 2].ToLower() == "force")
                    {
                        _forceUpdate = true;
                    }
                    else if (args.Length > (i + 3) && string.IsNullOrEmpty(args[i + 3]) && args[i + 3].ToLower() == "force")
                    {
                        _forceUpdate = true;
                    }

                    if (!string.IsNullOrWhiteSpace(branch))
                    {
                        _updateBranch = branch;
                    }
                    if (!string.IsNullOrWhiteSpace(version))
                    {
                        _updateToVer = version;
                    }

                    _doUpdate = true;
                }

                _strippedArgs.Add(strippedArg);
            }

            if (_checkForUpdate)
            {
                if (_updateBranch == "unknown")
                {
                    if (IsDevBuild())
                    {
                        _updateBranch = "dev";
                    }
                    else if (IsBetaBuild())
                    {
                        _updateBranch = "beta";
                    }
                    else
                    {
                        _updateBranch = "stable";
                    }
                }

                _update = new Update("dev");
            }

            if (_showLatestBranch == "unknown")
            {
                _showLatestBranch = _updateBranch;
            }

            if (_help)
            {
                Logging.Log("A FAES-based tool for encrypting and decrypting files using the command-line.\n\nPossible Launch Parameters:\n'--verbose' or '-v': Show more debugging information in the console (WIP)." +
                            "\n'--purgeTemp' or '-p': Purge the FileAES Temp folder to resolve possible errors.\n'--password <password>' or '-p <password>': Sets the password that will be used to encrypt/decrypt the file/folder." +
                            "\n'--hint <Password Hint>' or '-h <Password Hint>': Sets a password hint.\n'--compression <ZIP/TAR/LZMA/LEGACYZIP>' or '-c <ZIP/TAR/LZMA/LEGACYZIP>': Sets the compression method that will be used to encrypt the file/folder." +
                            "\n'--level <0-9>' or '-l <0-9>': Sets the compression level that will be used to encrypt the file/folder. (Only works for with the ZIP compression method)" +
                            ".\n'--getHint': Gets the password hint for the encrypted file.\n'--getTimestamp': Gets the encryption timestamp of the encrypted file." +
                            "\n'--getCompression': Gets the compression method of the encrypted file.\n'--ver': Gets the current version of FileAES-CLI and FAES being used." +
                            "\n'--FAES': Gets the current version of FAES being used.\n'--overwrite' or '-o': Overwrites any duplicate files found within the FAES process." +
                            "\n'--original' or '-po': Preserves the original file used in the encrypt/decrypt process." +
                            "\n'--progress [<Polling Rate (ms)>]': Outputs the current encryption/decryption progress to the console after desired time (Leaving polling rate blank defaults to 5000ms)." +
                            "\n'--buffer <Size (bytes)>': Sets the size of the FAES CryptoStream buffer.\n'--metadata': Shows the raw metadeta (Hex) of the encrypted file." +
                            "\n'--utf8metadata': Shows the raw metadeta (Decoded UTF8) of the encrypted file.\n'--offline': Disables auto-update checking." +
                            "\n'--latest [<branch>]': Outputs the latest version of FileAES-CLI on that branch (Leaving branch blank defaults to current builds branch)." +
                            "\n'--update [<version>] [<branch>] [force]': Updates FileAES-CLI as specified. Using no arguments updates to the latest version on the current branch.\n\n" +
                            "\n'--localEncrypt' or '-local': Encrypt files within the same folder as the source file (Default behaviour).\n\n" +
                            "\n'--tempEncrypt' or '-temp': Encrypt files within the OS' Temp folder (Old behaviour).\n\n" +
                            "File/Folder names can be entered as a launch parameter to select what to encrypt/decrypt (also allows for dragging/dropping a file/folder on the .exe).\n\n" +
                            "Example: 'FileAES-CLI.exe File.txt -p password123'");
                return;
            }

            if (_doUpdate)
            {
                if (_update != null && _checkForUpdate)
                {
                    _update.CheckForUpdateNonThreadded(true);

                    bool doUpdate = false;

                    if ((!_forceUpdate && _update.IsUpdate()) || _forceUpdate || _updateToVer != "latest")
                    {
                        if (_updateToVer == "latest")
                        {
                            string latestVer = _update.GetLatestVersion();
                            Logging.Log($"Installing FileAES-CLI {latestVer}...");
                            doUpdate = true;
                        }
                        else if (_update.DoesVersionExist(_updateToVer, "dev"))
                        {
                            Logging.Log($"Installing FileAES-CLI {_updateToVer}...");
                            doUpdate = true;
                        }
                        else
                        {
                            Logging.Log($"Could not find FileAES-CLI {_updateToVer}!", Severity.WARN);
                        }

                        if (doUpdate)
                        {
                            _update.UpdateSelf(true, _updateToVer);
                            return;
                        }
                    }
                }
            }
            else if (_checkForUpdate)
            {
                _update.CheckForUpdate();
            }

            if (_purgeTemp)
            {
                FileAES_Utilities.PurgeTempFolder();
            }

            if (_getVersion)
            {
                Logging.Log($"Current FileAES-CLI Version: {GetVersion()}");
                if (!_getFaesVersion)
                {
                    return;
                }
            }

            if (_getFaesVersion)
            {
                Logging.Log($"Current FAES Version: {FileAES_Utilities.GetVersion()}");
                return;
            }

            if (_showLatestVer)
            {
                if (_checkForUpdate)
                {
                    _update.SetBranch(_showLatestBranch);

                    string latestVer = _update.GetLatestVersion();

                    if (latestVer != "v0.0.0")
                    {
                        Logging.Log(
                            $"The latest FileAES-CLI version on branch '{_showLatestBranch.ToUpper()}' is: {latestVer}");
                    }
                    else
                    {
                        Logging.Log("The latest FileAES-CLI version could not be found! Please check your internet connection.", Severity.WARN);
                    }

                    _update.SetBranch(_updateBranch);
                }

                else
                {
                    Logging.Log("The latest version cannot be displayed when the program is in offline mode!");
                }

                return;
            }

            if (_getHint)
            {
                if (File.Exists(_directory) && FileAES_Utilities.IsFileDecryptable(_directory))
                {
                    string passHint = FileAES_Utilities.GetPasswordHint(_directory);

                    if (passHint != "No Password Hint Set")
                    {
                        Logging.Log($"The hint for '{Path.GetFileName(_directory)}' is: {passHint}");
                    }
                    else
                    {
                        Logging.Log($"'{Path.GetFileName(_directory)}' does not contain a password hint!");
                    }

                    if (string.IsNullOrEmpty(_password) && (!_getEncryptTimestamp || !_getEncryptCompression))
                    {
                        return;
                    }
                }
                else
                {
                    Logging.Log("You have not specified a valid encrypted file!", Severity.WARN);
                    return;
                }
            }

            if (_getEncryptTimestamp)
            {
                if (File.Exists(_directory) && FileAES_Utilities.IsFileDecryptable(_directory))
                {
                    long timestamp = FileAES_Utilities.GetEncryptionTimeStamp(_directory);

                    if (timestamp >= 0)
                    {
                        DateTime dateTime = FileAES_Utilities.UnixTimeStampToDateTime((double)timestamp);
                        Logging.Log(
                            $"'{Path.GetFileName(_directory)}' was encrypted on {dateTime.ToString("dd/MM/yyyy")} at {dateTime.ToString("HH:mm:ss tt")}.");
                    }
                    else
                    {
                        Logging.Log("This file does not contain a encryption date. This is likely due to this file being encrypted using an older FAES version.");
                    }

                    if (string.IsNullOrEmpty(_password) && !_getEncryptCompression)
                    {
                        return;
                    }
                }
                else
                {
                    Logging.Log("You have not specified a valid encrypted file!", Severity.WARN);
                    return;
                }
            }

            if (_getEncryptCompression)
            {
                if (File.Exists(_directory) && FileAES_Utilities.IsFileDecryptable(_directory))
                {
                    string compressionMode = FileAES_Utilities.GetCompressionMode(_directory);

                    if (compressionMode != "LGYZIP")
                    {
                        Logging.Log(
                            $"The Compression Mode used for '{Path.GetFileName(_directory)}' is: {compressionMode}");
                    }
                    else
                    {
                        Logging.Log(
                            $"The Compression Mode used for '{Path.GetFileName(_directory)}' is: LGYZIP (LEGACYZIP)");
                    }

                    if (string.IsNullOrEmpty(_password))
                    {
                        return;
                    }
                }
                else
                {
                    Logging.Log("You have not specified a valid encrypted file!", Severity.WARN);
                    return;
                }
            }

            if (_showAllMetadata)
            {
                if (File.Exists(_directory) && FileAES_Utilities.IsFileDecryptable(_directory))
                {
                    string compressionMode = FileAES_Utilities.GetCompressionMode(_directory);

                    MetaData faesMetaData = new MetaData(_directory);

                    if (faesMetaData.IsLegacyVersion())
                    {
                        Logging.Log(
                            $"The metadata (bytes) for '{Path.GetFileName(_directory)}' is (FAESv2):\n{BitConverter.ToString(faesMetaData.GetMetaData())}");
                    }
                    else
                    {
                        Logging.Log(
                            $"The metadata (bytes) for '{Path.GetFileName(_directory)}' is (FAESv3):\n{BitConverter.ToString(faesMetaData.GetMetaData())}");
                    }

                    if (string.IsNullOrEmpty(_password))
                    {
                        return;
                    }
                }
                else
                {
                    Logging.Log("You have not specified a valid encrypted file!", Severity.WARN);
                    return;
                }
            }

            if (_showAllMetadataString)
            {
                if (File.Exists(_directory) && FileAES_Utilities.IsFileDecryptable(_directory))
                {
                    string compressionMode = FileAES_Utilities.GetCompressionMode(_directory);

                    MetaData faesMetaData = new MetaData(_directory);

                    if (faesMetaData.IsLegacyVersion())
                    {
                        Logging.Log(
                            $"The metadata (string) for '{Path.GetFileName(_directory)}' is (FAESv2):\n{Encoding.UTF8.GetString(faesMetaData.GetMetaData())}");
                    }
                    else
                    {
                        Logging.Log(
                            $"The metadata (string) for '{Path.GetFileName(_directory)}' is (FAESv3):\n{Encoding.UTF8.GetString(faesMetaData.GetMetaData())}");
                    }

                    if (string.IsNullOrEmpty(_password))
                    {
                        return;
                    }
                }
                else
                {
                    Logging.Log("You have not specified a valid encrypted file!", Severity.WARN);
                    return;
                }
            }

            if (string.IsNullOrEmpty(_directory))
            {
                while (true)
                {
                    Console.Write("File/Folder: ");
                    _directory = Console.ReadLine();

                    if (File.Exists(_directory) || Directory.Exists(_directory))
                    {
                        break;
                    }
                    Logging.Log("You have not specified a valid file or folder!", Severity.WARN);
                }
            }
            if (string.IsNullOrEmpty(_password))
            {
                while (true)
                {
                    Console.Write("Password: "******"\nConf. Password: "******"Passwords do not match!");
                    }
                    else
                    {
                        Console.Write(Environment.NewLine);
                        _password = password;
                        break;
                    }
                }
            }

            if (!File.Exists(_directory) && !Directory.Exists(_directory))
            {
                Logging.Log("You have not specified a valid file or folder!", Severity.WARN);
            }
            else if (string.IsNullOrEmpty(_password))
            {
                Logging.Log("Please specify a password!", Severity.WARN);
            }
            else
            {
                FAES_File faesFile = new FAES_File(_directory);
                FileAES_Utilities.SetCryptoStreamBuffer(_csBuffer);

                try
                {
                    if (_compressionLevel < 0 || _compressionLevel > 9)
                    {
                        Logging.Log("You have not specified a valid compression level! Please choose a value between 0 and 9.", Severity.WARN);
                        return;
                    }
                    else
                    {
                        if (_verbose)
                        {
                            Logging.Log(
                                $"CryptoStream Buffer Size: {FileAES_Utilities.GetCryptoStreamBuffer()} bytes", Severity.DEBUG);
                        }

                        if (faesFile.IsFileEncryptable())
                        {
                            FileAES_Utilities.LocalEncrypt = _useLocalEncrypt;
                            FileAES_Encrypt encrypt = new FileAES_Encrypt(faesFile, _password, _passwordHint, Optimise.Balanced, null, _deleteOriginalFile, _overwriteDuplicates);

                            if (!string.IsNullOrEmpty(_compressionMethod))
                            {
                                switch (_compressionMethod)
                                {
                                case "ZIP":
                                    encrypt.SetCompressionMode(CompressionMode.ZIP, _compressionLevel);
                                    break;

                                case "TAR":
                                    encrypt.SetCompressionMode(CompressionMode.TAR, _compressionLevel);
                                    break;

                                case "LZMA":
                                    encrypt.SetCompressionMode(CompressionMode.LZMA, _compressionLevel);
                                    break;

                                case "GZIP":
                                    encrypt.SetCompressionMode(CompressionMode.GZIP, _compressionLevel);
                                    break;

                                case "LGYZIP":
                                case "LEGACYZIP":
                                case "LEGACY":
                                    encrypt.SetCompressionMode(CompressionMode.LGYZIP, _compressionLevel);
                                    break;

                                default:
                                    Console.WriteLine("Unknown Compression Method: {0}", _compressionMethod);
                                    return;
                                }
                            }

                            Thread progressThread = new Thread(() =>
                            {
                                while (_showProgress)
                                {
                                    ushort percentComplete = Convert.ToUInt16(encrypt.GetEncryptionPercentComplete());
                                    Logging.Log($"Progress: {percentComplete}%");
                                    Thread.Sleep(_progressSleep);
                                }
                            });

                            Thread eThread = new Thread(() =>
                            {
                                try
                                {
                                    if (encrypt.EncryptFile())
                                    {
                                        if (_showProgress)
                                        {
                                            Logging.Log("Progress: 100%");
                                        }

                                        Logging.Log($"Encryption on {faesFile.getFaesType().ToLower()} succeeded!");
                                    }
                                    else
                                    {
                                        Logging.Log($"Encryption on {faesFile.getFaesType().ToLower()} failed!");
                                    }
                                }
                                catch (Exception e)
                                {
                                    #if NETFRAMEWORK
                                    progressThread.Abort();
                                    #endif
                                    HandleException(e);
                                }
                            });

                            if (_showProgress)
                            {
                                progressThread.Start();
                            }
                            eThread.Start();

                            while (eThread.ThreadState == ThreadState.Running)
                            {
                            }
                            #if NETFRAMEWORK
                            progressThread.Abort();
                            #endif
                        }
                        else
                        {
                            FileAES_Decrypt decrypt = new FileAES_Decrypt(faesFile, _password, _deleteOriginalFile, _overwriteDuplicates);

                            Thread progressThread = new Thread(() =>
                            {
                                while (_showProgress)
                                {
                                    ushort percentComplete = Convert.ToUInt16(decrypt.GetDecryptionPercentComplete());

                                    Logging.Log($"Progress: {percentComplete}%");
                                    Thread.Sleep(_progressSleep);
                                }
                            });

                            Thread dThread = new Thread(() =>
                            {
                                try
                                {
                                    if (decrypt.DecryptFile())
                                    {
                                        if (_showProgress)
                                        {
                                            Logging.Log("Progress: 100%");
                                        }

                                        Logging.Log($"Decryption on {faesFile.getFaesType().ToLower()} succeeded!");
                                    }
                                    else
                                    {
                                        Logging.Log($"Decryption on {faesFile.getFaesType().ToLower()} failed!");
                                        Logging.Log("Ensure that you entered the correct password!");
                                        Logging.Log($"Password Hint: {faesFile.GetPasswordHint()}");
                                    }
                                }
                                catch (Exception e)
                                {
                                    #if NETFRAMEWORK
                                    progressThread.Abort();
                                    #endif
                                    HandleException(e);
                                }
                            });

                            if (_showProgress)
                            {
                                progressThread.Start();
                            }
                            dThread.Start();

                            while (dThread.ThreadState == ThreadState.Running)
                            {
                            }
                            #if NETFRAMEWORK
                            progressThread.Abort();
                            #endif
                        }
                    }
                }
                catch (Exception e)
                {
                    HandleException(e);
                }
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Decrypts the selected file using the given password
        /// </summary>
        /// <param name="inputFile">Encrypted File</param>
        /// <param name="password">Password to decrypt the file</param>
        /// <param name="percentComplete">Percent of completion</param>
        /// <returns>If the decryption was successful</returns>
        internal bool Decrypt(string inputFile, string password, ref decimal percentComplete)
        {
            byte[] passwordBytes = Encoding.UTF8.GetBytes(password);

            FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);

            fsCrypt = DecryptModeHandler(fsCrypt, out byte[] hash, out byte[] salt, out byte[] faesCBCMode, out byte[] faesMetaData, out var cipher);

            const int          keySize   = 256;
            const int          blockSize = 128;
            Rfc2898DeriveBytes key       = new Rfc2898DeriveBytes(passwordBytes, salt, 50000);
            RijndaelManaged    AES       = new RijndaelManaged
            {
                KeySize   = keySize,
                BlockSize = blockSize,
                Key       = key.GetBytes(keySize / 8),
                IV        = key.GetBytes(blockSize / 8),
                Padding   = PaddingMode.PKCS7,
                Mode      = cipher
            };

            try
            {
                CryptoStream cs         = new CryptoStream(fsCrypt, AES.CreateDecryptor(), CryptoStreamMode.Read);
                string       outputName = Path.ChangeExtension(inputFile, FileAES_Utilities.ExtentionUFAES);

                try
                {
                    FileStream fsOut = new FileStream(outputName, FileMode.Create);
                    File.SetAttributes(outputName, FileAttributes.Hidden);

                    byte[] buffer           = new byte[FileAES_Utilities.GetCryptoStreamBuffer()];
                    long   expectedComplete = fsCrypt.Length + hash.Length + salt.Length + faesCBCMode.Length + faesMetaData.Length + AES.KeySize + AES.BlockSize;

                    try
                    {
                        int read;
                        Logging.Log("Beginning writing decrypted data...", Severity.DEBUG);
                        while ((read = cs.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            try
                            {
                                percentComplete = Math.Ceiling((decimal)((Convert.ToDouble(fsOut.Length) / Convert.ToDouble(expectedComplete)) * 100));
                                if (percentComplete > 100)
                                {
                                    percentComplete = 100;
                                }
                            }
                            catch
                            {
                                Logging.Log("Percentage completion calculation failed!", Severity.WARN);
                            }

                            fsOut.Write(buffer, 0, read);
                        }
                        Logging.Log("Finished writing decrypted data.", Severity.DEBUG);
                    }
                    catch
                    {
                        fsOut.Close();
                    }

                    cs.Close();
                    fsOut.Close();
                    fsCrypt.Close();

                    if (Checksums.ConvertHashToString(hash) != Checksums.ConvertHashToString(Checksums.GetSHA1(outputName)))
                    {
                        Logging.Log("Invalid Checksum detected! Assuming password is incorrect.", Severity.DEBUG);
                        FileAES_IntUtilities.SafeDeleteFile(outputName);
                        return(false);
                    }
                    Logging.Log("Valid Checksum detected!", Severity.DEBUG);
                    return(true);
                }
                catch
                {
                    cs.Close();
                    fsCrypt.Close();

                    return(false);
                }
            }
            catch (CryptographicException)
            {
                fsCrypt.Close();
                return(false);
            }
        }
Esempio n. 17
0
        private void Encrypt()
        {
            string password      = passTextbox.Text;
            string passHint      = passHintTextbox.Text;
            int    compressIndex = compressMode.SelectedIndex;
            bool   delAfterEnc   = deleteOriginal.Checked;
            bool   ovDup         = overwriteDuplicate.Checked;

            Logging.Log("FAES_GUI(Encrypt): Started!'", Severity.DEBUG);

            SetNote("Encrypting... Please wait.", 0);

            _inProgress        = true;
            _encryptSuccessful = false;

            _mainEncryptThread = new Thread(() =>
            {
                try
                {
                    FileAES_Utilities.SetCryptoStreamBuffer(Program.programManager.GetCryptoStreamBufferSize());
                    FileAES_Utilities.TempEncrypt = Program.programManager.GetUseOSTemp();
                    FileAES_Encrypt encrypt       = new FileAES_Encrypt(_fileToEncrypt, password, passHint, FAES.Packaging.CompressionUtils.GetAllOptimiseModes()[compressIndex]);
                    encrypt.SetDeleteAfterEncrypt(delAfterEnc);
                    encrypt.SetOverwriteDuplicate(ovDup);
                    encrypt.DebugMode = FileAES_Utilities.GetVerboseLogging();

                    _faesThread = new Thread(() =>
                    {
                        try
                        {
                            _encryptSuccessful = encrypt.EncryptFile();
                        }
                        catch (Exception e)
                        {
                            SetNote(FileAES_Utilities.FAES_ExceptionHandling(e, Program.IsVerbose()).Replace("ERROR:", ""), 3);
                        }
                    });
                    _faesThread.Start();

                    while (_faesThread.ThreadState == ThreadState.Running)
                    {
                        _progress = encrypt.GetPercentComplete();
                    }

                    {
                        _inProgress = false;

                        Invoke(new MethodInvoker(() => Locked(false)));

                        if (_encryptSuccessful)
                        {
                            Logging.Log("FAES_GUI(Encrypt): Finished successfully!'", Severity.DEBUG);
                            SetNote("Encryption Complete", 0);
                            progressBar.CustomText = "Done";
                            progressBar.VisualMode = CustomControls.ProgressBarDisplayMode.TextAndPercentage;
                            if (_closeAfterOp)
                            {
                                Application.Exit();
                            }
                            else
                            {
                                ResetFile();
                            }
                        }
                        else
                        {
                            Logging.Log("FAES_GUI(Encrypt): Finished unsuccessfully!'", Severity.DEBUG);
                            if (!statusInformation.Text.ToLower().Contains("error"))
                            {
                                SetNote("Encryption Failed. Try again later.", 1);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    SetNote(FileAES_Utilities.FAES_ExceptionHandling(e, Program.IsVerbose()).Replace("ERROR:", ""), 3);
                }
            });
            _mainEncryptThread.Start();
        }