Ejemplo n.º 1
0
    // static int count = 0;
    public static AssetBundle LoadFromFile(string fullpath, out Stream fileStream)
    {
        // var watch = new System.Diagnostics.Stopwatch();
        // watch.Start();
        // Debug.Log("ASSETBUNDLE:" + fullpath + " : " + (count ++));
        fileStream = null;
#if UNITY_EDITOR
        FileStream fs = File.OpenRead(fullpath);
        byte []    bs = new byte[fs.Length];
        fs.Read(bs, 0, (int)fs.Length);
        decode(bs, 0, (int)fs.Length);
        return(AssetBundle.LoadFromMemory(bs));
#else
        AssetBundle   ab = null;
        EncryptStream et = new EncryptStream(fullpath);
        if (et.Exist())
        {
            ab = AssetBundle.LoadFromStream(et);
            if (ab != null)
            {
                fileStream = et;
            }
        }
        else
        {
            et.Dispose();
        }
        // ab = AssetBundle.LoadFromFile(fullpath);

        // watch.Stop();
        // UnityEngine.Debug.Log(string.Format("LoadFromStream bundle dela time {0}ms, {1}", watch.ElapsedMilliseconds, fullpath));
        return(ab);
#endif
    }
        public IActionResult DownloadFile(string q)
        {
            var fullPath = GetSafePath(q);

            var rangeStart = GetByteOffset();

            long fileLength = new FileInfo(fullPath).Length;
            var  fileStream = new EncryptStream(() => new FileStream(fullPath, FileMode.Open), this.coreEncryption, (rangeStart ?? 0) % 512);

            if (rangeStart == null)
            {
                Response.Headers.Add("Content-Length", fileLength.ToString());
            }
            else
            {
                long startbyte = rangeStart.Value;

                fileStream.Position = startbyte;

                Response.StatusCode = 206;
                Response.Headers.Add("Content-Length", (fileLength - startbyte).ToString());
                string contentRange = string.Format("bytes {0}-{1}/{2}", startbyte, fileLength - 1, fileLength);
                Response.Headers.Add("Content-Range", contentRange);
            }

            Response.Headers.Add("Accept-Ranges", "bytes");

            return(File(fileStream, "application/unknown", fileNameHelper.CreateAlternativeFileName(q) + extension));
        }
Ejemplo n.º 3
0
        public void TestEncryptStreamCreate()
        {
            // Setup
            // Test
            var enc = new EncryptStream();

            // Check
            Assert.IsNotNull(enc);
        }
Ejemplo n.º 4
0
        public void TestEncryptStreamGenerateNewKey()
        {
            // Setup
            var enc = new EncryptStream();

            // Test
            enc.GenerateNewKey();

            // Check
            Assert.IsNotNull(enc.Key);
            Assert.AreEqual(32, enc.Key.Length);
        }
Ejemplo n.º 5
0
        public void TestEncryptStreamEncrypt()
        {
            // Setup
            var enc = new EncryptStream();

            enc.GenerateNewKey();

            // Test
            var hexstring = enc.Encrypt("Test Message");

            // Check
            Assert.IsNotNull(hexstring);
            Assert.AreEqual(64, hexstring.Length);
        }
        private string CreateFileBackup(string data)
        {
            var guid         = Guid.NewGuid();
            var config       = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var datalocation = Path.Combine(config.AppSettings.Settings["FileRepo"].Value, guid.ToString());

            var encryptdata = new EncryptStream();

            encryptdata.GenerateNewKey();

            File.WriteAllText(datalocation, data);

            return(datalocation);
        }
Ejemplo n.º 7
0
        public void TestEncryptStreamDecrypt()
        {
            // Setup
            var enc = new EncryptStream();

            enc.Key = new byte[]
            {
                0xcd, 0x4f, 0x51, 0x98, 0xa3, 0xe8, 0x6c, 0xf4, 0x56, 0x18, 0x30, 0xf0, 0xdf, 0x18, 0x5e, 0x37,
                0x3c, 0x00, 0x3d, 0x12, 0x45, 0x74, 0xf2, 0xa6, 0x80, 0x0d, 0x5e, 0x84, 0xa8, 0x62, 0x03, 0x22
            };

            // Test
            var planestring = enc.Decrypt("49D9C6AC05FDEC3EE69099DF64A01FD5DA2B4D93050A13DB3D5ACA37B88337AC");

            // Check
            Assert.IsNotNull(planestring);
            Assert.AreEqual("Test Message", planestring);
        }
        public IActionResult DownloadMultiFile(string[] q, string path)
        {
            var filePaths = q.Select(x => GetSafePath(SafeCombine(path, x))).ToList();

            var tempLocation    = GetTempPathConfig();
            var newGuidFileName = Guid.NewGuid() + ".zip";
            var tempFullPath    = SafeCombine(tempLocation, newGuidFileName);

            using (var archiveStream = System.IO.File.OpenWrite(tempFullPath))
                using (var zip = new ZipArchive(archiveStream, ZipArchiveMode.Create))
                {
                    foreach (var filePath in filePaths)
                    {
                        AddFilesRecursively(zip, "", filePath);
                    }
                }

            var fileStream = new EncryptStream(() => new FileStream(tempFullPath, FileMode.Open), this.coreEncryption, 0, () => System.IO.File.Delete(tempFullPath));

            return(File(fileStream, "application/unknown", fileNameHelper.CreateAlternativeFileName(newGuidFileName) + extension));
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Шифрует файл
        /// </summary>
        /// <param name="IntStream">Исходный поток</param>
        /// <param name="size">Размер файла после шифрования</param>
        /// <param name="error">Данные ошибки</param>
        /// <returns>Зашифрованный поток</returns>
        public EncryptStream Encrypt(Stream IntStream, string LocalFile, ref long size, out string error)
        {
            error = null;
            try
            {
                // Узнаем размер файла в зашифрованном виде
                size = EncryptSize(LocalFile);

                // Получаем поток для шифрования
                ICryptoTransform EncryptoTransform = GetAES().CreateEncryptor();

                //Подключаем поток для расшифровки данных
                var stream = new EncryptStream(IntStream, EncryptoTransform, CryptoStreamMode.Read);
                stream.SetLength(size);
                return(stream);
            }
            catch (Exception ex)
            {
                error = ex.ToString();
                return(null);
            }
        }
Ejemplo n.º 10
0
    public static AssetBundleCreateRequest LoadFromFileAsync(string fullpath, out Stream fileStream)
    {
        // Debug.Log("ASSETBUNDLE ASYNC:" + fullpath + " : " + (count++));

        fileStream = null;

#if UNITY_EDITOR
        FileStream fs = File.OpenRead(fullpath);
        byte[]     bs = new byte[fs.Length];
        fs.Read(bs, 0, (int)fs.Length);
        decode(bs, 0, (int)fs.Length);
        return(AssetBundle.LoadFromMemoryAsync(bs));
#else
        AssetBundleCreateRequest req = null;
        EncryptStream            et  = new EncryptStream(fullpath);
        if (et.Exist())
        {
            fileStream = et;
            req        = AssetBundle.LoadFromStreamAsync(et);
        }

        return(req);
#endif
    }
Ejemplo n.º 11
0
        /// <summary>
        /// Tests EncryptStream and DecryptStream using cloud storage. A single
        /// file is uploaded in encrypted form and then downloaded.
        /// </summary>
        public void test_Encrypt_and_Decrypt_streams_on_cloud()
        {
            Console.WriteLine("About to upload a file to the cloud and download it back, "
                              + "using EncryptStream and DecryptStream. Press any key to continue, or ESC to skip.\n");
            if (hit_esc_key())
            {
                return;
            }

            var backup_services = create_cloud_backup_services_from_xml(cloud_backup_services_xml);

            // Choose one of the "backup_services" for use in testing.
            CloudBackupService backup_service = backup_services[2];
            string             bucket_name    = "xxxxxxxx";

            string original_file = @"E:\temp\temp\temp.bin";
            string base_path     = @"E:\temp\temp";
            string relative_path = original_file.Substring(base_path.Length + 1);

            string decrypted_file = @"E:\temp\temp2\temp.bin";

            var encrypt_stream = new EncryptStream();
            var decrypt_stream = new DecryptStream();

            Random random = new Random();

            byte[] buffer = new byte[1024];

            // create random file
            using (var fs = new FileStream(original_file, FileMode.Create, FileAccess.Write))
            {
                for (int j = 0; j < 640; j++)
                {
                    random.NextBytes(buffer);
                    fs.Write(buffer, 0, buffer.Length);
                }
            }

            // encrypted upload
            Console.WriteLine("Encrypting and uploading file to the cloud.");
            encrypt_stream.reset(original_file, relative_path, key);
            backup_service.upload(encrypt_stream, bucket_name, "temp.bin");

            Console.WriteLine("The file has been encrypted and uploaded to the cloud.");
            Thread.Sleep(2000);

            // download and decrypt
            decrypt_stream.reset(key, full_path_request_handler);

            // be sure the download can be done in pieces
            backup_service.download(bucket_name, "temp.bin", decrypt_stream, 0, 1024);
            Console.WriteLine("The first 1kB header says the pre-encrypt file size is "
                              + file_pre_encrypt_size + " bytes.");

            backup_service.download(bucket_name, "temp.bin", decrypt_stream, 1024, file_pre_encrypt_size);

            decrypt_stream.Flush();
            backup_service.delete(bucket_name, "temp.bin");

            Debug.Assert(compare_files(original_file, decrypted_file));

            Console.WriteLine("EncryptStream and DecryptStream has been tested using cloud storage.\n");
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Tests EncryptStream and DecryptStream using disk files. Different files
        /// are encrypted and then decrypted, both with and without compression.
        /// </summary>
        public void test_Encrypt_and_Decrypt_streams_on_disk()
        {
            Console.WriteLine("About to test EncryptStream and DecryptStream using files on disk."
                              + " Press any key to continue, or ESC to skip.\n");
            if (hit_esc_key())
            {
                return;
            }

            // paths:
            string original_file = @"E:\temp\temp\temp.bin";
            string base_path     = @"E:\temp\temp";
            string relative_path = original_file.Substring(base_path.Length + 1);

            string encrypted_file = @"E:\temp\temp2\temp_en.bin";
            string decrypted_file = @"E:\temp\temp2\temp.bin";

            var encrypt_stream = new EncryptStream();
            var decrypt_stream = new DecryptStream();

            Random random = new Random();

            for (int i = 0; i < 5; i++)
            {
                bool do_not_compress = false;

                // The different tests try different input files.
                if (i == 0)
                {
                    // zero byte file
                    using (var fs = new FileStream(original_file, FileMode.Create, FileAccess.Write)) { }
                }
                else if (i == 1)
                {
                    // one byte file
                    using (var fs = new FileStream(original_file, FileMode.Create, FileAccess.Write))
                        fs.WriteByte((byte)(random.Next(0, 256)));
                }

                else if (i == 2 || i == 3)
                {
                    // test #2: file with repetitive bytes
                    // test #3: file with repetitive bytes - no compression
                    if (i == 3)
                    {
                        do_not_compress = true;
                    }

                    byte[][] patterns = new byte[32][];
                    for (int j = 0; j < patterns.Length; j++)
                    {
                        patterns[j] = new byte[32];
                        random.NextBytes(patterns[j]);
                    }

                    using (var fs = new FileStream(original_file, FileMode.Create, FileAccess.Write))
                    {
                        for (int j = 0; j < 1024 * 10; j++)
                        {
                            int pattern_to_use = random.Next(0, 32);
                            fs.Write(patterns[pattern_to_use], 0, patterns[pattern_to_use].Length);
                        }
                    }
                }

                else if (i == 4)
                {
                    // random file
                    byte[] buffer = new byte[1024];

                    using (var fs = new FileStream(original_file, FileMode.Create, FileAccess.Write))
                    {
                        for (int j = 0; j < 1024; j++)
                        {
                            random.NextBytes(buffer);
                            fs.Write(buffer, 0, buffer.Length);
                        }
                    }
                }

                // The rest of the test is the same - encrypt, decrypt, the compare files.

                encrypt_stream.reset(original_file, relative_path, key, do_not_compress);
                using (var output_fs = new FileStream(encrypted_file, FileMode.Create))
                    encrypt_stream.CopyTo(output_fs);

                decrypt_stream.reset(key, full_path_request_handler);
                using (var fs = new FileStream(encrypted_file, FileMode.Open))
                    fs.CopyTo(decrypt_stream);
                decrypt_stream.Flush();

                Debug.Assert(compare_files(original_file, decrypted_file));
            }

            Console.WriteLine("EncryptStream and DecryptStream tested using disk.\n");
        }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            Console.WriteLine("Enter 1 for Factory Pattern. \n" +
                              "Enter 2 for Observer Pattern.");
            int choice = Convert.ToInt32(Console.ReadLine());

            switch (choice)
            {
            case 1:
                var ef = new EmployeeFactory();
                Console.WriteLine(ef.GetEmployee(1).GetBonus());
                Console.ReadLine();
                break;

            case 2:
                var observable = new TemperatureMonitor();
                var observer   = new TemperatureReporter();
                observer.Subscribe(observable);
                observable.GetTemperature();
                break;

            case 3:
                var editor  = new Editor();
                var history = new Momento.History();

                editor.SetContent("a");
                history.Push(editor.CreateState());
                editor.SetContent("b");
                history.Push(editor.CreateState());
                editor.SetContent("c");
                history.Push(editor.CreateState());
                editor.Restore(history.Pop());
                editor.Restore(history.Pop());

                Console.WriteLine(editor.GetContent());
                break;

            case 4:

                Canvas canvas = new Canvas();
                canvas.SelectTool(new BrushTool());
                canvas.MouseDown();
                canvas.MouseUp();
                break;

            case 5:

                BrowseHistory browseHistory = new BrowseHistory();
                browseHistory.Push("www.google.com");
                browseHistory.Push("www.yahoo.com");
                browseHistory.Push("www.reddif.com");
                browseHistory.Push("www.youtube.com");

                IIterator <string> iterator = browseHistory.CreateIterator();
                while (iterator.HasNext())
                {
                    var url = iterator.Current();
                    Console.WriteLine(url);
                    iterator.next();
                }
                break;

            case 6:
                //The difference between State and Strategy pattern is that in state pattern there is only a single state of the object and the behaviour is determined by the implementation injected.
                //In strategy pattern there could be multiple behaviours in form of multiple properties inside class such as IFilter & ICompression. The implementation injected further changes the behaviour.
                PhotoProcessor photoProcessor = new PhotoProcessor(new BnW(), new JPEG());
                photoProcessor.ProcessPhoto();
                break;

            case 7:     //template
                AbstractPreFlightCheckList flightChecklist = new F16PreFlightCheckList();
                flightChecklist.runChecklist();

                break;

            case 8:     //command
                var service = new CustomerService();
                var command = new AddCustomerCommand(service);
                var button  = new Command.Button(command);
                button.click();

                var composite = new CompositeCommand();
                composite.Add(new ResizeCommand());
                composite.Add(new BlackAndWHiteCommand());
                var button2 = new Command.Button(composite);
                button2.click();

                var commandHisotry = new Command.Undo.History();

                var doc = new Command.Undo.HtmlDocument();
                doc.SetContent("Hello World");
                var boldCommand = new BoldCommand(doc, commandHisotry);
                boldCommand.Execute();
                Console.WriteLine(doc.GetContent());

                var undoCommand = new UndoCommand(commandHisotry);
                undoCommand.Execute();
                Console.WriteLine(doc.GetContent());

                break;

            case 9:     //Observer
                DataSource dataSource = new DataSource();
                dataSource.AddObserver(new Chart());
                dataSource.AddObserver(new SpreadSheet(dataSource));
                dataSource.SetValue("value changed");
                break;

            case 10:     //Mediator //the pattern is applied to encapsulate or centralize the interactions amongst a number of objects
                var dialog = new ArticlesDialogBox();
                dialog.SimulateUsserInteraction();
                break;

            case 11:     //Chain of Responsibility
                //autehnticator --> logger --> compressor --> null
                var compressor    = new Compressor(null);
                var logger        = new Logger(compressor);
                var authenticator = new Authenticator(logger);
                var server        = new WebServer(authenticator);
                server.handle(new HttpRequest()
                {
                    UserName = "******", Password = "******"
                });
                break;

            case 12:     //Visitor
                var document = new Visitor.HtmlDocument();
                document.Add(new HeadingNode());
                document.Add(new AnchorNode());
                document.Execute(new HighlighOperation());
                break;

            case 13:     // Composite
                var shape1 = new Shape();
                var shape2 = new Shape();
                var group1 = new Group();
                group1.Add(shape1);
                group1.Add(shape2);
                var group2 = new Group();
                var shape3 = new Shape();
                group2.Add(shape3);
                group1.Add(group2);
                group1.render();
                break;

            case 14:     //Adapter
                Image       image       = new Image();
                ImageViewer imageViewer = new ImageViewer(image);
                imageViewer.Apply(new SepiaFilter());
                imageViewer.Apply(new FancyAdapter(new FancyFilter()));
                break;

            case 15:     //Decorator
                var cloudStream  = new CloudStream();
                var encryptData  = new EncryptStream(cloudStream);
                var compressData = new CompressStream(encryptData);
                compressData.write("some random data");
                break;

            case 16:     //Facade
                NotificationService notificationService = new NotificationService();
                notificationService.Send("Hello..", "17.0.0.1");
                break;

            case 17:     //Flyweight
                PointService pointService = new PointService(new PointFactory());
                var          points       = pointService.getPoints();
                foreach (var p in points)
                {
                    p.draw();
                }
                break;

            case 18:     //Bridge
                AdvancedRemoteControl remote = new AdvancedRemoteControl(new SonyTv());
                remote.setChannel(1);
                break;

            case 19:     //Proxy
                Library       lib       = new Library();
                List <string> bookNames = new List <string>()
                {
                    "a", "b", "c"
                };
                foreach (var book in bookNames)
                {
                    lib.eBooks.Add(book, new EBookProxy(book));
                }
                lib.OpenEbook("a");
                break;

            case 20:     //Factory Method
                FactoryMethod.Employee emp          = new FactoryMethod.Employee();
                BaseEmployeeFactory    permanentEmp = new PermanentEmployeeFactory(emp);
                permanentEmp.ApplySalary();
                Console.WriteLine(emp.HouseAllowance);
                break;

            case 21:     //Abstract Factory
                AbstractFactory.Employee emp1 = new AbstractFactory.Employee();
                emp1.EmployeeTypeID = 1;
                emp1.JobDescription = "Manager";
                EmployeeSystemFactory esf = new EmployeeSystemFactory();
                var computerFactory       = esf.Create(emp1);
                Console.WriteLine($"{computerFactory.GetType()}, {computerFactory.Processor()}, {computerFactory.SystemType()}, {computerFactory.Brand()}");
                break;

            case 22:     //Builder
                Builder.IToyBuilder toyBuilder  = new Builder.PremiumToyBuilder();
                Builder.ToyDirector toyDirector = new Builder.ToyDirector(toyBuilder);
                toyDirector.CreateFullFledgedToy();
                Console.WriteLine(toyDirector.GetToy());
                break;

            case 23:     //Fluent Builder
                //Difference of implementation is visible in Director class.
                FluentBuilder.IToyBuilder toyBuilder1  = new FluentBuilder.PremiumToyBuilder();
                FluentBuilder.ToyDirector toyDirector1 = new FluentBuilder.ToyDirector(toyBuilder1);
                toyDirector1.CreateFullFledgedToy();
                Console.WriteLine(toyDirector1.GetToy());
                break;

            case 24:    //Object Pool
                ObjectPool <OneExpensiveObjToCreate> objPool = new ObjectPool <OneExpensiveObjToCreate>();
                OneExpensiveObjToCreate obj = objPool.Get();
                objPool.Release(obj);
                break;
            }

            Console.ReadLine();
        }