public void StreamCryptoWrapperBaseTest()
        {
            if(!SetUpIsOK)
            {
                SetUp();
            }

            try
            {
                // Инициализируем генератор случайных чисел
                Random rnd = new Random(DateTime.Now.Ticks.GetHashCode());

                var password = new byte[255];
                var inputData = new byte[(1024 * 1024)]; // Размер тестовых данных - 1 Мб
                var inputData2 = new byte[(1024 * 1024)]; // Размер тестовых данных - 1 Мб
                var outputData = new byte[(1024 * 1024) + 32]; // В выходном потоке даем запас на выравнивание при шифровании

                // Генерируем случайный пароль...
                rnd.NextBytes(password);

                //...и случайные входные данные...
                rnd.NextBytes(inputData);

                //...затем выбираем случайное количество итераций при хешировании пароля
                int iterations = rnd.Next(1, 100);

                // Шифрование
                StreamCryptoWrapper streamCryptoWrapper = new StreamCryptoWrapper();
                streamCryptoWrapper.Initialize(password, iterations);
                MemoryStream inputStream = new MemoryStream(inputData);
                Stream outputStream = streamCryptoWrapper.WrapStream(new MemoryStream(outputData), true); // Шифрование
                inputStream.CopyTo(outputStream);
                inputStream.Close();
                outputStream.Flush();
                outputStream.Close();

                // Расшифровка
                streamCryptoWrapper = new StreamCryptoWrapper();
                streamCryptoWrapper.Initialize(password, iterations);
                Stream inputStream2 = streamCryptoWrapper.WrapStream(new MemoryStream(outputData), false); // Расшифровка
                MemoryStream outputStream2 = new MemoryStream(inputData2);
                inputStream2.CopyTo(outputStream2);
                inputStream2.Close();
                outputStream2.Flush();
                outputStream2.Close();

                // Проверка содержимого исходного массива и массива после расшифровки
                if(!inputData.SequenceEqual(inputData2))
                {
                    throw new InvalidDataException("StreamCryptoWrapperTest: Wrong decrypted data!");
                }
            } // try
            catch(Exception e)
            {
                Console.WriteLine(e.ToString());
                Assert.Fail();
            }
        }
예제 #2
0
        public static Stream JustDecryptAndDecompress(FileInfo file, string password, string salt)
        {
            MemoryStream decompressedStream = new MemoryStream();

            using (FileStream source = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read))
                using (StreamCryptoWrapper decryptedSource = StreamCryptoWrapper.Decrypt(source, password, salt))
                    using (MemoryStream decryptedMemory = new MemoryStream())
                    {
                        decryptedSource.CryptoStream.CopyTo(decryptedMemory);
                        decryptedMemory.Position = 0;
                        KeepLzmaCompressor.Decompress(decryptedMemory, decompressedStream);
                        decompressedStream.Position = 0;
                    }
            return(decompressedStream);
        }
예제 #3
0
        public override void Execute()
        {
            EnsurePathExists(PendingPath);

            try
            {
                if (_Mode == ModeEnum.CompressEncrypt)
                {
                    Program.log.Debug("starting backup of " + FromPath);

                    Program.log.Debug("=> compress and encrypt to " + PendingPath);

                    using (Stream encryptedStream = GetEncryptedStream())
                        using (StreamCryptoWrapper encryptedTarget = StreamCryptoWrapper.Encrypt(encryptedStream, _Password, _Salt))
                        {
                            using (Stream compressedStream = GetCompressedStream())
                            {
                                using (FileStream source = new FileStream(FromPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                                    KeepLzmaCompressor.Compress(source, compressedStream);

                                compressedStream.Position = 0;
                                Program.log.Debug("compression done, start encrypting");
                                compressedStream.CopyTo(encryptedTarget.CryptoStream);
                                encryptedTarget.CryptoStream.FlushFinalBlock();
                                Program.log.Debug("encryption done, hashing result");
                            }

                            encryptedStream.Position = 0;
                            ChecksumTarget           = KeepHasher.GetHash(encryptedStream);
                            encryptedStream.Position = 0;
                            SizeTarget = encryptedStream.Length;
                            Program.log.Debug("done");

                            if (encryptedStream is MemoryStream)
                            {
                                using (Stream target = new FileStream(PendingPath, FileMode.Create, FileAccess.Write, FileShare.Read))
                                    encryptedStream.CopyTo(target);
                            }
                        }
                }
                else if (_Mode == ModeEnum.DecryptDecompress)
                {
                    Program.log.Debug("<= decrypt and decompress " + FromPath);
                    using (FileStream source = new FileStream(FromPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                        using (StreamCryptoWrapper decryptedSource = StreamCryptoWrapper.Decrypt(source, _Password, _Salt))
                            using (Stream decryptedMemory = GetDecryptedStream())
                                using (FileStream target = new FileStream(PendingPath, FileMode.Create, FileAccess.Write, FileShare.Read))
                                {
                                    decryptedSource.CryptoStream.CopyTo(decryptedMemory);
                                    decryptedMemory.Position = 0;
                                    Program.log.Debug("decryption to memory done, decompressing to disc");
                                    KeepLzmaCompressor.Decompress(decryptedMemory, target);
                                    Program.log.Debug("decompression done");
                                }
                }
            }
            finally
            {
                foreach (string file in _TempFilesToDelete)
                {
                    Program.log.Debug("deleting temp file " + file);
                    File.Delete(file);
                }
            }

            EnsurePathExists(ToPath);

            Program.log.Debug("renaming " + PendingPath + " -> " + ToPath);
            File.Move(PendingPath, ToPath);

            if (_Mode == ModeEnum.DecryptDecompress)
            {
                Program.log.Debug("restoring metadata " + ToPath);
                FileInfo fi = new FileInfo(ToPath);
                fi.LastWriteTimeUtc = SourceFile.LastWriteTimeUtc;
                fi.CreationTimeUtc  = SourceFile.CreationTimeUtc;
                if (fi.Length != SourceFile.SizeBytes)
                {
                    Program.log.Error("size mismatch " + ToPath + " " + SourceFile.Sha256);
                }

                //string sha = Hashing.GetHash(fi);
                //if (sha != SourceFile.Sha256)
                //    Program.log.Error("hash mismatch " + ToPath + " " + sha + " but should be "+ SourceFile.Sha256);
            }
        }