/// <summary>
        /// Конструктор формы де/шифрования файла. Предпреждений перезаписи нет!
        /// </summary>
        /// <param name="src_file_path">Исходный файл</param>
        /// <param name="dst_path">Папку, в которую надо сохранять</param>
        /// <param name="dst_file_name">Имя файла, с которым его следует сохранить (работает только при расшифровании)</param>
        /// <param name="time_stamp">Штамп времени в тиках, не шифруется, добавляется в начало имени файла</param>
        /// <param name="IsEncrypt">Шифрация ли</param>
        /// <param name="prefix">Префикс "0." шифруемых файлов</param>
        /// <param name="pwd_file_enc">Ключ-пароль для шифрования файлов</param>
        /// <param name="key_size">Длина ключа шифрования файлов (256 192 128)</param>
        /// <param name="pwd_namefile_enc">Ключ для шифрования имен файлов</param>
        public FormAction(string src_file_path, string dst_path, string dst_file_name, string time_stamp, bool IsEncrypt, string prefix, string pwd_file_enc, UInt16 key_size, string pwd_namefile_enc)
        {
            FileCrypt cr = new FileCrypt();

            InitializeComponent();

            dst_path = ManageSetting.FixDrivePath(dst_path);

            _src_file_path = src_file_path;
            _dst_path      = dst_path;
            _dst_file_name = dst_file_name;
            _IsEncrypt     = IsEncrypt;

            _prefix           = prefix;
            _pwd_file_enc     = pwd_file_enc;
            _key_size         = key_size;
            _pwd_namefile_enc = pwd_namefile_enc;
            if (!string.IsNullOrEmpty(time_stamp))
            {
                _time_stamp = time_stamp + FileTreeExplorer.delimiter;
            }
            else
            {
                _time_stamp = string.Empty;
            }
        }
Exemple #2
0
        public async Task <IActionResult> DeleteEncryptedFilesAsync(long fileCryptId)
        {
            dynamic          ajaxReturn          = new JObject();
            UserBindingModel loggedInUserDetails = new UserBindingModel();

            loggedInUserDetails = this.User.GetLoggedInUserDetails();
            FileCrypt fileCrypt = new FileCrypt();

            fileCrypt.ModifiedBy = loggedInUserDetails.UserId;
            fileCrypt            = await this._fileCryptService.GetEncryptedFileDetailsAsync(fileCryptId);

            bool isFileDeletionSuccess = await this._fileCryptService.DeleteEncryptedFileAsync(fileCrypt);

            if (isFileDeletionSuccess)
            {
                ajaxReturn.Status         = "Success";
                ajaxReturn.GetGoodJobVerb = "Good Work";
                ajaxReturn.Message        = fileCrypt.FileName + " - file delete sucessfully" +
                                            "";
            }
            else
            {
                ajaxReturn.Status  = "Error";
                ajaxReturn.Message = "Error occured while deleting file - " + fileCrypt.FileName +
                                     "";
            }

            return(this.Json(ajaxReturn));
        }
Exemple #3
0
 /// <summary>
 /// Восстановление файла
 /// </summary>
 /// <param name="file">имя src-файла, _recover_dir должна быть установлена</param>
 private void RecoverFile(string file, string _rec_dir)
 {
     try
     {
         string decrypt_name = fileTreeExplorer.GetTrueFileName(Path.GetFileName(file));//надо извлечь имя файла
         if (fileTreeExplorer.IsCryptFile(decrypt_name, _prefix))
         {
             decrypt_name = new FileCrypt().DecryptFName(decrypt_name, _pwd_namefile_enc, _prefix);
             //расшифровываем файл и копируем в _recover_dir
             using (FormAction frm_a = new FormAction(file, _rec_dir, decrypt_name, string.Empty, false, _prefix, _pwd_file_enc, _key_size, _pwd_namefile_enc))
             {
                 frm_a.ShowDialog();
             }
         }
         else
         {
             //оставшиеся файлы копируем в _recover_dir
             File.Copy(file, Path.Combine(_rec_dir, decrypt_name), true);
         }
         ms.write_lview_message("Файл извлечен", Path.Combine(_rec_dir, decrypt_name), Color.GhostWhite, 0, listView_trace);
     }
     catch (Exception ex)
     {
         ms.PrintError(ex, listView_trace);
     }
 }
Exemple #4
0
        public async Task <bool> UploadFileAndEncryptAsync(FileCrypt fileCrypt, Stream stream)
        {
            fileCrypt.FileCryptId = await this._fileCryptRepository.SaveFileDetailsForEncryptionAsync(fileCrypt);

            Assembly asm                   = Assembly.GetExecutingAssembly();
            var      memoryStream          = new MemoryStream();
            var      memoryStreamEncrypted = new MemoryStream();
            string   tempFilePath          = "";

            fileCrypt.EncryptedFileName     = "FileEncrypt_" + fileCrypt.FileCryptId.ToString();
            fileCrypt.EncryptedFileFullPath = fileCrypt.EncryptedFilePath + fileCrypt.EncryptedFileName + fileCrypt.EncryptedFileExtension;
            tempFilePath = fileCrypt.EncryptedFilePath + fileCrypt.EncryptedFileName + ".temp";
            string path = System.IO.Path.GetDirectoryName(asm.Location);
            string privateKeyFileFullPath = path + @"\" + GlobalAppConfigurations.Instance.GetValue("PGPPrivateKeyFileFullPath").ToString();
            string publicKeyFileFullPath  = path + @"\" + GlobalAppConfigurations.Instance.GetValue("PGPPublicKeyFileFullPath").ToString();
            string pgpKeyPassword         = GlobalAppConfigurations.Instance.GetValue("PGPKeyPassword").ToString();

            // Write File from stream to Byte
            await stream.CopyToAsync(memoryStream);

            byte[] fileInByte = memoryStream.ToArray();

            // Save Encrytped File byte to File
            using (var fileStream = new FileStream(tempFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                using (var memoryStreamToFile = new MemoryStream(fileInByte))
                {
                    byte[] bytes = new byte[memoryStreamToFile.Length];
                    await memoryStreamToFile.ReadAsync(bytes, 0, (int)memoryStreamToFile.Length);

                    await fileStream.WriteAsync(bytes, 0, bytes.Length);
                }

            using (ChoPGPEncryptDecrypt pgp = new ChoPGPEncryptDecrypt())
            {
                try
                {
                    await pgp.EncryptFileAsync(tempFilePath,
                                               fileCrypt.EncryptedFileFullPath,
                                               publicKeyFileFullPath,
                                               true, true);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

            if (File.Exists(tempFilePath))
            {
                File.Delete(tempFilePath);
            }

            bool isUpdateSuccess = await this._fileCryptRepository.UpdateFileDetailsAfterEncryptionAsync(fileCrypt);

            return(isUpdateSuccess);
        }
Exemple #5
0
        public async Task <bool> DeleteEncryptedFileAsync(FileCrypt fileCrypt)
        {
            if (File.Exists(fileCrypt.EncryptedFileFullPath))
            {
                File.Delete(fileCrypt.EncryptedFileFullPath);
            }

            bool isDbUpdateSuccess = await this._fileCryptRepository.DeleteEncryptedFileAsync(fileCrypt);

            return(isDbUpdateSuccess);
        }
Exemple #6
0
        public async Task <IActionResult> GetEncryptedFileDownloadHistoryAsync(long fileCryptId)
        {
            List <FileCryptBindingModel> filesCryptBindingModel = new List <FileCryptBindingModel>();
            List <FileCrypt>             filesCrypt             = new List <FileCrypt>();
            FileCrypt fileCrypt = new FileCrypt();

            fileCrypt.FileCryptId = fileCryptId;
            filesCrypt            = await this._fileCryptService.GetEncryptedFileDownloadHistoryAsync(fileCrypt);

            filesCryptBindingModel = this._mapper.Map <List <FileCryptBindingModel> >(filesCrypt);

            return(await Task.Run(() => this.PartialView("_getEncryptedFileDownloadHistory", filesCryptBindingModel)));
        }
 private void button_ok_Click(object sender, EventArgs e)
 {
     if (FileCrypt.CheckKeyFNameLen(textBox_fnamekey.Text))
     {
         SaveFromControls();
         ManageSetting.CreateSettings(o);
         this.DialogResult = DialogResult.OK;
     }
     else
     {
         this.DialogResult = DialogResult.None;
     }
 }
        public static bool LoadSettings(ref Options o)
        {
            bool res = false;

            try
            {
                if (string.IsNullOrEmpty(Cached_Pwd))
                {
                    Cached_Pwd = GetPwdForKeysFile(true);
                }
                if (string.IsNullOrEmpty(Cached_Pwd))
                {
                    Application.Exit();
                }

                XmlSerializer       myXmlSer = new XmlSerializer(typeof(Options));
                PasswordDeriveBytes pdb      = new PasswordDeriveBytes(Cached_Pwd, null); //класс, позволяющий генерировать ключи на базе паролей
                pdb.HashName = "SHA512";                                                  //будем использовать SHA512
                byte[] key = pdb.GetBytes(12);

                byte[] bt = new FileCrypt().decrypt_file_to_byte(Encoding.ASCII.GetString(key), 256, path_to_set_file, new ProgressBar());

                using (MemoryStream ms = new MemoryStream(bt, false))
                {
                    o = (Options)myXmlSer.Deserialize(ms);
                    ms.Close();
                }

                res = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка: " + ex.Message);
                res = false;
            }
            return(res);
            //XmlSerializer myXmlSer = new XmlSerializer(typeof(Options));
            //FileStream mySet = new FileStream(path_to_set_file, FileMode.Open);
            //o = (Options)myXmlSer.Deserialize(mySet);
            //mySet.Close();
        }
Exemple #9
0
        public async Task <(FileCrypt fileDetails, MemoryStream memoryStream)> DecryptAndDownloadFileAsync(long fileCryptId)
        {
            MemoryStream memoryStream        = new MemoryStream();
            MemoryStream decryptMemoryStream = new MemoryStream();
            Assembly     asm  = Assembly.GetExecutingAssembly();
            string       path = System.IO.Path.GetDirectoryName(asm.Location);
            string       privateKeyFileFullPath = path + @"\" + GlobalAppConfigurations.Instance.GetValue("PGPPrivateKeyFileFullPath").ToString();
            string       publicKeyFileFullPath  = path + @"\" + GlobalAppConfigurations.Instance.GetValue("PGPPublicKeyFileFullPath").ToString();
            string       pgpKeyPassword         = GlobalAppConfigurations.Instance.GetValue("PGPKeyPassword").ToString();

            FileCrypt fileCrypt = await this._fileCryptRepository.GetEncryptedFileDetailsAsync(fileCryptId);

            await this._fileCryptRepository.SaveFileDecryptionHistoryAsync(fileCrypt);

            using (var stream = new FileStream(fileCrypt.EncryptedFileFullPath, FileMode.Open))
            {
                await stream.CopyToAsync(memoryStream);
            }

            memoryStream.Position = 0;

            using (ChoPGPEncryptDecrypt pgp = new ChoPGPEncryptDecrypt())
            {
                try
                {
                    pgp.Decrypt(memoryStream,
                                decryptMemoryStream,
                                privateKeyFileFullPath, pgpKeyPassword);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

            decryptMemoryStream.Position = 0;

            return(fileCrypt, decryptMemoryStream);
        }
        private void LoadContactsToTree(string filename)
        {
            try
            {
                treeView_с.Nodes.Clear();

                XmlSerializer       myXmlSer = new XmlSerializer(typeof(contacts));
                PasswordDeriveBytes pdb      = new PasswordDeriveBytes(ManageSetting.Cached_Pwd, null); //класс, позволяющий генерировать ключи на базе паролей
                pdb.HashName = "SHA512";                                                                //будем использовать SHA512
                byte[] key = pdb.GetBytes(12);

                byte[] bt = new FileCrypt().decrypt_file_to_byte(Encoding.ASCII.GetString(key), 256, filename, new ProgressBar());

                using (MemoryStream ms = new MemoryStream(bt, false))
                {
                    ct = (contacts)myXmlSer.Deserialize(ms);
                    ms.Close();
                }

                for (int i = 0; i < ct.Contacts.Length; i++)
                {
                    treeView_с.Nodes.Add(create_node("Контакт", ct.Contacts[i], 0, ct.Contacts[i]));

                    object[] st = ct.PrefContacts[i];

                    for (int j = 0; j < ct.PrefContacts[i].Length; j++)
                    {
                        string[] str = (string[])st[j];
                        treeView_с.Nodes[i].Nodes.Add(create_node(str[0], str[0] + ": " + str[1], int.Parse(str[2]), str[1]));
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка");
            }
        }
Exemple #11
0
        public async Task <IActionResult> UploadFiles(List <IFormFile> filesForUpload)
        {
            string signalRConnectionId = this._httpContextAccessor.HttpContext.Request?.Headers["SignalRConnectionId"];
            int    percentCompleted    = 20;

            dynamic          ajaxReturn          = new JObject();
            UserBindingModel loggedInUserDetails = new UserBindingModel();

            loggedInUserDetails = this.User.GetLoggedInUserDetails();

            if (signalRConnectionId != null)
            {
                percentCompleted = percentCompleted + 10;
                await this._anonymousHubContext.Clients
                .Client(signalRConnectionId)
                .SendAsync("progressBarUpdate", percentCompleted);
            }

            var uploadFilepath = Path.Combine(this._hostingEnvironment.WebRootPath, @"EncryptedFiles\");

            if (signalRConnectionId != null)
            {
                percentCompleted = percentCompleted + 10;

                await this._anonymousHubContext.Clients
                .Client(signalRConnectionId)
                .SendAsync("progressBarUpdate", percentCompleted);
            }

            int count = 1;

            foreach (var fileToEncrypt in filesForUpload)
            {
                int percentOfFiles = (int)Math.Round(((double)count / (double)filesForUpload.Count) * 50);
                int percentCompletedForEncryption = percentCompleted + percentOfFiles;
                count++;

                FileCrypt fileCrypt = new FileCrypt();
                fileCrypt.FileName               = fileToEncrypt.FileName;
                fileCrypt.EncryptedFilePath      = uploadFilepath;
                fileCrypt.EncryptedFileExtension = GlobalAppConfigurations.Instance.GetValue("PGPEncrypedFileExtension").ToString();

                fileCrypt.CreatedBy  = loggedInUserDetails.UserId;
                fileCrypt.ModifiedBy = loggedInUserDetails.UserId;

                await this._fileCryptService.UploadFileAndEncryptAsync(fileCrypt, fileToEncrypt.OpenReadStream());

                if (signalRConnectionId != null)
                {
                    await this._anonymousHubContext.Clients
                    .Client(signalRConnectionId)
                    .SendAsync("progressBarUpdate", percentCompletedForEncryption);
                }
            }

            ajaxReturn.Status         = "Success";
            ajaxReturn.GetGoodJobVerb = "Good Work";
            ajaxReturn.Message        = "File uploaded successfully" +
                                        " ";

            if (signalRConnectionId != null)
            {
                await this._anonymousHubContext.Clients
                .Client(signalRConnectionId)
                .SendAsync("progressBarUpdate", 100);
            }

            return(this.Json(ajaxReturn));
        }
        private void FileTransfer(string src_file_path, string dst_path, bool isEncrypt)
        {
            Application.DoEvents();
            FileCrypt cr = new FileCrypt();
            string    dst_file_path;
            string    _enc_file_name = string.Empty;
            string    _dec_file_name = string.Empty;

            textBox_src_file.Text = src_file_path;

            try
            {
                if (isEncrypt)
                {
                    this.Text = "Шифрование";
                    listBox_log.Items.Add("Шифрование начато...");
                    //EncryptFName - вызов из флат-эксплорера по хорошему
                    //Здесь результативное имя файла всегда постоянное
                    _enc_file_name        = cr.EncryptFName(Path.GetFileName(src_file_path), _pwd_namefile_enc, _prefix);
                    dst_file_path         = Path.Combine(dst_path, _time_stamp + _enc_file_name);
                    textBox_dst_file.Text = dst_file_path;

                    if (dst_path.Length < 3)
                    {
                        new CriticalErrors().PrintError("S2", "В эту папку сохранять нельзя");
                    }
                    else
                    {
                        cr.crypt_file(true, _pwd_file_enc, _key_size, src_file_path, dst_file_path, progressBar_crypt);
                    }
                }
                else
                {
                    this.Text = "Дешифрование";
                    listBox_log.Items.Add("Дешифрование начато...");
                    _dec_file_name = _dst_file_name;
                    if (string.IsNullOrEmpty(_dst_file_name))
                    {
                        _dec_file_name = cr.DecryptFName(Path.GetFileName(src_file_path), _pwd_namefile_enc, _prefix);
                    }
                    dst_file_path         = Path.Combine(dst_path, _dec_file_name);
                    textBox_dst_file.Text = dst_file_path;

                    if (dst_path.Length < 3)
                    {
                        new CriticalErrors().PrintError("S2", "В эту папку сохранять нельзя");
                    }
                    else
                    {
                        cr.crypt_file(false, _pwd_file_enc, _key_size, src_file_path, dst_file_path, progressBar_crypt);
                    }
                }
                listBox_log.Items.Add("OK");
                DialogResult = DialogResult.OK;
            }
            catch (Exception ex)
            {
                new CriticalErrors().PrintError("E1", ex.Message + " | " + ex.TargetSite);
                listBox_log.Items.Add(ex.Message);
                listBox_log.Items.Add("ERROR...");
            }
            finally
            {
                button_ok.Enabled = true;
            }
        }
        public void PrintFiles(string folder, string _prefix, string _pwd_namefile_enc)
        {
            try
            {
                tV.Nodes.Clear();
                FileInfo[] afi = new DirectoryInfo(folder).GetFiles("*", SearchOption.TopDirectoryOnly);

                foreach (FileInfo fi in afi)
                {
                    DateTime dt;
                    string   date_stamp   = string.Empty;
                    string   TrueFileName = fi.Name;
                    string   FileName     = fi.Name;

                    if (IsTimeStampFile(FileName))                //Если есть TimeStamp
                    {
                        TrueFileName = GetTrueFileName(FileName); //исходное имя файла
                        dt           = new DateTime(Convert.ToInt64(FileName.Remove(_len_ticks)));
                    }
                    else
                    {
                        dt = fi.LastWriteTime;
                    }
                    date_stamp = " :: " + dt.ToShortDateString() + " " + dt.ToShortTimeString();

                    //признак зашифрованнго файла

                    if (IsCryptFile(FileName, _prefix))
                    {
                        TrueFileName  = new FileCrypt().DecryptFName(TrueFileName, _pwd_namefile_enc, _prefix);//без разбора пытаемся его расшифровать
                        TrueFileName += FileCrypt.crypted_mess;
                    }

                    string node_key = TrueFileName.Replace(FileCrypt.crypted_mess, string.Empty);

                    TreeNode tn = new TreeNode();
                    tn.Name        = node_key;
                    tn.Text        = TrueFileName + date_stamp;
                    tn.Tag         = fi.FullName;
                    tn.ToolTipText = FileSize.PrintFileSize(fi.Length);

                    if (tV.Nodes.ContainsKey(node_key))//или в подноду, если имя совпало
                    {
                        TreeNode tn_child = new TreeNode();
                        tn_child.Name        = node_key;
                        tn_child.Text        = TrueFileName + date_stamp;
                        tn_child.Tag         = fi.FullName;
                        tn_child.ToolTipText = FileSize.PrintFileSize(fi.Length);

                        if (list_files.ContainsKey(fi.FullName))//выставляем чекбоксы, если есть в хеш-таблице
                        {
                            tn_child.Checked = true;
                        }
                        tV.Nodes[node_key].Nodes.Add(tn_child);
                        Application.DoEvents();
                    }
                    else
                    {
                        if (list_files.ContainsKey(fi.FullName))//выставляем чекбоксы, если есть в хеш-таблице
                        {
                            tn.Checked = true;
                        }
                        tV.Nodes.Add(tn);//или в основную ноду
                        Application.DoEvents();
                    }
                }
            }
            catch (Exception ex)
            {
                if (Error != null)
                {
                    Error.Invoke(ex.Message + " | " + ex.TargetSite);
                }
            }
        }
Exemple #14
0
 public async Task <List <FileCrypt> > GetEncryptedFileDownloadHistoryAsync(FileCrypt fileCrypt)
 {
     return(await this._fileCryptRepository.GetEncryptedFileDownloadHistoryAsync(fileCrypt));
 }