void EncryptedFileCopy(FileStream file, Xp3Entry xp3entry, Stream output, bool compress) { if (file.Length > int.MaxValue) { throw new FileSizeException(); } using (var map = MemoryMappedFile.CreateFromFile(file, null, 0, MemoryMappedFileAccess.Read, null, HandleInheritability.None, true)) { uint unpacked_size = (uint)file.Length; xp3entry.UnpackedSize = (uint)unpacked_size; xp3entry.Size = (uint)unpacked_size; using (var view = map.CreateViewAccessor(0, unpacked_size, MemoryMappedFileAccess.Read)) { var segment = new Xp3Segment { IsCompressed = compress, Offset = output.Position, Size = unpacked_size, PackedSize = unpacked_size, }; if (compress) { output = new ZLibStream(output, CompressionMode.Compress, CompressionLevel.Level9, true); } unsafe { byte[] read_buffer = new byte[81920]; byte * ptr = view.GetPointer(0); try { var checksum = new Adler32(); bool hash_after_crypt = xp3entry.Cipher.HashAfterCrypt; if (!hash_after_crypt) { xp3entry.Hash = checksum.Update(ptr, (int)unpacked_size); } int offset = 0; int remaining = (int)unpacked_size; while (remaining > 0) { int amount = Math.Min(remaining, read_buffer.Length); remaining -= amount; Marshal.Copy((IntPtr)(ptr + offset), read_buffer, 0, amount); xp3entry.Cipher.Encrypt(xp3entry, offset, read_buffer, 0, amount); if (hash_after_crypt) { checksum.Update(read_buffer, 0, amount); } output.Write(read_buffer, 0, amount); offset += amount; } if (hash_after_crypt) { xp3entry.Hash = checksum.Value; } } finally { view.SafeMemoryMappedViewHandle.ReleasePointer(); if (compress) { var dest = (output as ZLibStream).BaseStream; output.Dispose(); segment.PackedSize = (uint)(dest.Position - segment.Offset); xp3entry.Size = segment.PackedSize; } xp3entry.Segments.Add(segment); } } } } }
public static int adler32([NotNull] IBufferProtocol data, long value = 1L) { using var buffer = data.GetBuffer(); return((int)Adler32.GetAdler32Checksum(value, buffer.AsUnsafeArray() ?? buffer.ToArray(), 0, buffer.NumBytes())); }
/// <summary> /// Reads and decodes a window, returning whether or not there was /// any more data to read. /// </summary> /// <returns> /// Whether or not the delta stream had reached the end of its data. /// </returns> bool DecodeWindow() { int windowIndicator = delta.ReadByte(); // Have we finished? if (windowIndicator == -1) { return(false); } // The stream to load source data from for this window, if any Stream sourceStream; // Where to reposition the source stream to after reading from it, if anywhere int sourceStreamPostReadSeek = -1; // xdelta3 uses an undocumented extra bit which indicates that there are an extra // 4 bytes at the end of the encoding for the window bool hasAdler32Checksum = ((windowIndicator & 4) == 4); // Get rid of the checksum bit for the rest windowIndicator &= 0xfb; // Work out what the source data is, and detect invalid window indicators switch (windowIndicator & 3) { // No source data used in this window case 0: sourceStream = null; break; // Source data comes from the original stream case 1: if (original == null) { throw new VcdiffFormatException ("Source stream requested by delta but not provided by caller."); } sourceStream = original; break; case 2: sourceStream = output; sourceStreamPostReadSeek = (int)output.Position; break; case 3: throw new VcdiffFormatException ("Invalid window indicator - bits 0 and 1 both set."); default: throw new VcdiffFormatException("Invalid window indicator - bits 3-7 not all zero."); } // Read the source data, if any byte[] sourceData = null; int sourceLength = 0; if (sourceStream != null) { sourceLength = IOHelper.ReadBigEndian7BitEncodedInt(delta); int sourcePosition = IOHelper.ReadBigEndian7BitEncodedInt(delta); sourceStream.Position = sourcePosition; sourceData = IOHelper.CheckedReadBytes(sourceStream, sourceLength); // Reposition the source stream if appropriate if (sourceStreamPostReadSeek != -1) { sourceStream.Position = sourceStreamPostReadSeek; } } // Read how long the delta encoding is - then ignore it IOHelper.ReadBigEndian7BitEncodedInt(delta); // Read how long the target window is int targetLength = IOHelper.ReadBigEndian7BitEncodedInt(delta); byte[] targetData = new byte[targetLength]; MemoryStream targetDataStream = new MemoryStream(targetData, true); // Read the indicator and the lengths of the different data sections byte deltaIndicator = IOHelper.CheckedReadByte(delta); if (deltaIndicator != 0) { throw new VcdiffFormatException("VcdiffDecoder is unable to handle compressed delta sections."); } int addRunDataLength = IOHelper.ReadBigEndian7BitEncodedInt(delta); int instructionsLength = IOHelper.ReadBigEndian7BitEncodedInt(delta); int addressesLength = IOHelper.ReadBigEndian7BitEncodedInt(delta); // If we've been given a checksum, we have to read it and we might as well // use it to check the data. int checksumInFile = 0; if (hasAdler32Checksum) { byte[] checksumBytes = IOHelper.CheckedReadBytes(delta, 4); checksumInFile = (checksumBytes[0] << 24) | (checksumBytes[1] << 16) | (checksumBytes[2] << 8) | checksumBytes[3]; } // Read all the data for this window byte[] addRunData = IOHelper.CheckedReadBytes(delta, addRunDataLength); byte[] instructions = IOHelper.CheckedReadBytes(delta, instructionsLength); byte[] addresses = IOHelper.CheckedReadBytes(delta, addressesLength); int addRunDataIndex = 0; MemoryStream instructionStream = new MemoryStream(instructions, false); cache.Reset(addresses); while (true) { int instructionIndex = instructionStream.ReadByte(); if (instructionIndex == -1) { break; } for (int i = 0; i < 2; i++) { Instruction instruction = codeTable[instructionIndex, i]; int size = instruction.Size; if (size == 0 && instruction.Type != InstructionType.NoOp) { size = IOHelper.ReadBigEndian7BitEncodedInt(instructionStream); } switch (instruction.Type) { case InstructionType.NoOp: break; case InstructionType.Add: targetDataStream.Write(addRunData, addRunDataIndex, size); addRunDataIndex += size; break; case InstructionType.Copy: int addr = cache.DecodeAddress((int)targetDataStream.Position + sourceLength, instruction.Mode); if (sourceData != null && addr < sourceData.Length) { targetDataStream.Write(sourceData, addr, size); } else // Data is in target data { // Get rid of the offset addr -= sourceLength; // Can we just ignore overlap issues? if (addr + size < targetDataStream.Position) { targetDataStream.Write(targetData, addr, size); } else { for (int j = 0; j < size; j++) { targetDataStream.WriteByte(targetData[addr++]); } } } break; case InstructionType.Run: byte data = addRunData[addRunDataIndex++]; for (int j = 0; j < size; j++) { targetDataStream.WriteByte(data); } break; default: throw new VcdiffFormatException("Invalid instruction type found."); } } } output.Write(targetData, 0, targetLength); if (hasAdler32Checksum) { int actualChecksum = Adler32.ComputeChecksum(1, targetData); if (actualChecksum != checksumInFile) { throw new VcdiffFormatException("Invalid checksum after decoding window"); } } return(true); }
private byte[] Hash(byte[] bytes) { byte[] hash = BitConverter.GetBytes(Adler32.Generate(bytes)); return(hash.Combine(bytes)); }
private async static Task WriteDataChunksUncompressed() { // First setup some variables we're going to use later on so we can calculate how big of byte[] we need // to store the entire PNG file in so we only keep a single copy of the data in memory. // Figure out how much image data we're going to have: // H * W * (number of bytes in an ARGB value) + H to account for the filter byte in PNG files int dataLength = _image.PixelWidth * _image.PixelHeight * 4 + _image.PixelHeight; // Variables for the number of PNG blocks and how big the last block is going to be. int blockCount; int lastBlockSize; // We could have an exactly even count of blocks (ie MaxBlockSize * x), but that seems unlikely. // If we don't, then add one for the remainder of the data and figure out how much data will be // left. if ((dataLength % MaxBlockSize) == 0) { blockCount = dataLength / MaxBlockSize; lastBlockSize = MaxBlockSize; } else { blockCount = (dataLength / MaxBlockSize) + 1; lastBlockSize = dataLength - (MaxBlockSize * (blockCount - 1)); } // The size of the PNG file will be: // 2 header bytes + // ( blockCount - 1 ) * // ( // 1 last block byte + // 2 block size bytes + // 2 block size one's complement bytes + // maxBlockSize ) + // ( // 1 last block byte + // 2 block size bytes + // 2 block size one's complement bytes + // lastBlockSize ) + // 4 Adler32 bytes + // // = 2 + ((blockCount-1)*(5+MaxBlockSize)) + (5+lastBlockSize) + 4 // = 11 + ((blockCount-1)*(5+MaxBlockSize)) + lastBlockSize // int pngLength; pngLength = 11 + ((blockCount - 1) * (5 + MaxBlockSize)) + lastBlockSize; // Make a buffer to store the PNG in. byte[] data = new byte[pngLength]; // Write zlib headers. data[0] = 0x78; data[1] = 0xDA; // zlib compression uses Adler32 CRCs instead of CRC32s, so setup on up to calculate. Adler32 crcCode = new Adler32(); crcCode.resetAdler(); // Setup some variables to use in the loop. var blockRemainder = 0; // How much of the current block we have left, 0 to start so we write the block header out on the first block. var currentBlock = 0; // The current block we're working on, start with 0 as we increment in the first pass thorugh. var dataPointer = 2; // A pointer to where we are in the data array, start at 2 as we 'wrote' two bytes a few lines ago. var pixelSource = 0; // The current pixel we're working on from the image. byte[] pixel = new byte[4]; // Temporary storage to store the current pixel in as a byte array. // This is the main logic loop, we're going to be doing a lot of work so stick with me... // The loop has three parts to it: // 1. looping through each row (y) // 2. looping through each pixel in the row (x) // 3. looping through each byte of the pixel (z) // Loop thorough each row in the image. for (int y = 0; y < _image.PixelHeight; y++) { // This code appears twice, once here and once in the pixel byte loop (loop 3). // It checks to see if we're at the boundry for the PNG block and if so writes // out a new block header. It get executed on the first time through to setup // the first block but is unlikly to get executed again as it would mean the // block boundry is at a row boundry, which seems unlikly. if (blockRemainder == 0) { // Setup a temporary byte array to store the block size in. byte[] tempBytes = new byte[2]; // Increment the current block count. currentBlock++; // Figure out the current block size and if we're at the last block, write // out and 1 to let the zlib decompressor know. By default, use the MaxBlockSize. int length = MaxBlockSize; if (currentBlock == blockCount) { length = lastBlockSize; data[dataPointer] = 0x01; } else { data[dataPointer] = 0x00; } // Each and every time we write something to the data array, increment the pointer. dataPointer++; // Write the block length out. tempBytes = BitConverter.GetBytes(length); data[dataPointer + 0] = tempBytes[0]; data[dataPointer + 1] = tempBytes[1]; dataPointer += 2; // Write one's compliment of length for error checking. tempBytes = BitConverter.GetBytes((ushort)~length); data[dataPointer + 0] = tempBytes[0]; data[dataPointer + 1] = tempBytes[1]; dataPointer += 2; // Reset the remaining block size to the next block's length. blockRemainder = length; } // Set the filter byte to 0, not really required as C# initalizes the byte array to 0 by default, but here for clarity. data[dataPointer] = 0; // Add the current byte to the running Adler32 value, note we ONLY add the filter byte and the pixel bytes to the // Adler32 CRC, all other header and block header bytes are execluded from the CRC. crcCode.addToAdler(data, 1, (UInt32)dataPointer); // Increment the data pointer and decrement the remain block value. dataPointer++; blockRemainder--; // Loop thorough each pixel in the row, you have to do this as the source format and destination format may be different. for (int x = 0; x < _image.PixelWidth; x++) { // Data is in RGBA format but source may not be //pixel = BitConverter.GetBytes(_image.Pixels[pixelSource]); var color = _image.GetPixel(pixelSource, 0); pixel = new[] { color.A, color.R, color.G, color.B }; // Loop through the 4 bytes of the pixel and 'write' them to the data array. for (int z = 0; z < 4; z++) { // This is the second appearance of this code code. // It checks to see if we're at the boundry for the PNG block and if so writes // out a new block header. if (blockRemainder == 0) { // Setup a temporary byte array to store the block size in. byte[] tempBytes = new byte[2]; // Increment the current block count. currentBlock++; // Figure out the current block size and if we're at the last block, write // out and 1 to let the zlib decompressor know. By default, use the MaxBlockSize. int length = MaxBlockSize; if (currentBlock == blockCount) { length = lastBlockSize; data[dataPointer] = 0x01; } else { data[dataPointer] = 0x00; } // Each and every time we write something to the data array, increment the pointer. dataPointer++; // Write the block length out. tempBytes = BitConverter.GetBytes(length); data[dataPointer + 0] = tempBytes[0]; data[dataPointer + 1] = tempBytes[1]; dataPointer += 2; // Write one's compliment of length for error checking. tempBytes = BitConverter.GetBytes((ushort)~length); data[dataPointer + 0] = tempBytes[0]; data[dataPointer + 1] = tempBytes[1]; dataPointer += 2; // Reset the remaining block size to the next block's length. blockRemainder = length; } // Store the pixel's byte in to the data array. We use the WBByteOrder array to ensure // we have the write order of bytes to store in the PNG file. data[dataPointer] = pixel[WBByteOrder[z]]; // Add the current byte to the running Adler32 value, note we ONLY add the filter byte and the pixel bytes to the // Adler32 CRC, all other header and block header bytes are execluded from the CRC. crcCode.addToAdler(data, 1, (UInt32)dataPointer); // Increment the data pointer and decrement the remain block value. dataPointer++; blockRemainder--; } // Increment where we start writting the next pixel and where we get the next pixel from. pixelSource++; } } // Whew, wipe that brow, we're done all the complex bits now! // Write the Adler32 CRC out, but reverse the order of the bytes to match the zlib spec. pixel = BitConverter.GetBytes(crcCode.adler()); data[dataPointer + 0] = pixel[3]; data[dataPointer + 1] = pixel[2]; data[dataPointer + 2] = pixel[1]; data[dataPointer + 3] = pixel[0]; // Yes, yes, I know I said "Each and every time we write something to the data array, increment the pointer." // but we're done with it now so I'm not going to bother ;) // Write the entire PNG data chunk out to the file stream. await WriteChunk(PngChunkTypes.Data, data, 0, pngLength); }
private void WriteDataChunksFast() { byte[] pixels = ConvertPixelArrayToByteArray(_image.Data); // Convert the pixel array to a new array for adding // the filter byte. // -------------------------------------------------- byte[] data = new byte[_image.Width * _image.Height * 4 + _image.Height]; int rowLength = _image.Width * 4 + 1; for (int y = 0; y < _image.Height; y++) { data[y * rowLength] = 0; Array.Copy(pixels, y * _image.Width * 4, data, y * rowLength + 1, _image.Width * 4); } // -------------------------------------------------- Adler32 adler32 = new Adler32(); adler32.Update(data); using (MemoryStream tempStream = new MemoryStream()) { int remainder = data.Length; int blockCount; if ((data.Length % MaxBlockSize) == 0) { blockCount = data.Length / MaxBlockSize; } else { blockCount = (data.Length / MaxBlockSize) + 1; } // Write headers tempStream.WriteByte(0x78); tempStream.WriteByte(0xDA); for (int i = 0; i < blockCount; i++) { // Write the length ushort length = (ushort)((remainder < MaxBlockSize) ? remainder : MaxBlockSize); if (length == remainder) { tempStream.WriteByte(0x01); } else { tempStream.WriteByte(0x00); } tempStream.Write(BitConverter.GetBytes(length), 0, 2); // Write one's compliment of length tempStream.Write(BitConverter.GetBytes((ushort)~length), 0, 2); // Write blocks tempStream.Write(data, (int)(i * MaxBlockSize), length); // Next block remainder -= MaxBlockSize; } WriteInteger(tempStream, (int)adler32.Value); tempStream.Seek(0, SeekOrigin.Begin); byte[] zipData = new byte[tempStream.Length]; tempStream.Read(zipData, 0, (int)tempStream.Length); WriteChunk(PngChunkTypes.Data, zipData); } }
public File4Flickr PrepareCrc() { _crc = !string.IsNullOrEmpty(FullName) ? Adler32.FileChecksum(FullName, NumberOfBytesForCRC) : 0; return(this); }
protected override void OnReceived(byte[] body) { ByteArrayArrayStream stream = new ByteArrayArrayStream(body); ByteArrayStreamReader reader = new ByteArrayStreamReader(stream); try { if (Adler32.Generate(body, 4) == reader.ReadUInt()) { if (Keys == null) { Rsa.DecryptAndReplace(body, 9); } else { Xtea.DecryptAndReplace(body, 4, 32, Keys); stream.Seek(Origin.Current, 2); } Command command = null; switch (reader.ReadByte()) { case 0x0A: { var packet = server.PacketsFactory.Create <SelectedCharacterIncomingPacket>(reader); command = new LogInCommand(this, packet); } break; case 0x14: command = new LogOutCommand(Client.Player); break; case 0x1E: command = new PongCommand(Client.Player); break; case 0x64: { var packet = server.PacketsFactory.Create <WalkToIncomingPacket>(reader); command = new WalkToKnownPathCommand(Client.Player, packet.MoveDirections); } break; case 0x65: command = new WalkCommand(Client.Player, MoveDirection.North); break; case 0x66: command = new WalkCommand(Client.Player, MoveDirection.East); break; case 0x67: command = new WalkCommand(Client.Player, MoveDirection.South); break; case 0x68: command = new WalkCommand(Client.Player, MoveDirection.West); break; case 0x69: command = new StopWalkCommand(Client.Player); break; case 0x6A: command = new WalkCommand(Client.Player, MoveDirection.NorthEast); break; case 0x6B: command = new WalkCommand(Client.Player, MoveDirection.SouthEast); break; case 0x6C: command = new WalkCommand(Client.Player, MoveDirection.SouthWest); break; case 0x6D: command = new WalkCommand(Client.Player, MoveDirection.NorthWest); break; case 0x6F: command = new TurnCommand(Client.Player, Direction.North); break; case 0x70: command = new TurnCommand(Client.Player, Direction.East); break; case 0x71: command = new TurnCommand(Client.Player, Direction.South); break; case 0x72: command = new TurnCommand(Client.Player, Direction.West); break; case 0x78: { var packet = server.PacketsFactory.Create <MoveItemIncomingPacket>(reader); Position fromPosition = new Position(packet.FromX, packet.FromY, packet.FromZ); Position toPosition = new Position(packet.ToX, packet.ToY, packet.ToZ); if (fromPosition.IsContainer) { if (toPosition.IsContainer) { command = new MoveItemFromContainerToContainerCommand(Client.Player, fromPosition.ContainerId, fromPosition.ContainerIndex, packet.FromItemId, toPosition.ContainerId, toPosition.ContainerIndex, packet.Count); } else if (toPosition.IsInventory) { command = new MoveItemFromContainerToInventoryCommand(Client.Player, fromPosition.ContainerId, fromPosition.ContainerIndex, packet.FromItemId, toPosition.InventoryIndex, packet.Count); } else { command = new MoveItemFromContainerToTileCommand(Client.Player, fromPosition.ContainerId, fromPosition.ContainerIndex, packet.FromItemId, toPosition, packet.Count); } } else if (fromPosition.IsInventory) { if (toPosition.IsContainer) { command = new MoveItemFromInventoryToContainerCommand(Client.Player, fromPosition.InventoryIndex, packet.FromItemId, toPosition.ContainerId, toPosition.ContainerIndex, packet.Count); } else if (toPosition.IsInventory) { command = new MoveItemFromInventoryToInventoryCommand(Client.Player, fromPosition.InventoryIndex, packet.FromItemId, toPosition.InventoryIndex, packet.Count); } else { command = new MoveItemFromInventoryToTileCommand(Client.Player, fromPosition.InventoryIndex, packet.FromItemId, toPosition, packet.Count); } } else { if (toPosition.IsContainer) { command = new MoveItemFromTileToContainerCommand(Client.Player, fromPosition, packet.FromIndex, packet.FromItemId, toPosition.ContainerId, toPosition.ContainerIndex, packet.Count); } else if (toPosition.IsInventory) { command = new MoveItemFromTileToInventoryCommand(Client.Player, fromPosition, packet.FromIndex, packet.FromItemId, toPosition.InventoryIndex, packet.Count); } else { command = new MoveItemFromTileToTileCommand(Client.Player, fromPosition, packet.FromIndex, packet.FromItemId, toPosition, packet.Count); } } } break; case 0x79: { var packet = server.PacketsFactory.Create <LookItemNpcTradeIncommingPacket>(reader); command = new LookFromNpcTradeCommand(Client.Player, packet.ItemId, packet.Type); } break; case 0x7A: { var packet = server.PacketsFactory.Create <BuyNpcTradeIncommingPacket>(reader); command = new BuyNpcTradeCommand(Client.Player, packet); } break; case 0x7B: { var packet = server.PacketsFactory.Create <SellNpcTradeIncommingPacket>(reader); command = new SellNpcTradeCommand(Client.Player, packet); } break; case 0x7C: command = new CloseNpcTradeCommand(Client.Player); break; case 0x7D: { var packet = server.PacketsFactory.Create <TradeWithIncommingPacket>(reader); Position fromPosition = new Position(packet.X, packet.Y, packet.Z); if (fromPosition.IsContainer) { command = new TradeWithFromContainerCommand(Client.Player, fromPosition.ContainerId, fromPosition.ContainerIndex, packet.ItemId, packet.CreatureId); } else if (fromPosition.IsInventory) { command = new TradeWithFromInventoryCommand(Client.Player, fromPosition.InventoryIndex, packet.ItemId, packet.CreatureId); } else { command = new TradeWithFromTileCommand(Client.Player, fromPosition, packet.Index, packet.ItemId, packet.CreatureId); } } break; case 0x7E: { var packet = server.PacketsFactory.Create <LookItemTradeIncommingPacket>(reader); command = new LookFromTradeCommand(Client.Player, packet.WindowId, packet.Index); } break; case 0x7F: command = new AcceptTradeCommand(Client.Player); break; case 0x80: command = new CancelTradeCommand(Client.Player); break; case 0x82: { var packet = server.PacketsFactory.Create <UseItemIncomingPacket>(reader); Position fromPosition = new Position(packet.X, packet.Y, packet.Z); if (fromPosition.IsContainer) { command = new UseItemFromContainerCommand(Client.Player, fromPosition.ContainerId, fromPosition.ContainerIndex, packet.ItemId, packet.ContainerId); } else if (fromPosition.IsInventory) { command = new UseItemFromInventoryCommand(Client.Player, fromPosition.InventoryIndex, packet.ItemId); } else { command = new UseItemFromTileCommand(Client.Player, fromPosition, packet.Index, packet.ItemId); } } break; case 0x83: { var packet = server.PacketsFactory.Create <UseItemWithItemIncomingPacket>(reader); Position fromPosition = new Position(packet.FromX, packet.FromY, packet.FromZ); Position toPosition = new Position(packet.ToX, packet.ToY, packet.ToZ); if (fromPosition.IsContainer) { if (toPosition.IsContainer) { command = new UseItemWithItemFromContainerToContainerCommand(Client.Player, fromPosition.ContainerId, fromPosition.ContainerIndex, packet.FromItemId, toPosition.ContainerId, toPosition.ContainerIndex, packet.ToItemId); } else if (toPosition.IsInventory) { command = new UseItemWithItemFromContainerToInventoryCommand(Client.Player, fromPosition.ContainerId, fromPosition.ContainerIndex, packet.FromItemId, toPosition.InventoryIndex, packet.ToItemId); } else { command = new UseItemWithItemFromContainerToTileCommand(Client.Player, fromPosition.ContainerId, fromPosition.ContainerIndex, packet.FromItemId, toPosition, packet.ToIndex, packet.ToItemId); } } else if (fromPosition.IsInventory) { if (toPosition.IsContainer) { command = new UseItemWithItemFromInventoryToContainerCommand(Client.Player, fromPosition.InventoryIndex, packet.FromItemId, toPosition.ContainerId, toPosition.ContainerIndex, packet.ToItemId); } else if (toPosition.IsInventory) { command = new UseItemWithItemFromInventoryToInventoryCommand(Client.Player, fromPosition.InventoryIndex, packet.FromItemId, toPosition.InventoryIndex, packet.ToItemId); } else { command = new UseItemWithItemFromInventoryToTileCommand(Client.Player, fromPosition.InventoryIndex, packet.FromItemId, toPosition, packet.ToIndex, packet.ToItemId); } } else { if (toPosition.IsContainer) { command = new UseItemWithItemFromTileToContainerCommand(Client.Player, fromPosition, packet.FromIndex, packet.FromItemId, toPosition.ContainerId, toPosition.ContainerIndex, packet.ToItemId); } else if (toPosition.IsInventory) { command = new UseItemWithItemFromTileToInventoryCommand(Client.Player, fromPosition, packet.FromIndex, packet.FromItemId, toPosition.InventoryIndex, packet.ToItemId); } else { command = new UseItemWithItemFromTileToTileCommand(Client.Player, fromPosition, packet.FromIndex, packet.FromItemId, toPosition, packet.ToIndex, packet.ToItemId); } } } break; case 0x84: { var packet = server.PacketsFactory.Create <UseItemWithCreatureIncomingPacket>(reader); Position fromPosition = new Position(packet.X, packet.Y, packet.Z); if (fromPosition.IsContainer) { command = new UseItemWithCreatureFromContainerCommand(Client.Player, fromPosition.ContainerId, fromPosition.ContainerIndex, packet.ItemId, packet.CreatureId); } else if (fromPosition.IsInventory) { command = new UseItemWithCreatureFromInventoryCommand(Client.Player, fromPosition.InventoryIndex, packet.ItemId, packet.CreatureId); } else { command = new UseItemWithCreatureFromTileCommand(Client.Player, fromPosition, packet.Index, packet.ItemId, packet.CreatureId); } } break; case 0x85: { var packet = server.PacketsFactory.Create <RotateItemIncomingPacket>(reader); var fromPosition = new Position(packet.X, packet.Y, packet.Z); if (fromPosition.IsContainer) { command = new RotateItemFromContainerCommand(Client.Player, fromPosition.ContainerId, fromPosition.ContainerIndex, packet.ItemId); } else if (fromPosition.IsInventory) { command = new RotateItemFromInventoryCommand(Client.Player, fromPosition.InventoryIndex, packet.ItemId); } else { command = new RotateItemFromTileCommand(Client.Player, fromPosition, packet.Index, packet.ItemId); } } break; case 0x87: { var packet = server.PacketsFactory.Create <CloseContainerIncommingPacket>(reader); command = new CloseContainerCommand(Client.Player, packet.ContainerId); } break; case 0x88: { var packet = server.PacketsFactory.Create <OpenParentIncommingPacket>(reader); command = new OpenParentContainerCommand(Client.Player, packet.ContainerId); } break; case 0x8C: { var packet = server.PacketsFactory.Create <LookIncomingPacket>(reader); var fromPosition = new Position(packet.X, packet.Y, packet.Z); if (fromPosition.IsContainer) { command = new LookFromContainerCommand(Client.Player, fromPosition.ContainerId, fromPosition.ContainerIndex, packet.ItemId); } else if (fromPosition.IsInventory) { command = new LookFromInventoryCommand(Client.Player, fromPosition.InventoryIndex, packet.ItemId); } else { command = new LookFromTileCommand(Client.Player, fromPosition, packet.Index, packet.ItemId); } } break; case 0x96: { var packet = server.PacketsFactory.Create <TalkIncommingPacket>(reader); switch (packet.TalkType) { case TalkType.Say: command = new SayCommand(Client.Player, packet.Message); break; case TalkType.Whisper: command = new WhisperCommand(Client.Player, packet.Message); break; case TalkType.Yell: command = new YellCommand(Client.Player, packet.Message); break; case TalkType.Private: command = new SendMessageToPlayerCommand(Client.Player, packet.Name, packet.Message); break; case TalkType.ChannelYellow: command = new SendMessageToChannel(Client.Player, packet.ChannelId, packet.Message); break; case TalkType.ReportRuleViolationOpen: command = new CreateReportRuleViolationCommand(Client.Player, packet.Message); break; case TalkType.ReportRuleViolationAnswer: command = new AnswerInReportRuleViolationChannelCommand(Client.Player, packet.Name, packet.Message); break; case TalkType.ReportRuleViolationQuestion: command = new AskInReportRuleViolationChannelCommand(Client.Player, packet.Message); break; case TalkType.Broadcast: command = new BroadcastMessageCommand(Client.Player, packet.Message); break; } } break; case 0x97: command = new OpenNewChannelCommand(Client.Player); break; case 0x98: { var packet = server.PacketsFactory.Create <OpenedNewChannelIncomingPacket>(reader); command = new OpenedNewChannelCommand(Client.Player, packet.ChannelId); } break; case 0x99: { var packet = server.PacketsFactory.Create <CloseChannelIncommingPacket>(reader); command = new CloseChannelCommand(Client.Player, packet.ChannelId); } break; case 0x9A: { var packet = server.PacketsFactory.Create <OpenedPrivateChannelIncomingPacket>(reader); command = new OpenedPrivateChannelCommand(Client.Player, packet.Name); } break; case 0x9B: { var packet = server.PacketsFactory.Create <ProcessReportRuleViolationIncommingPacket>(reader); command = new ProcessReportRuleViolationCommand(Client.Player, packet.Name); } break; case 0x9C: { var packet = server.PacketsFactory.Create <CloseReportRuleViolationChannelAnswerIncommingPacket>(reader); command = new CloseReportRuleViolationChannelAnswerCommand(Client.Player, packet.Name); } break; case 0x9D: command = new CloseReportRuleViolationChannelQuestionCommand(Client.Player); break; case 0x9E: command = new CloseNpcsChannelCommand(Client.Player); break; case 0xA0: { var packet = server.PacketsFactory.Create <CombatControlsIncommingPacket>(reader); command = new CombatControlsCommand(Client.Player, packet.FightMode, packet.ChaseMode, packet.SafeMode); } break; case 0xA1: { var packet = server.PacketsFactory.Create <AttackIncommingPacket>(reader); if (packet.CreatureId == 0) { command = new StopAttackCommand(Client.Player); } else { command = new StartAttackCommand(Client.Player, packet.CreatureId, packet.Nonce); } } break; case 0xA2: { var packet = server.PacketsFactory.Create <FollowIncommingPacket>(reader); if (packet.CreatureId == 0) { command = new StopFollowCommand(Client.Player); } else { command = new StartFollowCommand(Client.Player, packet.CreatureId, packet.Nonce); } } break; case 0xA3: { var packet = server.PacketsFactory.Create <InviteToPartyIncomingPacket>(reader); command = new InviteToPartyCommand(Client.Player, packet.CreatureId); } break; case 0xA4: { var packet = server.PacketsFactory.Create <JoinPartyIncomingPacket>(reader); command = new JoinPartyCommand(Client.Player, packet.CreatureId); } break; case 0xA5: { var packet = server.PacketsFactory.Create <RevokePartyIncomingPacket>(reader); command = new RevokePartyCommand(Client.Player, packet.CreatureId); } break; case 0xA6: { var packet = server.PacketsFactory.Create <PassLeadershipToIncomingPacket>(reader); command = new PassLeaderShipToCommand(Client.Player, packet.CreatureId); } break; case 0xA7: command = new LeavePartyCommand(Client.Player); break; case 0xA8: { var packet = server.PacketsFactory.Create <SharedExperienceIncomingPacket>(reader); command = new SharedExperienceCommand(Client.Player, packet.Enabled); } break; case 0xAA: command = new OpenedMyPrivateChannelCommand(Client.Player); break; case 0xAB: { var packet = server.PacketsFactory.Create <InvitePlayerIncommingPacket>(reader); command = new InvitePlayerCommand(Client.Player, packet.Name); } break; case 0xAC: { var packet = server.PacketsFactory.Create <ExcludePlayerIncommingPacket>(reader); command = new ExcludePlayerCommand(Client.Player, packet.Name); } break; case 0xBE: command = new StopCommand(Client.Player); break; case 0xD2: command = new SelectOutfitCommand(Client.Player); break; case 0xD3: { var packet = server.PacketsFactory.Create <SelectedOutfitIncomingPacket>(reader); command = new SelectedOutfitCommand(Client.Player, packet.Outfit); } break; case 0xDC: { var packet = server.PacketsFactory.Create <AddVipIncommingPacket>(reader); command = new AddVipCommand(Client.Player, packet.Name); } break; case 0xDD: { var packet = server.PacketsFactory.Create <RemoveVipIncommingPacket>(reader); command = new RemoveVipCommand(Client.Player, packet.CreatureId); } break; case 0xE6: { var packet = server.PacketsFactory.Create <ReportBugIncomingPacket>(reader); command = new ReportBugCommand(Client.Player, packet.Message); } break; case 0xF0: command = new OpenQuestsCommand(Client.Player); break; case 0xF1: { var packet = server.PacketsFactory.Create <OpenQuestIncomingPacket>(reader); command = new OpenQuestCommand(Client.Player, packet.QuestId); } break; } if (command != null) { server.QueueForExecution(command); } } } catch (Exception ex) { server.Logger.WriteLine(ex.ToString()); } base.OnReceived(body); }
public void TestHashUpdate() { const int N = 1_000_000; var random = new Random(42); var data = new byte[N]; random.NextBytes(data); // CRC-32 var crc32 = new Crc32(); for (var n = 0; n < 1000; n++) { var span = data.AsSpan(0, n); var h = BitConverter.ToUInt32(crc32.GetHash(span)); var h2 = Crc32.Hash32(span); Assert.Equal(h, h2); } this.TestHashUpdate_do(crc32, data, random); // Adler-32 var adler32 = new Adler32(); for (var n = 0; n < 1000; n++) { var span = data.AsSpan(0, n); var h = BitConverter.ToUInt32(adler32.GetHash(span)); var h2 = Adler32.Hash32(span); Assert.Equal(h, h2); } this.TestHashUpdate_do(adler32, data, random); // FarmHash var farm = new FarmHash(); for (var n = 0; n < 1000; n++) { var span = data.AsSpan(0, n); var h = BitConverter.ToUInt64(farm.GetHash(span)); var h2 = FarmHash.Hash64(span); Assert.Equal(h, h2); } this.TestHashUpdate_do(farm, data, random); // xxHash32 var xxh32 = new XXHash32(); for (var n = 0; n < 1000; n++) { var span = data.AsSpan(0, n); var h = BitConverter.ToUInt32(xxh32.GetHash(span)); var h2 = XXHash32.Hash32(span); Assert.Equal(h, h2); } this.TestHashUpdate_do(xxh32, data, random); // xxHash64 var xxh64 = new XxHash64(); for (var n = 0; n < 1000; n++) { var span = data.AsSpan(0, n); var h = BitConverter.ToUInt64(xxh64.GetHash(span)); var h2 = XxHash64.Hash64(span); Assert.Equal(h, h2); } this.TestHashUpdate_do(xxh64, data, random); // Sha1 using var sha1 = new Arc.Crypto.Sha1(); this.TestHashUpdate_do(sha1, data, random); // Sha2_256 using var sha2_256 = new Arc.Crypto.Sha2_256(); this.TestHashUpdate_do(sha2_256, data, random); // Sha2_384 using var sha2_384 = new Arc.Crypto.Sha2_384(); this.TestHashUpdate_do(sha2_384, data, random); // Sha2_512 using var sha2_512 = new Arc.Crypto.Sha2_512(); this.TestHashUpdate_do(sha2_512, data, random); // Sha3_256 var sha3_256 = new Arc.Crypto.Sha3_256(); this.TestHashUpdate_do(sha3_256, data, random); // Sha3_384 var sha3_384 = new Arc.Crypto.Sha3_384(); this.TestHashUpdate_do(sha3_384, data, random); // Sha3_512 var sha3_512 = new Arc.Crypto.Sha3_512(); this.TestHashUpdate_do(sha3_512, data, random); }
public void Adler32_4() { Aver.AreEqual(UInt32.Parse("36E81466", System.Globalization.NumberStyles.HexNumber), Adler32.ForString("This is an example of a much longer string of characters")); }
public void Adler32_5() { Aver.AreEqual(UInt32.Parse("11E60398", System.Globalization.NumberStyles.HexNumber), Adler32.ForString("Wikipedia")); }
public void Adler32_3() { Aver.AreEqual(UInt32.Parse("1BE9043A", System.Globalization.NumberStyles.HexNumber), Adler32.ForString("Hello Dolly!")); }
public void Adler32_1() { Aver.AreEqual(UInt32.Parse("1BE9043A", System.Globalization.NumberStyles.HexNumber), Adler32.ForEncodedString("Hello Dolly!", System.Text.Encoding.ASCII)); }
public void Adler32_2() { Assert.AreEqual(UInt32.Parse("36E81466", System.Globalization.NumberStyles.HexNumber), Adler32.ForEncodedString("This is an example of a much longer string of characters", System.Text.Encoding.ASCII)); }
public static int adler32([BytesLike] IList <byte> data, long baseValue = 1L) { return((int)Adler32.GetAdler32Checksum(baseValue, data.ToArray(), 0, data.Count)); }
public uint SixLaborsCalculate() { return(Adler32.Calculate(this.data)); }
static int Main(string[] args) { return(Parser.Default.ParseArguments <UnpackOptions, ShowOptions, PackOptions>(args) .MapResult( (UnpackOptions opts) => { if (opts.extractTarOnly) { using (var inflater = GetTarInflaterInputStream(File.OpenRead(opts.file))) { using (var tar = File.Create(Path.Combine(opts.directory, "backup.abh.tar"))) { inflater.CopyTo(tar); } } } else { using (var tarStream = GetTarInputStream(File.OpenRead(opts.file))) { ExtractTarByEntry(tarStream, opts.directory); } // tarArchive.ExtractContents(opts.directory); } return 0; }, (ShowOptions opts) => { using (var tarStream = GetTarInputStream(File.OpenRead(opts.file))) { TarEntry tarEntry; while ((tarEntry = tarStream.GetNextEntry()) != null) { var entryStr = tarEntry.IsDirectory ? " [D] " : " [F] "; entryStr += $"{tarEntry.Name} {tarEntry.Size:n0} bytes"; Console.WriteLine(entryStr); } } return 0; }, (PackOptions opts) => { var tarname = $"{opts.file}.tar"; using (var tar = File.Create(tarname)) { AddAppsToTar(tar, opts.apps_dir, !opts.disableConventions); } using (var outAB = File.OpenWrite(opts.file)) { outputAndroidBackupHeader(outAB); outAB.WriteByte(0x78); outAB.WriteByte(0xDA); var chksum = new Adler32(); using (var fTar = File.OpenRead(tarname)) { using (var br = new BinaryReader(fTar, Encoding.UTF8, true)) { var BUFLEN = 4096; while (true) { var buf = br.ReadBytes(BUFLEN); if (buf.Length <= 0) { break; } chksum.Update(buf); } } fTar.Seek(0, SeekOrigin.Begin); using (var defOut = new DeflateStream(outAB, CompressionMode.Compress, true)) { fTar.CopyTo(defOut); } } outAB.Write(BitConverter.GetBytes((uint)chksum.Value), 0, 4); } return 0; }, errs => 1)); }
public static int adler32([BytesConversion] IList <byte> data, [DefaultParameterValue(1L)] long baseValue) { return((int)Adler32.GetAdler32Checksum(baseValue, data.ToArray(), 0, data.Count())); }
internal void InitCrctest() { this.crctest = new Adler32(); }
public void ReturnsCorrectWhenEmpty(uint input) { Assert.Equal(input, Adler32.Calculate(input, default)); }
public static byte[] GenerateChecksum(string checksum, int offset, byte[] buffer, int eof = -1) { byte[] returnValue = null; switch (checksum) { case "Adler8 - {1Bytes}": returnValue = eof == -1 ? Adler8.Compute(offset, buffer) : Adler8.Compute(offset, buffer, eof); break; case "Adler16 - {2Bytes}": returnValue = eof == -1 ? Adler16.Compute(offset, buffer) : Adler16.Compute(offset, buffer, eof); break; case "Adler32 - {4Bytes}": returnValue = eof == -1 ? Adler32.Compute(offset, buffer) : Adler32.Compute(offset, buffer, eof); break; case "Checksum8 - {1Bytes}": returnValue = eof == -1 ? Checksum8.Compute(offset, buffer) : Checksum8.Compute(offset, buffer, eof); break; case "Checksum16 - {2Bytes}": returnValue = eof == -1 ? Checksum16.Compute(offset, buffer) : Checksum16.Compute(offset, buffer, eof); break; case "Checksum24 - {3Bytes}": returnValue = eof == -1 ? Checksum24.Compute(offset, buffer) : Checksum24.Compute(offset, buffer, eof); break; case "Checksum32 - {4Bytes}": returnValue = eof == -1 ? Checksum32.Compute(offset, buffer) : Checksum32.Compute(offset, buffer, eof); break; case "Checksum40 - {5Bytes}": returnValue = eof == -1 ? Checksum40.Compute(offset, buffer) : Checksum40.Compute(offset, buffer, eof); break; case "Checksum48 - {6Bytes}": returnValue = eof == -1 ? Checksum48.Compute(offset, buffer) : Checksum48.Compute(offset, buffer, eof); break; case "Checksum56 - {7Bytes}": returnValue = eof == -1 ? Checksum56.Compute(offset, buffer) : Checksum56.Compute(offset, buffer, eof); break; case "Checksum64 - {8Bytes}": returnValue = eof == -1 ? Checksum64.Compute(offset, buffer) : Checksum64.Compute(offset, buffer, eof); break; case "CRC16 - {2Bytes}": Crc16 crc16 = new Crc16(); returnValue = eof == -1 ? crc16.Compute(offset, buffer) : crc16.Compute(offset, buffer, eof); break; case "CRC16 CCITT - {2Bytes}": Crc16ccitt crc16Ccitt = new Crc16ccitt(); returnValue = eof == -1 ? crc16Ccitt.Compute(offset, buffer) : crc16Ccitt.Compute(offset, buffer, eof); break; case "CRC32 - {4Bytes}": returnValue = eof == -1 ? Crc32.Compute(offset, buffer) : Crc32.Compute(offset, buffer, eof); break; case "HMAC SHA 1 (128) - {16Bytes}": returnValue = eof == -1 ? HmacSha1.Compute(offset, buffer) : HmacSha1.Compute(offset, buffer, eof); break; case "HMAC SHA 256 - {32Bytes}": returnValue = eof == -1 ? HmacSha256.Compute(offset, buffer) : HmacSha256.Compute(offset, buffer, eof); break; case "HMAC SHA 384 - {48Bytes}": returnValue = eof == -1 ? HmacSha384.Compute(offset, buffer) : HmacSha384.Compute(offset, buffer, eof); break; case "HMAC SHA 512 - {64Bytes}": returnValue = eof == -1 ? HmacSha512.Compute(offset, buffer) : HmacSha512.Compute(offset, buffer, eof); break; case "MD5 - {16Bytes}": returnValue = eof == -1 ? Md5.Compute(offset, buffer) : Md5.Compute(offset, buffer, eof); break; case "MD5 CNG - {16Bytes}": returnValue = eof == -1 ? Md5Cng.Compute(offset, buffer) : Md5Cng.Compute(offset, buffer, eof); break; } return(returnValue); }
/// <summary> /// Write Bytes Routine /// </summary> /// <param name="buffer">The buffer.</param> /// <param name="pos">The position.</param> /// <param name="len">The length.</param> protected override void WriteBytes(byte[] buffer, int pos, int len) { _writeAdler32 = Adler32.Checksum(_writeAdler32, buffer, pos, len); _writeFile.Write(buffer, pos, len); }
public static V6Packet DecodeV6(byte[] v6HeaderBins, byte[] v6BodyBins, byte[] crcBins, byte[] bodyKey, MIMCUser user) { byte[] v6Bins = new byte[v6HeaderBins.Length + v6BodyBins.Length + crcBins.Length]; //logger.DebugFormat("decodeV6 ============== v6BodyBins.Length:{0}", v6BodyBins.Length); v6HeaderBins.CopyTo(v6Bins, 0); v6BodyBins.CopyTo(v6Bins, v6HeaderBins.Length); crcBins.CopyTo(v6Bins, v6HeaderBins.Length + v6BodyBins.Length); //logger.DebugFormat("decodeV6 ============== data v6HeaderBins :{0}", BitConverter.ToString(v6HeaderBins)); //logger.DebugFormat("decodeV6 ============== data v6BodyBins:{0}", BitConverter.ToString(v6BodyBins)); //logger.DebugFormat("decodeV6 ============== data crcBins:{0}", BitConverter.ToString(crcBins)); //logger.DebugFormat("decodeV6 ============== data v6Bins:{0}", BitConverter.ToString(v6Bins)); uint fecrc = GetUint(crcBins, 0); uint crc = Adler32.checkCRC(v6Bins, 0, v6Bins.Length - 4); if (fecrc != crc) { logger.WarnFormat("decodeV6, INVALID_CRC, {0}!={1}", fecrc, crc); return(null); } V6Packet v6Packet = new V6Packet(); v6Packet.Magic = V6PacketDecoder.GetChar(v6HeaderBins, 0); v6Packet.Version = V6PacketDecoder.GetChar(v6HeaderBins, 2); v6Packet.PacketLen = (int)V6PacketDecoder.GetUint(v6HeaderBins, 4); if (v6Packet.PacketLen == 0) { return(v6Packet); } if (bodyKey != null && bodyKey.Length > 0 && v6BodyBins != null && v6BodyBins.Length > 0) { v6BodyBins = RC4Cryption.DoEncrypt(bodyKey, v6BodyBins); } v6Packet.PacketLen = v6BodyBins == null ? 0 : v6BodyBins.Length; short payloadType = GetShort(v6BodyBins, 0); short clientHeaderLen = GetShort(v6BodyBins, 2); uint v6PayloadLen = GetUint(v6BodyBins, 4); if (payloadType != Constant.PAYLOAD_TYPE || clientHeaderLen < 0 || v6PayloadLen < 0) { logger.WarnFormat("decodeV6, INVALID_HEADER, payloadType:{0}, clientHeaderLen:{1}, v6PayloadLen:{2}", payloadType, clientHeaderLen, v6PayloadLen); return(null); } byte[] clientHeaderBins = new byte[clientHeaderLen]; Array.Copy(v6BodyBins, Constant.V6_BODY_HEADER_LENGTH, clientHeaderBins, 0, clientHeaderLen); byte[] v6PayloadBins = new byte[v6PayloadLen]; Array.Copy(v6BodyBins, Constant.V6_BODY_HEADER_LENGTH + clientHeaderLen, v6PayloadBins, 0, v6PayloadLen); ClientHeader clientHeader = null; using (MemoryStream ms = new MemoryStream(clientHeaderBins)) { clientHeader = Serializer.Deserialize <ClientHeader>(ms); } //logger.InfoFormat("receive v6 packet cmd:{0}, user:{1}", clientHeader.cmd, user.AppAccount()); if (Constant.CMD_SECMSG == clientHeader.cmd) { byte[] payloadKey = RC4Cryption.GenerateKeyForRC4(user.SecurityKey, clientHeader.id); v6PayloadBins = RC4Cryption.DoEncrypt(payloadKey, v6PayloadBins); } v6Packet.V6BodyBin = v6BodyBins; V6Packet.V6Body v6Body = new V6Packet.V6Body(); v6Body.PayloadType = payloadType; v6Body.ClientHeaderLen = clientHeaderLen; v6Body.PayloadLen = (int)v6PayloadLen; v6Body.ClientHeader = clientHeader; v6Body.Payload = v6PayloadBins; v6Packet.Body = v6Body; return(v6Packet); }
/// <summary>Calculates the Adler32 check-sum on specified portion of a buffer.</summary> /// <param name="data">Data buffer to perform check-sum on.</param> /// <param name="startIndex">Starts index in data buffer to begin check-sum.</param> /// <param name="length">Total number of bytes from <paramref name="startIndex">startIndex</paramref> to /// perform check-sum over.</param> /// <remarks> /// <para> /// Computes Adler32 checksum for a stream of data. An Adler32 checksum is not as reliable as a CRC32 /// checksum, but a lot faster to compute. /// </para> /// <para> /// The specification for Adler32 may be found in RFC 1950. ZLIB Compressed Data Format Specification /// version 3.3. /// </para> /// </remarks> /// <returns>Computed Adler32 checksum over the specified portion of the buffer.</returns> public static uint Adler32Checksum(this byte[] data, int startIndex, int length) { Adler32 checksum = new Adler32(); checksum.Update(data, startIndex, length); return checksum.Value; }
/// <summary> /// Creates a new inflater. /// </summary> /// <param name="noHeader"> /// True if no RFC1950/Zlib header and footer fields are expected in the input data /// /// This is used for GZIPed/Zipped input. /// /// For compatibility with /// Sun JDK you should provide one byte of input more than needed in /// this case. /// </param> public Inflater(bool noHeader) { this.noHeader = noHeader; this.adler = new Adler32(); input = new StreamManipulator(); outputWindow = new OutputWindow(); mode = noHeader ? DECODE_BLOCKS : DECODE_HEADER; }
/// <summary> /// Construct instance with pending buffer /// </summary> /// <param name="pending"> /// Pending buffer to use /// </param>> public DeflaterEngine(DeflaterPending pending) { this.pending = pending; huffman = new DeflaterHuffman(pending); adler = new Adler32(); window = new byte[2 * WSIZE]; head = new short[HASH_SIZE]; prev = new short[WSIZE]; // We start at index 1, to avoid an implementation deficiency, that // we cannot build a repeat pattern at index 0. blockStart = strstart = 1; }
public void MixedUpdateTest() { Adler32 checksum = new Adler32(); int i = 0; checksum.Reset(); while (i < LicenseData.Length / 4) checksum.Update(LicenseData[i++]); for (int j = 0; j < 2; j++) { checksum.Update(LicenseData, i, LicenseData.Length / 4); i += LicenseData.Length / 4; } while (i < LicenseData.Length) checksum.Update(LicenseData[i++]); Assert.AreEqual(LicenseChecksum, checksum.Value); }
public void UpdateByteTest() { Adler32 checksum = new Adler32(); foreach (byte d in LicenseData) checksum.Update(d); Assert.AreEqual(LicenseChecksum, checksum.Value); }
private void WriteDataChunksUncompressed() { // First setup some variables we're going to use later on so we can calculate how big of byte[] we need // to store the entire PNG file in so we only keep a single copy of the data in memory. // Figure out how much image data we're going to have: // H * W * (number of bytes in an ARGB value) + H to account for the filter byte in PNG files int dataLength = _bitmap.PixelWidth * _bitmap.PixelHeight * 4 + _bitmap.PixelHeight; // Variables for the number of PNG blocks and how big the last block is going to be. int blockCount; int lastBlockSize; // We could have an exactly even count of blocks (ie MaxBlockSize * x), but that seems unlikely. // If we don't, then add one for the remainder of the data and figure out how much data will be // left. if ( ( dataLength % MaxBlockSize ) == 0 ) { blockCount = dataLength / MaxBlockSize; lastBlockSize = MaxBlockSize; } else { blockCount = ( dataLength / MaxBlockSize ) + 1; lastBlockSize = dataLength - ( MaxBlockSize * ( blockCount - 1 ) ); } // The size of the PNG file will be: // 2 header bytes + // ( blockCount - 1 ) * // ( // 1 last block byte + // 2 block size bytes + // 2 block size one's complement bytes + // maxBlockSize ) + // ( // 1 last block byte + // 2 block size bytes + // 2 block size one's complement bytes + // lastBlockSize ) + // 4 Adler32 bytes + // // = 2 + ((blockCount-1)*(5+MaxBlockSize)) + (5+lastBlockSize) + 4 // = 11 + ((blockCount-1)*(5+MaxBlockSize)) + lastBlockSize // int pngLength; pngLength = 11 + ( ( blockCount - 1 ) * ( 5 + MaxBlockSize ) ) + lastBlockSize; // Make a buffer to store the PNG in. byte[] data = new byte[pngLength]; // Write zlib headers. data[0] = 0x78; data[1] = 0xDA; // zlib compression uses Adler32 CRCs instead of CRC32s, so setup on up to calculate. Adler32 crcCode = new Adler32(); crcCode.Reset(); // Setup some variables to use in the loop. var blockRemainder = 0; // How much of the current block we have left, 0 to start so we write the block header out on the first block. var currentBlock = 0; // The current block we're working on, start with 0 as we increment in the first pass thorugh. var dataPointer = 2; // A pointer to where we are in the data array, start at 2 as we 'wrote' two bytes a few lines ago. var pixelSource = 0; // The current pixel we're working on from the image. byte[] pixel = new byte[4]; // Temporary storage to store the current pixel in as a byte array. // This is the main logic loop, we're going to be doing a lot of work so stick with me... // The loop has three parts to it: // 1. looping through each row (y) // 2. looping through each pixel in the row (x) // 3. looping through each byte of the pixel (z) // Loop thorough each row in the image. for ( int y = 0; y < _bitmap.PixelHeight; y++ ) { // This code appears twice, once here and once in the pixel byte loop (loop 3). // It checks to see if we're at the boundry for the PNG block and if so writes // out a new block header. It get executed on the first time through to setup // the first block but is unlikly to get executed again as it would mean the // block boundry is at a row boundry, which seems unlikly. if ( blockRemainder == 0 ) { // Setup a temporary byte array to store the block size in. byte[] tempBytes = new byte[2]; // Increment the current block count. currentBlock++; // Figure out the current block size and if we're at the last block, write // out and 1 to let the zlib decompressor know. By default, use the MaxBlockSize. int length = MaxBlockSize; if ( currentBlock == blockCount ) { length = lastBlockSize; data[dataPointer] = 0x01; } else { data[dataPointer] = 0x00; } // Each and every time we write something to the data array, increment the pointer. dataPointer++; // Write the block length out. tempBytes = BitConverter.GetBytes( length ); data[dataPointer + 0] = tempBytes[0]; data[dataPointer + 1] = tempBytes[1]; dataPointer += 2; // Write one's compliment of length for error checking. tempBytes = BitConverter.GetBytes( (ushort) ~length ); data[dataPointer + 0] = tempBytes[0]; data[dataPointer + 1] = tempBytes[1]; dataPointer += 2; // Reset the remaining block size to the next block's length. blockRemainder = length; } // Set the filter byte to 0, not really required as C# initalizes the byte array to 0 by default, but here for clarity. data[dataPointer] = 0; // Add the current byte to the running Adler32 value, note we ONLY add the filter byte and the pixel bytes to the // Adler32 CRC, all other header and block header bytes are execluded from the CRC. crcCode.Add( data, 1, (uint) dataPointer ); // Increment the data pointer and decrement the remain block value. dataPointer++; blockRemainder--; // Loop thorough each pixel in the row, you have to do this as the source format and destination format may be different. for ( int x = 0; x < _bitmap.PixelWidth; x++ ) { // Data is in RGBA format but source may not be pixel = BitConverter.GetBytes( _bitmap.Pixels[pixelSource] ); // Loop through the 4 bytes of the pixel and 'write' them to the data array. for ( int z = 0; z < 4; z++ ) { // This is the second appearance of this code code. // It checks to see if we're at the boundry for the PNG block and if so writes // out a new block header. if ( blockRemainder == 0 ) { // Setup a temporary byte array to store the block size in. byte[] tempBytes = new byte[2]; // Increment the current block count. currentBlock++; // Figure out the current block size and if we're at the last block, write // out and 1 to let the zlib decompressor know. By default, use the MaxBlockSize. int length = MaxBlockSize; if ( currentBlock == blockCount ) { length = lastBlockSize; data[dataPointer] = 0x01; } else { data[dataPointer] = 0x00; } // Each and every time we write something to the data array, increment the pointer. dataPointer++; // Write the block length out. tempBytes = BitConverter.GetBytes( length ); data[dataPointer + 0] = tempBytes[0]; data[dataPointer + 1] = tempBytes[1]; dataPointer += 2; // Write one's compliment of length for error checking. tempBytes = BitConverter.GetBytes( (ushort) ~length ); data[dataPointer + 0] = tempBytes[0]; data[dataPointer + 1] = tempBytes[1]; dataPointer += 2; // Reset the remaining block size to the next block's length. blockRemainder = length; } // Store the pixel's byte in to the data array. We use the WBByteOrder array to ensure // we have the write order of bytes to store in the PNG file. if ( z != 3 && pixel[WBByteOrder[3]] != 0 && pixel[WBByteOrder[3]] != 255 ) { // Calculate unmultiplied pixel value from premultiplied value (Windows Phone always uses premultiplied ARGB32) data[dataPointer] = (byte) ( ( 255 * pixel[WBByteOrder[z]] ) / pixel[WBByteOrder[3]] ); } else { // Alpha channel or no need to unpremultiply data[dataPointer] = pixel[WBByteOrder[z]]; } // Add the current byte to the running Adler32 value, note we ONLY add the filter byte and the pixel bytes to the // Adler32 CRC, all other header and block header bytes are execluded from the CRC. crcCode.Add( data, 1, (uint) dataPointer ); // Increment the data pointer and decrement the remain block value. dataPointer++; blockRemainder--; } // Increment where we start writting the next pixel and where we get the next pixel from. pixelSource++; } } // Whew, wipe that brow, we're done all the complex bits now! // Write the Adler32 CRC out, but reverse the order of the bytes to match the zlib spec. pixel = BitConverter.GetBytes( crcCode.CurrentValue ); data[dataPointer + 0] = pixel[3]; data[dataPointer + 1] = pixel[2]; data[dataPointer + 2] = pixel[1]; data[dataPointer + 3] = pixel[0]; // Yes, yes, I know I said "Each and every time we write something to the data array, increment the pointer." // but we're done with it now so I'm not going to bother ;) // Write the entire PNG data chunk out to the file stream. WriteChunk( PngChunkTypes.Data, data, 0, pngLength ); }
public void free() { next_in = null; next_out = null; msg = null; _adler = null; }