public void TestComposes() { var crc = new Crc32C(); crc.Update(Encoding.ASCII.GetBytes("hello "), 0, 6); crc.Update(Encoding.ASCII.GetBytes("world"), 0, 5); Assert.Equal(crc.GetIntValue(), ComputeCrc(Encoding.ASCII.GetBytes("hello world"))); }
private static uint ComputeCrc(byte[] data) { var crc = new Crc32C(); crc.Update(data, 0, data.Length); return(crc.GetIntValue()); }
public byte[] ToByteArray() { using (MemoryStream ms = new MemoryStream()) using (BinaryWriter writer = new BinaryWriter(ms)) { writer.Write((byte)(((byte)packetType) | (usingChecksum ? 0x80 : 0))); writer.Write(retryCount); writer.Write(from); writer.Write(to); writer.Write(channel); writer.Write(fragment); writer.Write(seq); writer.Write(timestamp); writer.Write(payload); writer.Flush(); if (usingChecksum) { byte[] data = ms.ToArray(); Crc32C crc = new Crc32C(); crc.Update(data, 0, data.Length); uint checksum = crc.GetIntValue(); writer.Write(checksum); writer.Flush(); } return(ms.ToArray()); } }
public void TestMask() { var crc = new Crc32C(); crc.Update(Encoding.ASCII.GetBytes("foo"), 0, 3); Assert.Equal(crc.GetMaskedValue(), Mask(crc.GetIntValue())); Assert.False(crc.GetIntValue() == crc.GetMaskedValue(), "crc should not match masked crc"); Assert.False(crc.GetIntValue() == Mask(crc.GetMaskedValue()), "crc should not match double masked crc"); Assert.Equal(crc.GetIntValue(), Unmask(crc.GetMaskedValue())); Assert.Equal(crc.GetIntValue(), Unmask(Unmask(Mask(crc.GetMaskedValue())))); }
public static NetworkPacket FromByteArray(byte[] data) { NetworkPacket packet = new NetworkPacket(); using (MemoryStream ms = new MemoryStream(data, false)) using (BinaryReader reader = new BinaryReader(ms)) { byte packetFlags = reader.ReadByte(); packet.usingChecksum = (packetFlags & 0x80) != 0; packet.packetType = (PacketType)(byte)(packetFlags & ~0x80); packet.retryCount = reader.ReadByte(); packet.from = reader.ReadByte(); packet.to = reader.ReadByte(); packet.channel = reader.ReadByte(); packet.fragment = reader.ReadUInt16(); packet.seq = reader.ReadUInt16(); packet.timestamp = reader.ReadUInt32(); if (packet.usingChecksum) { packet.payload = reader.ReadBytes(data.Length - 13 - 4); uint checksum = reader.ReadUInt32(); Crc32C crc = new Crc32C(); crc.Update(data, 0, data.Length - 4); uint validChecksum = crc.GetIntValue(); if (checksum != validChecksum) { throw new IOException("Invalid checksum! Got 0x" + checksum.ToString("X8") + ", should be 0x" + validChecksum.ToString("X8")); } } else { packet.payload = reader.ReadBytes(data.Length - 13); } return(packet); } }