Exemplo n.º 1
0
        /// <summary>
        /// Updates selected encrypted file with a specified unencrypted file.
        /// </summary>
        /// <param name="pathOnEfs">The name of the file to update.</param>
        /// <param name="updateFile">Updated, unencrypted file.</param>
        public void Update(string pathOnEfs, OriginalFile updateFile)
        {
            CertificateCheck("You cannot update files.");

            if (updateFile.FileSize > 2_000_000_000)
            {
                throw new Exception("File can't be larger than 2 GB.");
            }

            if (!CanItBeStored(updateFile.FileSize))
            {
                throw new Exception("Insufficient storage available. File can't be uploaded.");
            }

            var encryptedFile           = new EncryptedFile(pathOnEfs.Substring(pathOnEfs.LastIndexOf('\\') + 1).Split('.')[0]);
            var updatedEncryptedFileRaw = encryptedFile.Update(updateFile, File.ReadAllBytes(pathOnEfs), currentUser.Id, currentUser.PrivateKey);

            // Name update is always necessary because file's IV has been changed and possibly a new file has a different name.
            encryptedFile.NameEncryption(updateFile.GetOriginalFileFullName(),
                                         new AesAlgorithm(((SecurityDescriptor)encryptedFile.Headers[1]).GetKey((int)currentUser.Id, currentUser.PrivateKey),
                                                          ((SecurityDescriptor)encryptedFile.Headers[1]).IV, "OFB"));

            // delete the old encrypted file
            DeleteFile(pathOnEfs);

            if (CanItBeStored(updatedEncryptedFileRaw.Length))
            {
                CreateFile(updatedEncryptedFileRaw, pathOnEfs.Substring(0, pathOnEfs.LastIndexOf('\\')) + "\\" + encryptedFile.GetEncryptedFileFullName());
            }
            else
            {
                throw new Exception("Insufficient storage available. File can't be updated.");
            }
        }
Exemplo n.º 2
0
        public void EncryptFile(OriginalFile input, FileStream output, ProgressReporter reporter = null)
        {
            var cert = new X509Certificate2(this.receiver.PublicCertificate);

            if (cert == null)
            {
                reporter?.Log("Receiver certificate error. Aborting.");
            }
            else
            {
                reporter?.Log("Verifying certificate...");

                if (CertificateValidator.VerifyCertificate(cert) is false)
                {
                    reporter?.Log("Receiver's certificate is invalid. Aborting.");
                }
                else
                {
                    reporter?.Log("Receiver's certificate is valid.");
                    reporter?.Log("Encrypting file...");
                    FileCryptor cryptor = new FileCryptor(this.currentUser.PrivateKey, ((RSACryptoServiceProvider)cert.PublicKey.Key).ExportParameters(false));
                    cryptor.Encrypt(input, output, this.combo, reporter.SetPercentage);
                    reporter?.Log("File encryption complete.");
                }
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Uploads selected file. File is first encrypted after which is stored on the specified path on encrypted file system.
        /// </summary>
        /// <param name="originalFile">Original, unencrypted file.</param>
        /// <param name="pathOnEfs">Path on the encrypted file system where the file will be stored.</param>
        /// <param name="algorithmNameSignature">Name of the algorithm used for file encryption.</param>
        /// <param name="hashAlgorithmName">Name of the hashing algorithm used to create a file signature.</param>
        /// <returns>Encrypted name of the file.</returns>
        public string Upload(OriginalFile originalFile, string pathOnEfs, string algorithmNameSignature, string hashAlgorithmName)
        {
            CertificateCheck("You cannot import any new files.");

            string encryptedName;

            if (originalFile.FileSize > 1_900_000_000)
            {
                throw new Exception("File can't be larger than 2 GB.");
            }

            if (CanItBeStored(originalFile.FileSize))
            {
                var encryptedFile    = new EncryptedFile(originalFile.GetOriginalFileFullName(), (uint)currentUser.Id, algorithmNameSignature, hashAlgorithmName, currentUser.PublicKey, currentUser.PrivateKey);
                var encryptedFileRaw = encryptedFile.Encrypt(originalFile, currentUser.Id, currentUser.PrivateKey);
                encryptedName = encryptedFile.EncryptedName;

                // var userPrivateKey = currentUser.GetPrivateKey(privateKeyPath, password);

                if (CanItBeStored(encryptedFileRaw.Length))
                {
                    CreateFile(encryptedFileRaw, pathOnEfs + "\\" + encryptedFile.GetEncryptedFileFullName());
                }
                else
                {
                    throw new Exception("Insufficient storage available. File can't be uploaded.");
                }
            }
            else
            {
                throw new Exception("Insufficient storage available. File can't be uploaded.");
            }

            return(encryptedName);
        }
Exemplo n.º 4
0
        public void TestTwofishFileDecryption()
        {
            byte[] data = new byte[10000];
            new Random().NextBytes(data); // fill random data

            using (var senderRsa = new RSACryptoServiceProvider())
            {
                var senderPrivateKey = senderRsa.ExportParameters(true);

                using (var receiverRsa = new RSACryptoServiceProvider())
                {
                    var receiverPrivateKey = receiverRsa.ExportParameters(true);
                    var receiverPublicKey  = receiverRsa.ExportParameters(false);

                    CryptCombo   combo             = new CryptCombo(MD5.Create(), new TwofishMachine());
                    MemoryStream cryptedFileStream = new MemoryStream();

                    OriginalFile originFile = new OriginalFile(new MemoryStream(data), ".java");
                    FileCryptor  cryptor    = new FileCryptor(senderPrivateKey, receiverPublicKey);
                    cryptor.Encrypt(originFile, cryptedFileStream, combo);

                    MemoryStream  decryptedStream = new MemoryStream();
                    EncryptedFile newCryptedFile  = EncryptedFileChecker.Parse(cryptedFileStream);
                    FileDecryptor decryptor       = new FileDecryptor(receiverPrivateKey);
                    decryptor.Decrypt(newCryptedFile, decryptedStream);

                    Assert.IsTrue(decryptedStream.ToArray().SequenceEqual(data));
                }
            }
        }
Exemplo n.º 5
0
        public CsvMerger(DataTable originalFile, DataTable secondFile)
        {
            this.OriginalFile = originalFile;
            this.SecondFile   = secondFile;

            //Merges to dataTables
            OriginalFile.Merge(SecondFile);

            prepareTable();
        }
Exemplo n.º 6
0
        //Function that combines data of rows with the same dimensions (it gets indexes from "checkIfThisRowRepeats" function)
        //It places all data from the same rows in the first one on the list with selected dimensions
        //After creating row with all combined data, it deletes rows that repeat (from whom it took data earlier)
        void prepareTable()
        {
            int        i;
            int        n            = OriginalFile.Rows.Count;
            List <int> rowsToDelete = new List <int>();

            foreach (DataColumn column in OriginalFile.Columns)
            {
                column.ReadOnly = false;
            }

            for (i = 0; i < n; i++)
            {
                DataRow currentRow = OriginalFile.Rows[i];

                List <int> sameCustomerAndProductRowIndex = checkIfThisRowRepeats(OriginalFile, currentRow);

                if (sameCustomerAndProductRowIndex != null)
                {
                    int j;

                    for (j = 0; j < OriginalFile.Columns.Count; j++)
                    {
                        if (currentRow.ItemArray[j].ToString() == "")
                        {
                            foreach (int index in sameCustomerAndProductRowIndex)
                            {
                                if (OriginalFile.Rows[index].ItemArray[j].ToString() != "")
                                {
                                    currentRow.SetField(j, OriginalFile.Rows[index].ItemArray[j].ToString());
                                    break;
                                }
                            }
                        }
                    }

                    sameCustomerAndProductRowIndex.RemoveAt(0);

                    foreach (int index in sameCustomerAndProductRowIndex)
                    {
                        if (!rowsToDelete.Contains(index))
                        {
                            rowsToDelete.Add(index);
                        }
                    }
                }
            }

            foreach (int index in rowsToDelete)
            {
                OriginalFile.Rows[index].Delete();
            }

            OriginalFile.AcceptChanges();
        }
Exemplo n.º 7
0
 public virtual void Save()
 {
     if (!Directory.Exists(this.SavePhysicalPath))
     {
         Directory.CreateDirectory(this.SavePhysicalPath);
     }
     if (OriginalFile != null)
     {
         OriginalFile.SaveAs(this.SavePhysicalPath + this.FileName);
     }
 }
Exemplo n.º 8
0
        /// <summary>
        /// Uploads selected file. File is first encrypted after which is stored on the specified path on encrypted file system.
        /// </summary>
        /// <param name="pathOnFs">The fully qualified name of the new file.</param>
        /// <param name="pathOnEfs">Path on the encrypted file system where the file will be stored.</param>
        /// <param name="algorithmNameSignature">Name of the algorithm used for file encryption.</param>
        /// <param name="hashAlgorithmName">Name of the hashing algorithm used to create a file signature.</param>
        /// <param name="deleteOriginal">Flag used to remove an original copy of file.</param>
        /// <returns>Encrypted name of the file.</returns>
        public string Upload(string pathOnFs, string pathOnEfs, string algorithmNameSignature, string hashAlgorithmName, bool deleteOriginal = false)
        {
            if (Convert.ToDateTime(currentUser.CertificateExpirationDate) < DateTime.Now)
            {
                throw new Exception("Your certificate has expired. You cannot import any new files.");
            }

            // var fileSize = new FileInfo(pathOnFs).Length;
            var fullFileName = pathOnFs.Substring(pathOnFs.LastIndexOf('\\') + 1);
            var originalFile = new OriginalFile(File.ReadAllBytes(pathOnFs), fullFileName);

            var encryptedName = Upload(originalFile, pathOnEfs, algorithmNameSignature, hashAlgorithmName);

            if (deleteOriginal)
            {
                DeleteFile(pathOnFs);
            }

            return(encryptedName);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Encrypts a file using a combination of an encryption and a hash algorithm.
        /// </summary>
        /// <param name="input"><see cref="OriginalFile"/> to be encrypted.</param>
        /// <param name="output">Output <see cref="Stream"/> where the encrypted file will be written.</param>
        /// <param name="algs">Combination of an encryption and a hash algorithm.</param>
        /// <param name="reportProgress">Action used to report progress somewhere.</param>
        public void Encrypt(OriginalFile input, Stream output, CryptCombo algs, Action <int> reportProgress = null)
        {
            BinaryWriter writer = new BinaryWriter(output); // to write to output
            BinaryReader reader = new BinaryReader(input.FileContent);

            writer.Seek(0, SeekOrigin.Begin); // write to beginning, this will override if there is something there
            reader.BaseStream.Position = 0;   // read from beginning

            long numberOfBlocks = input.FileContent.Length / algs.Machine.BlockSize;

            if (numberOfBlocks * algs.Machine.BlockSize < input.FileContent.Length)
            {
                numberOfBlocks++;
            }

            var algKey     = algs.Machine.Key;
            var cryptedkey = new RsaMachine(this.ReceiverPublicKey).Encrypt(algKey);

            byte[] header = new byte[] { };
            header = header // we concat here instead of writing directly so we can calculate hash
                     .Concat(Helpers.MagicBytes)
                     .Concat(Encoding.ASCII.GetBytes(algs.Machine.GetSignatureString()))
                     .Concat(Encoding.ASCII.GetBytes(Helpers.GetCodeFromHasher(algs.Hasher)))
                     .Concat(BitConverter.GetBytes(cryptedkey.Length))
                     .Concat(cryptedkey)
                     .Concat(BitConverter.GetBytes(input.Extension.Length))
                     .Concat(Encoding.ASCII.GetBytes(input.Extension))
                     .Concat(BitConverter.GetBytes(numberOfBlocks))
                     .ToArray();

            var contentHashAggregate = algs.Hasher.ComputeHash(header);

            writer.Write(header);
            reportProgress?.Invoke(25);

            byte[] additionalData = algs.Machine.AdditionalData;
            if (additionalData != null)
            {
                contentHashAggregate = algs.Hasher.ComputeHash(contentHashAggregate.Concat(algs.Hasher.ComputeHash(additionalData)).ToArray());
                writer.Write(additionalData);
            }

            reportProgress?.Invoke(30);
            for (int i = 0; i < numberOfBlocks; i++)
            {
                byte[] buffer         = reader.ReadBytes(algs.Machine.BlockSize);
                byte[] encryptedBlock = algs.Machine.Encrypt(buffer);
                byte[] encSize        = BitConverter.GetBytes(encryptedBlock.Length);
                byte[] blockToWrite   = encSize.Concat(encryptedBlock).ToArray();
                contentHashAggregate = algs.Hasher.ComputeHash(contentHashAggregate.Concat(algs.Hasher.ComputeHash(blockToWrite)).ToArray());
                writer.Write(blockToWrite);

                int progress = (int)(((float)i / (float)numberOfBlocks) * 1000.00);
                reportProgress?.Invoke(progress < 980 ? progress : 980);
            }

            byte[] rsaSignature = new RsaMachine(this.SenderPrivateKey).Sign(contentHashAggregate, algs.Hasher);
            reportProgress?.Invoke(990);

            writer.Write(rsaSignature.Length);
            writer.Write(rsaSignature);
            reportProgress?.Invoke(1000);
        }
Exemplo n.º 10
0
        public async Task <string> Index()
        {
            //Consuming the given Sample API
            OriginalFile rootObj = new OriginalFile();

            using (var httpClient = new HttpClient())
            {
                using (var response = await httpClient.GetAsync("https://reqres.in/api/users"))
                {
                    string apiResponse = await response.Content.ReadAsStringAsync();

                    rootObj = JsonConvert.DeserializeObject <OriginalFile>(apiResponse);
                }
            }

            //Building JSON Object for the Facebook Response

            var FacebookResponse = new FacebookResponse
            {
                messaging_type = "RESPONSE",
                recipient      = new Recipient
                {
                    id = "{PSID}"
                },
                message = new Message
                {
                    attachment = new Attachment
                    {
                        type    = "template",
                        payload = new Payload
                        {
                            template_type = "generic",
                            elements      = new List <Element>()
                            {
                                //Only 1 generic template, chose it to be the third user, with 1 button
                                new Element()
                                {
                                    title          = rootObj.data[2].first_name,
                                    image_url      = rootObj.data[2].avatar,
                                    subtitle       = rootObj.data[2].last_name,
                                    default_action = new DefaultAction
                                    {
                                        type = "web_url",
                                        url  = "mailto:" + rootObj.data[2].email + "?Subject=Hello",
                                        webview_height_ratio = "tall"
                                    },
                                    buttons = new List <Button>()
                                    {
                                        new Button()
                                        {
                                            type  = "web_url",
                                            url   = "mailto:" + rootObj.data[2].email + "?Subject=Hello",
                                            title = "Send Email"
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            };
            //Converting to a JSON object and returning it
            var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(FacebookResponse);

            return(jsonString);
        }
Exemplo n.º 11
0
        private void button1_Click(object sender, EventArgs e)
        {
            invertFormAcces();
            labelSimulationStatus.Visible = true;
            int[] thresholds      = { 15 };
            int[] dictionarySizes = { 1024, 2048, 4096, 8192, 16384, 32768, 65536 };


            if (OriginalFile != null)
            {
                List <SimulationResult> simulations = new List <SimulationResult>(thresholds.Length * dictionarySizes.Length);

                string   delimiter = ",";
                string[] parts     = OriginalFile.Split('\\');
                string   imageName = parts[parts.Length - 1].Split('.')[0];

                foreach (int threshold in thresholds)
                {
                    StringBuilder sb = new StringBuilder();

                    sb.Append("Marime dictionar" + delimiter);
                    sb.Append("Prag" + delimiter);
                    sb.Append("Timp de executie compresie" + delimiter);
                    sb.Append("Timp de executie decompresie" + delimiter);
                    sb.Append("Numar de blocuri" + delimiter);
                    sb.Append("Marime fisier comprimat" + delimiter);
                    sb.Append("Marime fisier decomprimat" + delimiter);
                    sb.AppendLine("PSNR" + delimiter);

                    foreach (int dictionarySize in dictionarySizes)
                    {
                        AvqCompression = new AVQ(OriginalFile);
                        simulations.Add(AvqCompression.StartSimulation(threshold, dictionarySize));
                        labelSimulationStatus.Text = "Simulation D_" + dictionarySize + " P_" + threshold + " finished";
                        labelSimulationStatus.Refresh();
                    }

                    string filePath = @"D:\Facultate\Licenta\Img\" + imageName + "_P_" + threshold + ".csv";

                    foreach (SimulationResult result in simulations)
                    {
                        sb.Append(result.DictionarySize + delimiter);
                        sb.Append(result.Threshold + delimiter);
                        sb.Append(result.CompressionTime + delimiter);
                        sb.Append(result.DeompressionTime + delimiter);
                        sb.Append(result.BlocksNumber.ToString() + delimiter);
                        sb.Append(result.CompressedFileSize.ToString() + delimiter);
                        sb.Append(result.DecompressedFileSize.ToString() + delimiter);
                        sb.AppendLine(result.PSNR.ToString() + delimiter);
                    }

                    File.WriteAllText(filePath, sb.ToString());
                }
            }
            else
            {
                MessageBox.Show("You need to choose an image!");
            }



            labelSimulationStatus.Visible = false;
            invertFormAcces();
            MessageBox.Show("Simulation finished!");
        }