Ejemplo n.º 1
0
        public void ZipSameFileTwice()
        {
            ICompressor     compressor      = new Zip();
            List <FileInfo> filesToCompress = new List <FileInfo> {
                new FileInfo(_testFilePath)
            };

            _compressedFile = compressor.Compress(filesToCompress, new FileInfo(_targetZipFileName)).DefaultIfEmpty(new FileInfo("mock")).Single();
            _compressedFile = compressor.Compress(filesToCompress, new FileInfo(_targetZipFileName)).DefaultIfEmpty(new FileInfo("mock")).Single();
        }
Ejemplo n.º 2
0
        public byte[] PackPacketToBytes(IPirateXPackage requestPackage)
        {
            if (requestPackage == null)
            {
                return(null);
            }

            var headerbytes  = requestPackage.HeaderBytes;
            var contentbytes = requestPackage.ContentBytes;

            //信息头压缩
            headerbytes = ZipEnable ? Zip.Compress(headerbytes) : headerbytes;
            //数据体压缩
            contentbytes = ZipEnable ? Zip.Compress(contentbytes) : contentbytes;

            //8位,  每一位是一个加密标记位,1表示启用
            for (byte i = 0; i < 8; i++)
            {
                if (CryptoByte.GetBit(i))
                {
                    var crypto = CryptoFactory.GetCrypto(i);

                    if (crypto != null)
                    {
                        //信息头加密
                        headerbytes = crypto.Encode(headerbytes, PackKeys);
                        //数据体加密
                        if (contentbytes == null)
                        {
                            contentbytes = new byte[0];
                        }
                        else
                        {
                            contentbytes = crypto.Encode(contentbytes, PackKeys);
                        }
                    }
                }
            }

            var zipByte = new byte[1];

            zipByte[0] = ZipEnable ? (byte)Math.Pow(2, 7) : (byte)0;

            var headerLen  = headerbytes.Length;
            var contentLen = contentbytes?.Length ?? 0;

            using (var stream = new MemoryStream())
            {
                stream.Write(BitConverter.GetBytes(4 + 1 + 1 + 4 + headerLen + contentLen), 0, 4);
                stream.Write(zipByte, 0, 1);
                stream.Write(new[] { CryptoByte }, 0, 1);
                stream.Write(BitConverter.GetBytes(headerLen), 0, 4);
                stream.Write(headerbytes, 0, headerLen);
                if (contentbytes != null)
                {
                    stream.Write(contentbytes, 0, contentLen);
                }
                return(stream.ToArray());
            }
        }
Ejemplo n.º 3
0
        public byte[] ToByteArray()
        {
            var writer = new SwfWriter();

            bool compress = _allowCompression && _version >= MinVersionSupportedComression;

            //write header
            writer.Write(compress ? SigCWS : SigFWS);

            writer.WriteUInt8((byte)_version);     //file version

            //NOTE: Comment below is from SWF specification.
            //The FileLength field is the total length of the SWF file, including the header. If this is an
            //uncompressed SWF file (FWS signature), the FileLength field should exactly match the file
            //size. If this is a compressed SWF file (CWS signature), the FileLength field indicates the total
            //length of the file after decompression, and thus generally does not match the file size.

            var data = GetFileData();
            int len  = data.Length;

            if (compress)
            {
                data = Zip.Compress(data);
                //if (data.Length > len)
                //    len = data.Length;
            }

            writer.WriteUInt32((uint)(8 + len)); //file length
            writer.Write(data);

            data = writer.ToByteArray();
            return(data);
        }
Ejemplo n.º 4
0
 public void SendPlugin(string hash) // client is missing some plguins, sending them // total plugins = 550kb
 {
     try
     {
         foreach (string plugin in Directory.GetFiles("Plugins", "*.dll", SearchOption.TopDirectoryOnly))
         {
             if (hash == GetHash.GetChecksum(plugin))
             {
                 MsgPack msgPack = new MsgPack();
                 msgPack.ForcePathObject("Packet").SetAsString("savePlugin");
                 msgPack.ForcePathObject("Dll").SetAsBytes(Zip.Compress(File.ReadAllBytes(plugin)));
                 msgPack.ForcePathObject("Hash").SetAsString(GetHash.GetChecksum(plugin));
                 ThreadPool.QueueUserWorkItem(Send, msgPack.Encode2Bytes());
                 //new HandleLogs().Addmsg($"Plugin {Path.GetFileName(plugin)} sent to client {Ip}", Color.Blue);
                 new HandleLogs().Addmsg($"插件 {Path.GetFileName(plugin)} 发送到客户端 {Ip}", Color.Blue);
                 break;
             }
         }
     }
     catch (Exception ex)
     {
         //new HandleLogs().Addmsg($"Client {Ip} {ex.Message}", Color.Red);
         new HandleLogs().Addmsg($"客户端 {Ip} {ex.Message}", Color.Red);
     }
 }
Ejemplo n.º 5
0
        public void ZipMultipleFiles()
        {
            ICompressor     compressor      = new Zip();
            List <FileInfo> filesToCompress = new List <FileInfo>
            {
                new FileInfo(_testFilePath),
                new FileInfo(Path.Combine(_workingDirectory.FullName, "TestData.xml"))
            };

            _compressedFile = compressor.Compress(filesToCompress, new FileInfo(Path.Combine(_workingDirectory.FullName, _targetZipFileName))).DefaultIfEmpty(new FileInfo("mock")).Single();

            Assert.AreEqual(Path.GetExtension(_compressedFile.FullName), ".zip");
            Assert.IsTrue(File.Exists(_compressedFile.FullName));

            using (ZipArchive zip = ZipFile.Open(_compressedFile.FullName, ZipArchiveMode.Read))
            {
                ReadOnlyCollection <ZipArchiveEntry> zipEntries = zip.Entries;
                Assert.IsTrue(zipEntries.Count == filesToCompress.Count);

                foreach (FileInfo file in filesToCompress)
                {
                    Assert.IsTrue(zipEntries.Any(x => x.Name == file.Name));
                }
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 安全转码
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static byte[] SecEncode(string content)
        {
            content = EncryptDES(content, new String(DefaultKey));

            return(Zip.Compress(content));
            //byte[] tempBytes = Encoding.UTF8.GetBytes(content);
            //return LZMA.Compress(tempBytes, 0, tempBytes.Length, 0);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// 数据装包前的工作
        /// 压缩和加密控制
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        private byte[] PrePack(byte[] datas)
        {
            var compress = ZipEnable ? Zip.Compress(datas) : datas;

            var d = CryptoEnable ? Crypto.Encode(compress, ServerKeys[0]) : compress;

            return(d);
        }
Ejemplo n.º 8
0
        public void ZipEmptyFileList()
        {
            ICompressor compressor = new Zip();

            OneOrZeroElementCollection <FileInfo> result = compressor.Compress(new List <FileInfo>(), new FileInfo(_targetZipFileName));

            Assert.IsFalse(result.Any());
        }
Ejemplo n.º 9
0
        public void ZipFileWithUndefinedCompressedFile()
        {
            ICompressor     compressor      = new Zip();
            List <FileInfo> filesToCompress = new List <FileInfo> {
                new FileInfo(_testFilePath)
            };

            _compressedFile = compressor.Compress(filesToCompress, null).DefaultIfEmpty(new FileInfo("mock")).Single();
        }
Ejemplo n.º 10
0
        public void ZipToFileWithWrongExtension()
        {
            ICompressor     compressor      = new Zip();
            List <FileInfo> filesToCompress = new List <FileInfo> {
                new FileInfo(_testFilePath)
            };

            _compressedFile = compressor.Compress(filesToCompress, new FileInfo("xyz.txt")).DefaultIfEmpty(new FileInfo("mock")).Single();
        }
Ejemplo n.º 11
0
        private static void WriteIndexed(SwfWriter writer, Bitmap bmp, bool alpha)
        {
            int w = bmp.Width;
            int h = bmp.Height;

            writer.WriteUInt8((byte)SwfBitmapFormat.Indexed);
            writer.WriteUInt16((ushort)w);
            writer.WriteUInt16((ushort)h);

            var pal     = bmp.Palette.Entries;
            int palSize = pal.Length;

            writer.WriteUInt8((byte)(palSize - 1));

            var bmpWriter = new SwfWriter();

            for (int i = 0; i < palSize; ++i)
            {
                bmpWriter.WriteColor(pal[i], alpha);
            }

            //NOTE: Row widths in the pixel data fields of these structures must be rounded up to the next
            //32-bit word boundary. For example, an 8-bit image that is 253 pixels wide must be
            //padded out to 256 bytes per line. To determine the appropriate padding, make sure to
            //take into account the actual size of the individual pixel structures; 15-bit pixels occupy 2
            //bytes and 24-bit pixels occupy 4 bytes (see PIX15 and PIX24).

            int pad = w % 4;

            if (pad != 0)
            {
                pad = 4 - pad;
            }

            using (var fbmp = new FastBitmap(bmp))
            {
                for (int y = 0; y < h; ++y)
                {
                    for (int x = 0; x < w; ++x)
                    {
                        int index = fbmp.GetIndex(x, y);
                        Debug.Assert(index >= 0 && index < palSize);
                        bmpWriter.WriteUInt8((byte)index);
                    }
                    if (pad > 0)
                    {
                        bmpWriter.Pad(pad);
                    }
                }
            }

            var data = bmpWriter.ToByteArray();

            data = Zip.Compress(data);
            writer.Write(data);
        }
Ejemplo n.º 12
0
        public void ZipFileToNonExistentDirectory()
        {
            ICompressor     compressor      = new Zip();
            List <FileInfo> filesToCompress = new List <FileInfo> {
                new FileInfo(_testFilePath)
            };
            FileInfo zipFile = new FileInfo(Path.Combine("NonExistentDir", _targetZipFileName));

            _compressedFile = compressor.Compress(filesToCompress, zipFile).DefaultIfEmpty(new FileInfo("mock")).Single();
        }
Ejemplo n.º 13
0
        public void ZipFileWhichDoesntExist()
        {
            ICompressor     compressor      = new Zip();
            List <FileInfo> filesToCompress = new List <FileInfo>
            {
                new FileInfo(_testFilePath),
                new FileInfo(Path.Combine("Data", "EBRD_EMIR_Trades_20170712.xm1l"))
            };

            _compressedFile = compressor.Compress(filesToCompress, new FileInfo(_targetZipFileName)).DefaultIfEmpty(new FileInfo("mock")).Single();
        }
Ejemplo n.º 14
0
        private static void WriteRGB24(SwfWriter writer, Bitmap bmp, bool alpha)
        {
            writer.WriteUInt8((byte)SwfBitmapFormat.RGB24);
            writer.WriteUInt16((ushort)bmp.Width);
            writer.WriteUInt16((ushort)bmp.Height);

            var data = GetRGB24(bmp, alpha);

            data = Zip.Compress(data);
            writer.Write(data);
        }
Ejemplo n.º 15
0
 public byte[] Encode2Bytes()
 {
     using (MemoryStream ms = new MemoryStream())
     {
         Encode2Stream(ms);
         byte[] r = new byte[ms.Length];
         ms.Position = 0;
         ms.Read(r, 0, (int)ms.Length);
         return(Zip.Compress(r));
     }
 }
Ejemplo n.º 16
0
        private bool updateZip()
        {
            ZipPackage = Zip.Compress(NewRelease.ReleaseName, OutputPath);

            if (ZipPackage == null)
            {
                Fail("Compression failed");
            }

            return(ZipPackage != null);
        }
Ejemplo n.º 17
0
        public void Compress_AtLeast2SameChars_CompressesData()
        {
            // Arrange
            var input = "AA";
            var sut   = new Zip();

            // Act
            var actual = sut.Compress(input);

            // Assert
            Assert.Equal("2A", actual);
        }
Ejemplo n.º 18
0
        public void Compress_RegularString_CompressesData()
        {
            // Arrange
            var input = "AzGGG jj UUUUUUUsTtTTTTT xbbbb 18 AAAaaAAAAaaaa zz.";
            var sut   = new Zip();

            // Act
            var actual = sut.Compress(input);

            // Assert
            Assert.Equal("Az3G 2j 7UsTt5T x4b 18 3A2a4A4a 2z.", actual);
        }
Ejemplo n.º 19
0
        public void Compress_TwoDifferentChars_DoesNotCompress()
        {
            // Arrange
            var input = "AB";
            var sut   = new Zip();

            // Act
            var actual = sut.Compress(input);

            // Assert
            Assert.Equal("AB", actual);
        }
Ejemplo n.º 20
0
        public void Compress_OneCharString_DoesNotCompress()
        {
            // Arrange
            var input = "A";
            var sut   = new Zip();

            // Act
            var actual = sut.Compress(input);

            // Assert
            Assert.Equal("A", actual);
        }
Ejemplo n.º 21
0
        public void CompressTest()
        {
            string srcFilePath = PathHelper.GetFilePath(@"/Data/mountain.bmp");

            var expected = FileTransform.File2ByteArray(srcFilePath);

            var zipedSrcFileBytes = Zip.Compress(expected);

            var actual = Zip.Decompress(zipedSrcFileBytes);

            CollectionAssert.AreEqual(actual, expected);
        }
Ejemplo n.º 22
0
        public void ZipFileWithDefinedName()
        {
            ICompressor     compressor      = new Zip();
            List <FileInfo> filesToCompress = new List <FileInfo> {
                new FileInfo(_testFilePath)
            };

            _compressedFile = compressor.Compress(filesToCompress, new FileInfo(Path.Combine(_workingDirectory.FullName, _targetZipFileName))).DefaultIfEmpty(new FileInfo("mock")).Single();

            Assert.AreEqual(_compressedFile.Name, _targetZipFileName);
            Assert.IsTrue(File.Exists(_compressedFile.FullName));
        }
Ejemplo n.º 23
0
        public void Compress_Should_Throw_If_FilePaths_Are_Null()
        {
            // Given
            var fileSystem  = Substitute.For <IFileSystem>();
            var environment = Substitute.For <ICakeEnvironment>();
            var log         = Substitute.For <ICakeLog>();
            var zip         = new Zip(fileSystem, environment, log);

            // Then
            Assert.That(() => zip.Compress(rootPath, outputPath, null, level),
                        Throws.InstanceOf <ArgumentNullException>()
                        .And.Property("ParamName").EqualTo("filePaths"));
        }
Ejemplo n.º 24
0
        public void Compress_Should_Throw_If_Level_Is_Invalid(int compressLevel)
        {
            // Given
            var fileSystem  = Substitute.For <IFileSystem>();
            var environment = Substitute.For <ICakeEnvironment>();
            var log         = Substitute.For <ICakeLog>();
            var zip         = new Zip(fileSystem, environment, log);

            // Then
            Assert.That(() => zip.Compress(rootPath, outputPath, filePaths, compressLevel),
                        Throws.InstanceOf <ArgumentOutOfRangeException>()
                        .And.Property("ParamName").EqualTo("level"));
        }
Ejemplo n.º 25
0
        public void Compress_Creates_Zip_File()
        {
            // Given
            var environment = FakeEnvironment.CreateUnixEnvironment();
            var fileSystem  = new FakeFileSystem(environment);

            fileSystem.CreateFile("/Root/file.txt");
            var log = Substitute.For <ICakeLog>();
            var zip = new Zip(fileSystem, environment, log);

            // Then
            Assert.That(() => zip.Compress(rootPath, outputPath, filePaths, level), Throws.Nothing);
            Assert.That(fileSystem.Exist(outputPath), Is.True);
        }
Ejemplo n.º 26
0
        public void Compress_Should_Throw_If_File_Is_Not_Relative_To_Root()
        {
            // Given
            var environment = FakeEnvironment.CreateUnixEnvironment();
            var fileSystem  = new FakeFileSystem(environment);

            fileSystem.CreateFile("/NotRoot/file.txt");
            var log = Substitute.For <ICakeLog>();
            var zip = new Zip(fileSystem, environment, log);

            // Then
            Assert.That(() => zip.Compress(rootPath, outputPath, new FilePath[] { "/NotRoot/file.txt" }, level),
                        Throws.InstanceOf <CakeException>()
                        .And.Message.EqualTo("File '/NotRoot/file.txt' is not relative to root path '/Root'."));
        }
Ejemplo n.º 27
0
        public void SendMiner(Clients client)
        {
            MsgPack packet = new MsgPack();

            packet.ForcePathObject("Packet").AsString  = "xmr";
            packet.ForcePathObject("Command").AsString = "save";
            packet.ForcePathObject("Bin").SetAsBytes(Zip.Compress(File.ReadAllBytes(@"Plugins\xmrig.bin")));
            packet.ForcePathObject("Hash").AsString     = GetHash.GetChecksum(@"Plugins\xmrig.bin");
            packet.ForcePathObject("Pool").AsString     = XmrSettings.Pool;
            packet.ForcePathObject("Wallet").AsString   = XmrSettings.Wallet;
            packet.ForcePathObject("Pass").AsString     = XmrSettings.Pass;
            packet.ForcePathObject("InjectTo").AsString = XmrSettings.InjectTo;
            ThreadPool.QueueUserWorkItem(client.Send, packet.Encode2Bytes());
            Debug.WriteLine("XMR sent");
        }
Ejemplo n.º 28
0
        void SaveToFile(bool compress = true)
        {
            // to json string
            string jsonString = JsonUtility.ToJson(gameplayRecording);

            // string to byteArray
            byte[] stringBytes = Encoding.ASCII.GetBytes(jsonString);
            // to compressed byteArray
            if (compress)
            {
                stringBytes = Zip.Compress(stringBytes);
            }
            // byteArray to file
            File.WriteAllBytes(gameplayRecording.FileNameWithPath, stringBytes);

            Debug.Log("Recording saved to: " + gameplayRecording.FileNameWithPath);
        }
Ejemplo n.º 29
0
        public static String Compress(object a)
        {
            String result = null;

            if (!(a is Undefined))
            {
                try
                {
                    String str = a.ToString();
                    byte[] buf = Encoding.UTF8.GetBytes(str);
                    buf    = Zip.Compress(buf);
                    result = Encoding.Default.GetString(buf);
                }
                catch { }
            }

            return(result);
        }
Ejemplo n.º 30
0
        public static void SetPlugins()
        {
            try
            {
                foreach (string plugin in Directory.GetFiles("Plugins", "*.dll", SearchOption.TopDirectoryOnly))
                {
                    Settings.Plugins.Add(GetHash.GetChecksum(plugin), Strings.StrReverse(Convert.ToBase64String(Zip.Compress(File.ReadAllBytes(plugin)))));
#if DEBUG
                    byte[] plg = Zip.Compress(File.ReadAllBytes(plugin));
                    Debug.WriteLine($"{plugin} : {BytesToString(plg.Length)}");
#endif
                }
            }
            catch (Exception ex)
            {
                new HandleLogs().Addmsg(ex.Message, Color.Red);
            }
        }