예제 #1
0
        public ActionResult Create(ExaminationCRUViewModel viewModel)
        {
            //var file = new file
            //{
            //    id = viewmodel.examfile.id,
            //    contenttype = viewmodel.examfile.fileupload.contenttype
            //};
            ExaminationTranslator examTranslator = new ExaminationTranslator();
            List <File>           files          = new List <File>();
            Examination           exam           = examTranslator.ToExaminationDataModel(viewModel, files);

            viewModel.ExamDoctorID = new SelectList(db.Doctors, "ID", "FullName", exam.DoctorID);
            viewModel.PatientID    = new SelectList(db.Patients, "ID", "FullName", exam.PatientID);
            if (ModelState.IsValid)
            {
                FileManipulation fileUploader = new FileManipulation();

                fileUploader.FileUpload(files, viewModel.File.MultipleFileUpload);
                foreach (File file in files)
                {
                    db.Files.Add(file);
                }
                exam.Files = files;

                exam.DoctorID  = viewModel.SelectedDoctorID;
                exam.PatientID = viewModel.SelectedPatientID;

                db.Examinations.Add(exam);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(viewModel));
        }
예제 #2
0
 private void saveProgramFile(StroopProgram newProgram)
 {
     if (FileManipulation.StroopProgramExists(prgNameTextBox.Text))
     {
         DialogResult dialogResult = MessageBox.Show(LocRM.GetString("programExists", currentCulture), "", MessageBoxButtons.OKCancel);
         if (dialogResult != DialogResult.Cancel)
         {
             if (newProgram.saveProgramFile())
             {
                 MessageBox.Show(LocRM.GetString("programSave", currentCulture));
             }
             this.Parent.Controls.Remove(this);
         }
         else
         {
             MessageBox.Show(LocRM.GetString("programNotSave", currentCulture));
         }
     }
     else
     {
         if (newProgram.saveProgramFile())
         {
             MessageBox.Show(LocRM.GetString("programSave", currentCulture));
         }
         this.Parent.Controls.Remove(this);
     }
 }
예제 #3
0
        private void openButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Filter = "ZIP|*.zip";

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                originDataGridView.Rows.Clear();
                importDataGridView.Rows.Clear();
                FileManipulation.CreatImportFolder();
                FileManipulation.ExtractImportFile(openFileDialog.FileName);
                fileTextBox.Text = openFileDialog.FileName;

                addFilesToOriginGrid(FileManipulation._importPath + "/StroopProgram/", LocRM.GetString("stroopTest", currentCulture), stroopPath);
                addFilesToOriginGrid(FileManipulation._importPath + "/ReactionProgram/", LocRM.GetString("reactionTest", currentCulture), reactionPath);
                addFilesToOriginGrid(FileManipulation._importPath + "/MatchingProgram/", LocRM.GetString("matchingTest", currentCulture), matchingPath);
                addFilesToOriginGrid(FileManipulation._importPath + "/ExperimentProgram/", LocRM.GetString("experiment", currentCulture), experimentPath);
                addFilesToOriginGrid(FileManipulation._importPath + "/Lists/", LocRM.GetString("lists", currentCulture), listPath);
            }
            else
            {
                /* do nothing */
            }
        }
예제 #4
0
        public ActionResult Edit(HttpPostedFileBase uploadImg, Employee updatedEmployee)
        {
            if (!ModelState.IsValid)
            {
                return(View(updatedEmployee));
            }

            string imageName = FileManipulation.SavePhoto(uploadImg, Server.MapPath(uploadedImagesPath));
            string oldEmpImg = FileManipulation.GetFileName(updatedEmployee.img);

            if (!string.IsNullOrEmpty(imageName))
            {
                FileManipulation.DeletePhoto(Server.MapPath(uploadedImagesPath), oldEmpImg);
                updatedEmployee.img = imageName;
            }
            else
            {
                if (oldEmpImg == placeholderImageFileName)
                {
                    updatedEmployee.img = null;
                }
                else
                {
                    updatedEmployee.img = oldEmpImg;
                }
            }

            _uow.Employees.Update(updatedEmployee);
            _uow.SaveChanges();

            return(RedirectToAction("Index"));
        }
예제 #5
0
        /// <summary>
        /// Import a <see cref="EncryptionKeyPair"/> from a PEM file.
        /// </summary>
        /// <param name="path">Where the pem file is located.</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">Directory not specified.</exception>
        /// <exception cref="ArgumentException">Directory not found.</exception>
        /// <exception cref="InvalidCastException">Wasn't possible to import key.</exception>
        public static EncryptionKeyPair ImportPEMFile(string path)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentNullException(
                          paramName: nameof(path),
                          message: "Directory not specified.");
            }

            if (!File.Exists(path))
            {
                throw new ArgumentException(
                          paramName: nameof(path),
                          message: "File not found.");
            }

            using (var rsa = new RSACryptoServiceProvider())
            {
                try
                {
                    FileManipulation.OpenFile(path, out byte[] content);
                    return(rsa.ImportRSAKeyPEM(content.AsEncodedString()));
                }
                finally
                {
                    rsa.PersistKeyInCsp = false;
                }
            }
        }
예제 #6
0
        private void exportAllAudiosButton_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            // save file on .WAV format
            saveFileDialog1.Filter           = "Pasta Compactada (.zip)|*.zip";
            saveFileDialog1.RestoreDirectory = true;
            saveFileDialog1.FileName         = resultComboBox.Text + "_audios";

            // only saves if there is one selected result to save
            if (audioPathDataGridView.Rows.Count != 0)
            {
                if (saveFileDialog1.ShowDialog() == DialogResult.OK) // abre caixa para salvar
                {
                    string directory = Path.GetDirectoryName(saveFileDialog1.FileName) + "\\" + Path.GetFileNameWithoutExtension(saveFileDialog1.FileName);
                    FileManipulation.CreateFolder(directory);
                    for (int i = 0; i < audioPathDataGridView.Rows.Count; i++)
                    {
                        string audioPath = audioPathDataGridView.Rows[i].Cells[1].Value.ToString();
                        FileManipulation.CopyFile(audioPath, directory + "\\" + Path.GetFileName(audioPath), true);
                    }
                    FileManipulation.CreateZip(directory, saveFileDialog1.FileName);
                    FileManipulation.DeleteFolder(directory);
                }
            }
            else
            {
                MessageBox.Show(LocRM.GetString("selectDataFile", currentCulture));
            }
        }
예제 #7
0
        public ActionResult EmpDetail(int?id)
        {
            if (!id.HasValue)
            {
                return(null);
            }

            Employee employee = _uow.Employees.GetById(id.Value);

            if (employee == null)
            {
                return(null);
            }

            if (string.IsNullOrEmpty(employee.img))
            {
                employee.img = FileManipulation.GetFileFullPath(serverPath, placeholderImageFileName);
            }
            else
            {
                employee.img = FileManipulation.GetFileFullPath(serverPath, employee.img);
            }

            return(PartialView("_EmployeeDetail", employee));
        }
예제 #8
0
        public void Main_Decrypting_SingleFile_Verbosity_OK()
        {
            Setup.Initialize(out var testFolders);
            Setup.SetEncryptedFiles(testFolders);

            string originalFilePath = Directory.GetFiles(testFolders["original"])[0];
            string outputFilePath   = Path.Combine(
                path1: testFolders["decrypted"],
                path2: Path.GetFileNameWithoutExtension(originalFilePath) + ".decrypted.txt");
            string targetFilePath = Path.Combine(
                path1: testFolders["encrypted"],
                path2: Path.GetFileNameWithoutExtension(originalFilePath) + ".encrypted.txt");

            string[] args =
            {
                "-d",                                        "--verbose",
                $@"--key={Setup.AbsolutePath}\priv.key.pem",
                $"--output={testFolders["decrypted"]}",
                $"--target={targetFilePath}",
            };

            Program.Main(args);

            Assert.True(File.Exists(outputFilePath));

            FileManipulation.OpenFile(outputFilePath, out var outputFile);
            Assert.NotNull(outputFile);

            FileManipulation.OpenFile(originalFilePath, out var originalFile);
            Assert.NotNull(originalFile);

            Assert.Equal(outputFile.Length, originalFile.Length);
            Assert.Equal(outputFile, originalFile);
        }
예제 #9
0
        public ActionResult Edit(int?id, ExaminationCRUViewModel viewModel)
        {
            Examination examToUpdate = db.Examinations
                                       .Include(e => e.Doctor)
                                       .Include(e => e.Patient)
                                       .Include(e => e.Files)
                                       .SingleOrDefault(e => e.ID == id);
            FileManipulation editFile = new FileManipulation();
            List <File>      files    = new List <File>();

            if (ModelState.IsValid)
            {
                //if (viewModel.File.FileUpload != null)
                //{
                editFile.FileUpload(files, viewModel.File.MultipleFileUpload);
                foreach (File file in files)
                {
                    db.Files.Add(file);
                }
                examToUpdate.Files = files;
                //}
                //examToUpdate = examTranslator.ToExaminationDataModel(viewModel, files);
                examToUpdate.DateOfVisit  = viewModel.ExamDate;
                examToUpdate.DiagnoseCode = viewModel.Diagnose;
                examToUpdate.LabResults   = viewModel.LabResult;
                examToUpdate.ExamResults  = viewModel.ExamResult;
                examToUpdate.DoctorID     = viewModel.SelectedDoctorID;
                examToUpdate.PatientID    = viewModel.SelectedPatientID;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            viewModel.ExamDoctorID = new SelectList(db.Doctors, "ID", "FullName", examToUpdate.DoctorID);
            viewModel.PatientID    = new SelectList(db.Patients, "ID", "FullName", examToUpdate.PatientID);
            return(View(viewModel));
        }
        public void Main_VerifySignature_NotValidSignature_OK()
        {
            string hashalg = "SHA256";

            Setup.Initialize(out var testFolders);
            Setup.SetSignatureFile(testFolders, hashalg);

            string fileName          = Path.GetFileNameWithoutExtension(Directory.GetFiles(testFolders["encrypted"], "*encrypt*")[0].Replace(".encrypted", ""));
            string originalFilePath  = Directory.GetFiles(testFolders["original"]).Last();
            string signatureFilePath = Directory.GetFiles(testFolders["encrypted"], $"*{fileName}.SHA256*")[0];

            string[] args =
            {
                "-v",                                       $"--hashalg={hashalg}", "--verbose",
                $@"--key={Setup.AbsolutePath}\pub.key.pem",
                $"--target={originalFilePath}",
                $"--signaturefile={signatureFilePath}"
            };

            Program.Main(args);

            FileManipulation.OpenFile(originalFilePath, out var originalFile);
            FileManipulation.OpenFile(signatureFilePath, out var signatureFile);

            Assert.True(!Setup.PublicKey.VerifySignedData(originalFile, signatureFile, hashalg));
        }
예제 #11
0
        /**
         * Constructor method, creates directories for program, in case they dont exist
         * */
        public FormMain()
        {
            InitializeComponent();
            FileManipulation.Instance(this);
            initializeParticipants();

            _contentPanel = contentPanel;
        }
예제 #12
0
        private void readParticipantFile(string fileName)
        {
            if (File.Exists(GetParticipantPath(fileName)))
            {
                StreamReader  tr;
                string        line;
                string[]      linesInstruction;
                List <string> config = new List <string>();

                tr     = new StreamReader(GetParticipantPath(fileName), Encoding.Default, true);
                line   = tr.ReadLine();
                line   = FileManipulation.EncodeLatinText(line);
                config = line.Split().ToList();

                this.registrationID           = int.Parse(config[0]);
                this.name                     = config[1];
                this.age                      = int.Parse(config[2]);
                this.sex                      = int.Parse(config[3]);
                this.livingLocation           = config[4];
                this.DegreeOfSchooling        = int.Parse(config[5]);
                this.birthDate                = DateTime.Parse(config[6]);
                this.lastPeriodDate           = DateTime.Parse(config[7]);
                this.reasonForNotMenstruating = int.Parse(config[8]);
                this.wearGlasses              = bool.Parse(config[9]);
                this.usesMedication           = bool.Parse(config[10]);
                this.goodLastNightOfSleep     = bool.Parse(config[11]);
                this.consumedAlcohol          = bool.Parse(config[12]);
                this.usedRelaxant             = bool.Parse(config[13]);
                this.consumedDrugs            = bool.Parse(config[14]);
                this.consumedEnergizers       = bool.Parse(config[15]);

                this.glassesEspecification    = FileManipulation.EncodeLatinText(tr.ReadLine());
                this.medicationEspecification = FileManipulation.EncodeLatinText(tr.ReadLine());
                this.relaxantEspecification   = FileManipulation.EncodeLatinText(tr.ReadLine());
                this.sleepEspecification      = FileManipulation.EncodeLatinText(tr.ReadLine());
                this.alcoholEspecification    = FileManipulation.EncodeLatinText(tr.ReadLine());
                this.drugsEspecification      = FileManipulation.EncodeLatinText(tr.ReadLine());
                this.energizersEspecification = FileManipulation.EncodeLatinText(tr.ReadLine());
                tr.Close();
                linesInstruction = File.ReadAllLines(GetParticipantPath(fileName));
                if (linesInstruction.Length > 8) // read instructions if any
                {
                    for (int i = 8; i < linesInstruction.Length; i++)
                    {
                        this.observations.Add(linesInstruction[i]);
                    }
                }
                else
                {
                    this.observations = null;
                }
            }
            else
            {
                throw new FileNotFoundException();
            }
        }
예제 #13
0
        public ActionResult Edit(int?id, DoctorEditViewModel viewModel, HttpPostedFileBase upload)
        {
            Doctor doctorToUpdate = db.Doctors
                                    .Include(d => d.Image)
                                    .SingleOrDefault(d => d.ID == id);

            viewModel.Image.ID = doctorToUpdate.ImageID;
            var validImageTypes = new string[]
            {
                "image/gif",
                "image/jpeg",
                "image/png"
            };

            FileManipulation editImage = new FileManipulation();

            if (ModelState.IsValid)
            {
                if (viewModel.Image.ImgUpload != null && viewModel.Image.ImgUpload.ContentLength > 0)
                {
                    if (!validImageTypes.Contains(viewModel.Image.ImgUpload.ContentType))
                    {
                        ModelState.AddModelError("ImgUpload", "Please, choose either GIF, JPG, or PNG type of files.");
                    }
                    if (viewModel.Image.ID == 1)
                    {
                        File image = new File
                        {
                            ContentType = viewModel.Image.ImgUpload.ContentType
                        };
                        editImage.FileUpload(image, viewModel.Image.ImgUpload);
                        //call for upload with file-system:
                        //EditImageUpload(viewModel.Image.ID, doctorToUpdate, image, viewModel);
                        db.Files.Add(image);
                        doctorToUpdate.Image = image;
                    }
                    else
                    {
                        File image = db.Files.Single(i => i.ID == doctorToUpdate.ImageID);

                        editImage.FileUpload(image, viewModel.Image.ImgUpload);
                    }
                }
                doctorToUpdate.FirstName   = viewModel.Doctor.FirstName;
                doctorToUpdate.LastName    = viewModel.Doctor.LastName;
                doctorToUpdate.Address     = viewModel.Doctor.Address;
                doctorToUpdate.PhoneNumber = viewModel.Doctor.PhoneNumber;
                doctorToUpdate.Email       = viewModel.Doctor.Email;
                doctorToUpdate.Position    = viewModel.Doctor.Position;

                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(viewModel));
        }
예제 #14
0
        public void Draw()
        {
            List <NationalTeam> nationalTeams = FileManipulation.ImportData();

            GetNationalTeams(nationalTeams);
            setPots();

            Group[] g = setGroups();

            FileManipulation.ExportData(g);
        }
예제 #15
0
        // exporting items to directories accordingly to type and zipping them together
        private void exportButton_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.InitialDirectory = "C:\\";
            saveFileDialog.Filter           = "Zip Files | *.zip";
            saveFileDialog.ShowDialog();
            if (saveFileDialog.FileName != "" && !File.Exists(saveFileDialog.FileName))
            {
                FileManipulation.CreateExportationFolders(saveFileDialog.FileName);

                // exporting each row according to type: list, reaction program, stroop program or experiment program
                foreach (DataGridViewRow row in exportDataGridView.Rows)
                {
                    if (row.Cells[1].Value.ToString() == LocRM.GetString("lists", currentCulture))
                    {
                        if ((row.Cells[0].Value.ToString().Split('_')[1] == "color") || (row.Cells[0].Value.ToString().Split('_')[1] == "words"))
                        {
                            exportFile(row.Cells[2].Value.ToString(), Path.GetDirectoryName(saveFileDialog.FileName) + "/ExportingFiles/Lists/" + row.Cells[0].Value.ToString() + ".lst");
                        }
                        else
                        {
                            exportListContent(row.Cells[0].Value.ToString(), Path.GetDirectoryName(saveFileDialog.FileName) + "/ExportingFiles/Lists");
                        }
                    }
                    else if (row.Cells[1].Value.ToString() == LocRM.GetString("reactionTest", currentCulture))
                    {
                        exportFile(row.Cells[2].Value.ToString(), Path.GetDirectoryName(saveFileDialog.FileName) + "/ExportingFiles/" + "ReactionProgram/" + row.Cells[0].Value.ToString() + ".prg");
                    }
                    else if (row.Cells[1].Value.ToString() == LocRM.GetString("stroopTest", currentCulture))
                    {
                        exportFile(row.Cells[2].Value.ToString(), Path.GetDirectoryName(saveFileDialog.FileName) + "/ExportingFiles/" + "StroopProgram/" + row.Cells[0].Value.ToString() + ".prg");
                    }
                    else if (row.Cells[1].Value.ToString() == LocRM.GetString("matchingTest", currentCulture))
                    {
                        exportFile(row.Cells[2].Value.ToString(), Path.GetDirectoryName(saveFileDialog.FileName) + "/ExportingFiles/" + "MatchingProgram/" + row.Cells[0].Value.ToString() + ".prg");
                    }
                    else if (row.Cells[1].Value.ToString() == LocRM.GetString("experiment", currentCulture))
                    {
                        exportFile(row.Cells[2].Value.ToString(), Path.GetDirectoryName(saveFileDialog.FileName) + "/ExportingFiles/" + "ExperimentProgram/" + row.Cells[0].Value.ToString() + ".prg");
                    }
                }

                ZipFile.CreateFromDirectory(Path.GetDirectoryName(saveFileDialog.FileName) + "/ExportingFiles/", @saveFileDialog.FileName);
                Directory.Delete(Path.GetDirectoryName(saveFileDialog.FileName) + "/ExportingFiles/", true);
                MessageBox.Show(LocRM.GetString("exportSuccess", currentCulture));
                Parent.Controls.Remove(this);
            }
            else
            {
                MessageBox.Show(LocRM.GetString("exportDirectory", currentCulture));
            }
        }
예제 #16
0
        public ContentResult AddAjax(HttpPostedFileBase uploadImg, Employee employee)
        {
            if (!ModelState.IsValid)
            {
                return(Content($"<p>Failed to add the following employee: {employee.fName} {employee.lName}</p>"));
            }

            employee.img = FileManipulation.SavePhoto(uploadImg, Server.MapPath(uploadedImagesPath));

            _uow.Employees.Add(employee);
            _uow.SaveChanges();
            return(Content($"<p>Employee {employee.fName} {employee.lName} have been added successfully</p>"));
        }
예제 #17
0
        public ActionResult Add(HttpPostedFileBase uploadImg, Employee employee)
        {
            if (!ModelState.IsValid)
            {
                return(View(employee));
            }

            employee.img = FileManipulation.SavePhoto(uploadImg, Server.MapPath(uploadedImagesPath));

            _uow.Employees.Add(employee);
            _uow.SaveChanges();
            return(RedirectToAction("Index"));
        }
예제 #18
0
        private void btnCopyFiles_Click(object sender, EventArgs e)
        {
            try
            {
                ValidateDirectories();

                FileManipulation.CopyDirectory(txtSource.Text, txtTarget.Text, OnProgressListener);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
예제 #19
0
 public Journal NextJournal()
 {
     try
     {
         var     jornals = FileManipulation.ReadExcelFile();
         Journal journal = jornals[index];
         index++;
         return(journal);
     }
     catch (Exception ex)
     {
         throw;
     }
 }
예제 #20
0
        public ActionResult Create(DoctorCreateViewModel viewModel)
        {
            var validImageTypes = new string[]
            {
                "image/gif",
                "image/jpeg",
                "image/png"
            };

            if (ModelState.IsValid)
            {
                var image = new File
                {
                    ID          = viewModel.Image.ID,
                    ContentType = viewModel.Image.ImgUpload.ContentType
                };
                DoctorTranslator doctorDataTranslator = new DoctorTranslator();
                Doctor           doctor            = doctorDataTranslator.ToDoctorDataModel(viewModel, image);
                FileManipulation imageUploadHelper = new FileManipulation();

                if (viewModel.Image.ImgUpload != null && viewModel.Image.ImgUpload.ContentLength > 0)
                {
                    if (!validImageTypes.Contains(viewModel.Image.ImgUpload.ContentType))
                    {
                        ModelState.AddModelError("ImgUpload", "Please, choose either GIF, JPG, or PNG type of files.");
                    }
                    //upload with file-system, make sure that folder Uploads in DoctorsOffice exist
                    //var imgFileName = Guid.NewGuid().ToString() + GetExtension(viewModel.Image.ImgUpload.ContentType);
                    //var uploadDir = "~/Uploads";
                    //var imagePath = System.IO.Path.Combine(Server.MapPath(uploadDir), imgFileName);
                    //var imageUrl = System.IO.Path.Combine(uploadDir, imgFileName);
                    //viewModel.Image.ImgUpload.SaveAs(imagePath);

                    imageUploadHelper.FileUpload(image, viewModel.Image.ImgUpload);
                    //imageUploadHelper.ResizeImage(viewModel.Image.ImgUpload);-don't work yet!!!
                    //db.Files.Add(image);
                }
                else
                {
                    imageUploadHelper.DefaultImage(doctor);
                }

                db.Doctors.Add(doctor);
                db.SaveChanges();

                return(RedirectToAction("Index"));
            }

            return(View(viewModel));
        }
예제 #21
0
        public static void SetSignatureFile(Dictionary <string, string> testFolders, string hashalg = "SHA256")
        {
            SetEncryptedFiles(testFolders);

            var filePath = Directory.GetFiles(testFolders["original"])[0];
            var fileName = Path.GetFileNameWithoutExtension(filePath);
            var fileExt  = Path.GetExtension(filePath);

            FileManipulation.OpenFile(filePath, out var originalFile);

            string output        = Path.Combine(testFolders["encrypted"], $"{fileName}.{hashalg}{fileExt}");
            var    signatureData = PrivateKey.SignData(originalFile, hashalg);

            File.WriteAllBytes(output, signatureData);
        }
예제 #22
0
        /// <summary>
        /// Export this <see cref="EncryptionKeyPair"/> into a PEM file.
        /// </summary>
        /// <param name="path">Only path name. DO NOT include filename.</param>
        /// <param name="filename">
        /// Filename to export, if not specified it sets to pub.key/priv.key adequately.
        /// DO NOT include extension.
        /// </param>
        /// <param name="includePrivate">On exporting to file include private key content, otherwise false</param>
        /// <exception cref="ArgumentNullException">Directory not specified.</exception>
        /// <exception cref="ArgumentException">Directory not found.</exception>
        /// <exception cref="InvalidOperationException">Error when exporting key.</exception>
        public void ExportAsPEMFile(string path, string filename = "key", bool includePrivate = false)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentNullException(
                          paramName: nameof(path),
                          message: "Directory not specified.");
            }

            if (!Directory.Exists(path))
            {
                throw new ArgumentException(
                          paramName: nameof(path),
                          message: "Directory not found.");
            }

            // trying to export private key from a public key
            if (PublicOnly && includePrivate)
            {
                throw new InvalidOperationException(
                          message: "Impossible to export private content from a public key.");
            }

            using (var rsa = new RSACryptoServiceProvider(this.KeySize))
            {
                try
                {
                    rsa.ImportParameters(this.RSAParameters);
                    if (includePrivate)
                    {
                        filename = "priv." + filename + ".pem";
                        string fileContent = rsa.ExportRSAPrivateKeyAsPEM();
                        FileManipulation.SaveFile(fileContent.ToByteArray(), path, filename, attributes: FileAttributes.ReadOnly);
                    }
                    else
                    {
                        filename = "pub." + filename + ".pem";
                        string fileContent = rsa.ExportRSAPublicKeyAsPEM();
                        FileManipulation.SaveFile(fileContent.ToByteArray(), path, filename, attributes: FileAttributes.ReadOnly);
                    }
                }
                finally
                {
                    rsa.PersistKeyInCsp = false;
                }
            }
        }
예제 #23
0
        private void loadingAudioFilesToDataGrid()
        {
            string[] audioFiles = FileManipulation.GetAllFilesInFolder(path, "WAV");
            // Fills data grid view with .wav files from data directory
            if (audioFiles.Length != 0)
            {
                audioPathDataGridView.Rows.Clear();
                audioPathDataGridView.Refresh();
                currenFolderLabel.Text = path;

                DGVManipulation.ReadStringListIntoDGV(audioFiles, audioPathDataGridView);
                numberFiles.Text = audioPathDataGridView.RowCount.ToString();
            }
            else
            {
                /*path doesnt exist*/
            }
        }
예제 #24
0
        public ActionResult Detail(int?id)
        {
            if (id == null)
            {
                return(RedirectToAction("Index"));
            }

            Employee employee = _uow.Employees.GetById(id.Value);

            if (string.IsNullOrEmpty(employee.img))
            {
                employee.img = FileManipulation.GetFileFullPath(serverPath, placeholderImageFileName);
            }
            else
            {
                employee.img = FileManipulation.GetFileFullPath(serverPath, employee.img);
            }

            return(View(employee));
        }
예제 #25
0
        public static void SetEncryptedFiles(Dictionary <string, string> testFolders, bool multiple = false)
        {
            int files = Directory.GetFiles(testFolders["original"]).Length;

            int i = 0;

            do
            {
                string filePath = Directory.GetFiles(testFolders["original"])[i];

                FileManipulation.OpenFile(filePath, out var originalFile);

                string encryptedFileName = Path.GetFileNameWithoutExtension(filePath) + ".encrypted.txt";
                string encryptedPathFile = Path.Combine(testFolders["encrypted"], encryptedFileName);

                byte[] encryptedFile = PrivateKey.EncryptRijndael(originalFile);
                File.WriteAllBytes(encryptedPathFile, encryptedFile);
                i++;
            } while (i < (multiple ? files : 1));
        }
예제 #26
0
        private void exportAudioButton_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            // save file on .WAV format
            saveFileDialog1.Filter           = "WAVEform (.wav)|*.wav";
            saveFileDialog1.RestoreDirectory = true;
            // only saves if there is one selected result to save
            if (audioPathDataGridView.CurrentRow != null)
            {
                saveFileDialog1.FileName = audioPathDataGridView.CurrentRow.Cells[0].Value.ToString();
                if (saveFileDialog1.ShowDialog() == DialogResult.OK) // abre caixa para salvar
                {
                    FileManipulation.CopyFile(audioPathDataGridView.CurrentRow.Cells[1].Value.ToString(), saveFileDialog1.FileName, true);
                }
            }
            else
            {
                MessageBox.Show(LocRM.GetString("selectAudioFile", currentCulture));
            }
        }
예제 #27
0
        public static void SetMergedFile(Dictionary <string, string> testFolders, string hashalg)
        {
            SetSignatureFile(testFolders, hashalg);

            string output            = testFolders["encrypted"];
            string originalFilePath  = Directory.GetFiles(testFolders["original"])[0];
            string fileName          = Path.GetFileNameWithoutExtension(originalFilePath);
            string signatureFilePath = Directory.GetFiles(testFolders["encrypted"], $"*{fileName}.SHA256*")[0];

            FileManipulation.OpenFile(originalFilePath, out var data);
            FileManipulation.OpenFile(signatureFilePath, out var signature);

            byte[] mergedFile = new byte[signature.Length + data.Length];
            using (var ms = new MemoryStream(mergedFile))
            {
                ms.Write(signature, 0, signature.Length);
                ms.Write(data, 0, data.Length);
            }

            File.WriteAllBytes($"{output}\\{fileName}.merged.txt", mergedFile);
        }
예제 #28
0
        /// <summary>
        /// Export an <see cref="EncryptionKeyPair"/> as an encrypted key using a password./>
        /// </summary>
        /// <param name="password">password to encrypt key.</param>
        /// <param name="path">output path</param>
        /// <param name="filename">output file name</param>
        /// <exception cref="ArgumentNullException">Password or path are missing.</exception>
        /// <exception cref="ArgumentException">File not found.</exception>
        /// <exception cref="InvalidOperationException">Impossible to export as encrypted key when public only.</exception>
        /// <exception cref="CryptographicException">Password is incorrect.</exception>
        public void ExportAsPKCS8(string password, string path, string filename = "key")
        {
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException(
                          paramName: nameof(password),
                          message: "In order to export as an encrypted key a password is needed.");
            }
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentNullException(
                          paramName: nameof(path),
                          message: "Directory not specified.");
            }

            if (this.PublicOnly)
            {
                throw new InvalidOperationException(
                          message: "Must be a private key to export as an encrypted key.");
            }

            filename = $"enc.{filename}.pem";

            using (var rsa = new RSACryptoServiceProvider(this.KeySize))
            {
                try
                {
                    rsa.ImportParameters(this.RSAParameters);
                    var    hashalg     = new HashAlgorithmName("SHA1");
                    var    pbe         = new PbeParameters(PbeEncryptionAlgorithm.Aes256Cbc, hashalg, 64);
                    string fileContent = rsa.ExportEncryptedPkcs8PrivateKeyAsPEM(password, pbe);

                    FileManipulation.SaveFile(fileContent.ToByteArray(), path, filename, attributes: FileAttributes.ReadOnly);
                }
                finally
                {
                    rsa.PersistKeyInCsp = false;
                }
            }
        }
예제 #29
0
        public void Main_Decrypting_MultipleFile_Verbosity_OK()
        {
            Setup.Initialize(out var testFolders);
            Setup.SetEncryptedFiles(testFolders, true);

            string[] originalFilesPath = Directory.GetFiles(testFolders["original"]);
            string[] targetFilesPath   = Directory.GetFiles(testFolders["encrypted"], "*encrypt*");

            Array.Sort(targetFilesPath);

            string[] args =
            {
                "-d",                                        "--verbose",
                $@"--key={Setup.AbsolutePath}\priv.key.pem",
                $"--output={testFolders["decrypted"]}",
                $"--target={testFolders["encrypted"]}",
            };

            Program.Main(args);

            string[] outputFilesPath = Directory.GetFiles(testFolders["decrypted"]);
            Array.Sort(outputFilesPath);

            Assert.Equal(outputFilesPath.Length, originalFilesPath.Length);

            for (int i = 0; i < targetFilesPath.Length; i++)
            {
                FileManipulation.OpenFile(outputFilesPath[i], out var outputFile);
                Assert.NotNull(outputFile);

                FileManipulation.OpenFile(originalFilesPath[i], out var originalFile);
                Assert.NotNull(originalFile);

                Assert.Equal(outputFile.Length, originalFile.Length);
                Assert.Equal(outputFile, originalFile);
            }
        }
예제 #30
0
 public static SqlInt32 udf_clr_DeleteFile(string Path)
 {
     return(FileManipulation.DeleteFile(Path));
 }