Example #1
0
        /// <summary>
        /// WebSocket Frame输出
        /// </summary>
        /// <param name="response"></param>
        /// <param name="mask"></param>
        public static void WriteWebSocketFrameResponse(FrameResponse response, bool mask)
        {
            ByteBits bits = (byte)response.Frame;

            bits[0] = response.Fin;
            response.Stream.WriteByte(bits);
            if (response.Content.Length > UInt16.MaxValue)
            {
                response.Stream.WriteByte(mask ? byte.MaxValue : (byte)127);
                response.Stream.WriteLong((long)response.Content.Length);
            }
            else if (response.Content.Length > 125)
            {
                response.Stream.WriteByte(mask ? (byte)254 : (byte)126);
                response.Stream.WriteShort((short)response.Content.Length);
            }
            else
            {
                byte len = mask ? (byte)(response.Content.Length + 128) : (byte)response.Content.Length;
                response.Stream.WriteByte(len);
            }
            if (mask)
            {
                byte[] maskingKey = Converter.ToBytes(FrameResponse.ran.Next());
                response.Stream.WriteBytes(maskingKey);

                for (int i = 0; i < response.Content.Length; i++)
                {
                    response.Content[i] = (byte)(response.Content[i] ^ (maskingKey[i % 4]));
                }
            }

            response.Stream.WriteBytes(response.Content);
        }
        public void TestBytesToBits()
        {
            byte[] input  = SampleByteArray.ToArray();
            bool[] bytes  = ByteBits.GetBits(input);
            byte[] output = ByteBits.GetBytes(bytes);

            CompareBytes(input, output);
        }
Example #3
0
        public void op_ImplicitTest1()
        {
            ByteBits bits     = new ByteBits(); // TODO: 初始化为适当的值
            byte     expected = 0;              // TODO: 初始化为适当的值
            byte     actual;

            actual = bits;
            Assert.AreEqual(expected, actual);
        }
Example #4
0
        public void op_ImplicitTest()
        {
            byte     value    = 0;              // TODO: 初始化为适当的值
            ByteBits expected = new ByteBits(); // TODO: 初始化为适当的值
            ByteBits actual;

            actual = value;
            Assert.AreEqual(expected, actual);
        }
Example #5
0
        public void GetHashCodeTest()
        {
            ByteBits target   = 6; // TODO: 初始化为适当的值
            int      expected = 6; // TODO: 初始化为适当的值
            int      actual;

            actual = target.GetHashCode();
            Assert.AreEqual(expected, actual);
        }
Example #6
0
        public void TakeTest()
        {
            ByteBits target   = byte.MaxValue; // TODO: 初始化为适当的值
            int      count    = 4;             // TODO: 初始化为适当的值
            ByteBits expected = 15;            // TODO: 初始化为适当的值
            ByteBits actual;

            actual = target.Take(count);
            Assert.AreEqual(expected, actual);
        }
Example #7
0
        public void MoveLeftTest()
        {
            ByteBits target   = byte.MaxValue;     // TODO: 初始化为适当的值
            int      count    = 1;                 // TODO: 初始化为适当的值
            ByteBits expected = byte.MaxValue - 1; // TODO: 初始化为适当的值
            ByteBits actual;

            actual = target.MoveLeft(count);
            Assert.AreEqual(expected, actual);
        }
Example #8
0
        public void EqualsTest()
        {
            ByteBits target   = 5;     // TODO: 初始化为适当的值
            object   obj      = 5;     // TODO: 初始化为适当的值
            bool     expected = false; // TODO: 初始化为适当的值
            bool     actual;

            actual = target.Equals(obj);
            Assert.AreEqual(expected, actual);
        }
Example #9
0
 public void ItemTest()
 {
     ByteBits target = new ByteBits(); // TODO: 初始化为适当的值
     int index = 0; // TODO: 初始化为适当的值
     bool expected = false; // TODO: 初始化为适当的值
     bool actual;
     target[index] = expected;
     actual = target[index];
     Assert.AreEqual(expected, actual);
 }
Example #10
0
        public void TakeTest1()
        {
            ByteBits target   = 2;     // TODO: 初始化为适当的值
            int      index    = 8 - 2; // TODO: 初始化为适当的值
            int      count    = 2;     // TODO: 初始化为适当的值
            ByteBits expected = 2;     // TODO: 初始化为适当的值
            ByteBits actual;

            actual = target.Take(index, count);
            Assert.AreEqual(expected, actual);
        }
Example #11
0
        static public byte GetBitValue(int dx, int dy)
        {
            int index;

            if (TryGetBitIndex(dx, dy, out index))
            {
                return(ByteBits.GetNthBitValue(index));
            }

            return(0);
        }
Example #12
0
        public void ItemTest()
        {
            ByteBits target   = new ByteBits(); // TODO: 初始化为适当的值
            int      index    = 0;              // TODO: 初始化为适当的值
            bool     expected = false;          // TODO: 初始化为适当的值
            bool     actual;

            target[index] = expected;
            actual        = target[index];
            Assert.AreEqual(expected, actual);
        }
Example #13
0
        /// <summary>
        /// 转换为ArraySegment
        /// </summary>
        /// <param name="mask">是否打码</param>
        /// <returns></returns>
        public override unsafe ArraySegment <byte> ToArraySegment(bool mask)
        {
            var builder = new ByteBuilder(Endians.Big);

            ByteBits bits = (byte)this.Frame;

            bits[0] = this.Fin;
            builder.Add(bits);

            if (this.Content.Length > UInt16.MaxValue)
            {
                builder.Add(mask ? byte.MaxValue : (byte)127);
                builder.Add((ulong)this.Content.Length);
            }
            else if (this.Content.Length > 125)
            {
                builder.Add(mask ? (byte)254 : (byte)126);
                builder.Add((ushort)this.Content.Length);
            }
            else
            {
                var len = mask ? (byte)(this.Content.Length + 128) : (byte)this.Content.Length;
                builder.Add(len);
            }

            if (mask == true)
            {
                var maskingKey = ByteConverter.ToBytes(ran.Next(), Endians.Big);
                builder.Add(maskingKey);

                fixed(byte *pcontent = &this.Content[0], pmask = &maskingKey[0])
                {
                    for (var i = 0; i < this.Content.Length; i++)
                    {
                        *(pcontent + i) = (byte)(*(pcontent + i) ^ *(pmask + i % 4));
                    }
                }
            }

            builder.Add(this.Content);
            return(builder.ToArraySegment());
        }
 public static Byte SetBit(this Byte value, ByteBits bitIndex, Boolean bitValue)
 {
     var mask = bitIndex.GetMask();
     return ByteExtensions.SetBit(value, mask, bitValue);
 }
Example #15
0
        /// <summary>
        /// 解析请求的数据
        /// 返回请求数据包
        /// </summary>
        /// <param name="stream">所有收到的数据</param>
        /// <param name="requiredMask">是否要求必须Mask</param>
        /// <exception cref="NotSupportedException"></exception>
        /// <returns></returns>
        public unsafe static FrameRequest Parse(IStreamReader stream, bool requiredMask = true)
        {
            if (stream.Length < 2)
            {
                return(null);
            }

            ByteBits byte0     = stream[0];
            var      fin       = byte0[0];
            var      frameCode = (FrameCodes)(byte)byte0.Take(4, 4);

            if (fin == false || frameCode == FrameCodes.Continuation)
            {
                return(null);
            }

            var      rsv   = byte0.Take(1, 3);
            ByteBits byte1 = stream[1];
            var      mask  = byte1[0];

            if (requiredMask && mask == false)
            {
                throw new NotSupportedException("mask is required");
            }

            if (Enum.IsDefined(typeof(FrameCodes), frameCode) == false || rsv != 0)
            {
                throw new NotSupportedException();
            }

            var contentSize   = 0;
            var contentLength = (int)byte1.Take(1, 7);

            stream.Position = 2;

            if (contentLength == 127)
            {
                contentSize   = 8;
                contentLength = (int)stream.ReadUInt64();
            }
            else if (contentLength == 126)
            {
                contentSize   = 2;
                contentLength = (int)stream.ReadUInt16();
            }

            var maskSize     = mask ? 4 : 0;
            var packetLength = 2 + maskSize + contentSize + contentLength;

            if (stream.Length < packetLength)
            {
                return(null);
            }

            var maskingKey = mask ? stream.ReadArray(4) : null;
            var content    = stream.ReadArray(contentLength);

            stream.Clear(packetLength);

            if (mask && contentLength > 0)
            {
                fixed(byte *pcontent = &content[0], pmask = &maskingKey[0])
                {
                    for (var i = 0; i < contentLength; i++)
                    {
                        *(pcontent + i) = (byte)(*(pcontent + i) ^ *(pmask + i % 4));
                    }
                }
            }

            return(new FrameRequest
            {
                Fin = fin,
                Rsv = rsv,
                Mask = mask,
                Frame = frameCode,
                ContentLength = contentLength,
                MaskingKey = maskingKey,
                Content = content
            });
        }
Example #16
0
        /// <summary>
        /// 解析请求的数据
        /// 返回请求数据包
        /// </summary>
        /// <param name="buffer">所有收到的数据</param>
        /// <returns></returns>
        public unsafe static FrameRequest Parse(IReceiveBuffer buffer)
        {
            if (buffer.Length < 2)
            {
                return(null);
            }

            ByteBits byte0     = buffer[0];
            var      fin       = byte0[0];
            var      frameCode = (FrameCodes)(byte)byte0.Take(4, 4);

            if (fin == false || frameCode == FrameCodes.Continuation)
            {
                return(null);
            }

            var      rsv   = byte0.Take(1, 3);
            ByteBits byte1 = buffer[1];
            var      mask  = byte1[0];

            if (mask == false || Enum.IsDefined(typeof(FrameCodes), frameCode) == false || rsv != 0)
            {
                return(null);
            }

            var contentLength = (int)byte1.Take(1, 7);

            buffer.Position = 2;

            if (contentLength == 127)
            {
                contentLength = (int)buffer.ReadUInt64();
            }
            else if (contentLength == 126)
            {
                contentLength = (int)buffer.ReadUInt16();
            }

            var packetLength = 6 + contentLength;

            if (buffer.Length < packetLength)
            {
                return(null);
            }

            var maskingKey = buffer.ReadArray(4);
            var content    = buffer.ReadArray(contentLength);

            buffer.Clear(packetLength);

            if (contentLength > 0)
            {
                fixed(byte *pcontent = &content[0], pmask = &maskingKey[0])
                {
                    for (var i = 0; i < contentLength; i++)
                    {
                        *(pcontent + i) = (byte)(*(pcontent + i) ^ *(pmask + i % 4));
                    }
                }
            }

            return(new FrameRequest
            {
                Fin = fin,
                Rsv = rsv,
                Mask = mask,
                Frame = frameCode,
                ContentLength = contentLength,
                MaskingKey = maskingKey,
                Content = content
            });
        }
Example #17
0
        /// <summary>
        /// 解析请求的数据
        /// 返回请求数据包
        /// </summary>
        /// <param name="streamReader">数据读取器</param>
        /// <param name="requiredMask">是否要求必须Mask</param>
        /// <exception cref="NotSupportedException"></exception>
        /// <returns></returns>
        public static FrameRequest Parse(IByteStream streamReader, bool requiredMask = true)
        {
            if (streamReader.Length < 2)
            {
                return(null);
            }

            ByteBits   byte0     = streamReader.ReadByte();
            bool       fin       = byte0[0];
            ByteBits   rsv       = byte0.Take(1, 3);
            FrameCodes frameCode = (FrameCodes)(byte)byte0.Take(4, 4);

            ByteBits byte1 = streamReader.ReadByte();
            bool     mask  = byte1[0];

            if (requiredMask && mask == false)
            {
                throw new NotSupportedException("mask is required");
            }

            if (Enum.IsDefined(typeof(FrameCodes), frameCode) == false || rsv != 0)
            {
                throw new NotSupportedException();
            }

            int contentSize   = 0;
            int contentLength = byte1.Take(1, 7);

            if (contentLength == 127)
            {
                contentSize   = 8;
                contentLength = (int)streamReader.ReadLong();
            }
            else if (contentLength == 126)
            {
                contentSize   = 2;
                contentLength = (ushort)streamReader.ReadShort();
            }

            int maskSize     = mask ? 4 : 0;
            int packetLength = 2 + maskSize + contentSize + contentLength;

            if (streamReader.Length < packetLength)
            {
                return(null);
            }

            byte[] maskingKey = mask ? streamReader.ReadBytes(4) : null;
            byte[] content    = streamReader.ReadBytes(contentLength);

            if (mask && contentLength > 0)
            {
                for (int i = 0; i < contentLength; i++)
                {
                    content[i] = (byte)(content[i] ^ maskingKey[i % 4]);
                }
            }

            return(new FrameRequest
            {
                Fin = fin,
                Rsv = rsv,
                Mask = mask,
                Frame = frameCode,
                ContentLength = contentLength,
                MaskingKey = maskingKey,
                Content = content
            });
        }
Example #18
0
 public void op_ImplicitTest1()
 {
     ByteBits bits = new ByteBits(); // TODO: 初始化为适当的值
     byte expected = 0; // TODO: 初始化为适当的值
     byte actual;
     actual = bits;
     Assert.AreEqual(expected, actual);            
 }
Example #19
0
 public void op_ImplicitTest()
 {
     byte value = 0; // TODO: 初始化为适当的值
     ByteBits expected = new ByteBits(); // TODO: 初始化为适当的值
     ByteBits actual;
     actual = value;
     Assert.AreEqual(expected, actual);           
 }
Example #20
0
        private void SetValuesPartialBinaryMix(BinaryMessage requestedMessage, List <List <byte> > dataRequestsBytes)
        {
            m_responseValues = new List <object>();
            int index    = 0;
            int bitIndex = 0;


            if (m_detailsBytes.Count > 0 || requestedMessage.Details.DetailsBytes.Length > 0)
            {
                for (int i = 0; i < m_dataRequests.Count; i++)
                {
                    string operatorName = String.Empty;
                    UInt16 length       = 0;
                    int    size         = 0;

                    operatorName = (dataRequestsBytes[i])[2].GetOperandNameByValue();
                    size         = Utils.OperandTypesDictionary[operatorName].OperandSize;
                    length       = BitConverter.ToUInt16(dataRequestsBytes[i].ToArray(), 0);

                    switch (size)
                    {
                    case 1:
                        int NumOfValues =
                            BitConverter.ToInt32(
                                new byte[] { dataRequestsBytes[i][0], dataRequestsBytes[i][1], 0, 0 }, 0);
                        ByteBits bits;
                        bits = new ByteBits(m_detailsValues[index]);
                        for (int iter = 0; iter < NumOfValues; iter++)
                        {
                            if (bits[bitIndex])
                            {
                                m_responseValues.Add((short)1);
                            }
                            else
                            {
                                m_responseValues.Add((short)0);
                            }

                            bitIndex++;
                            if (bitIndex >= 8)
                            {
                                bitIndex = 0;
                                index++;
                                bits = new ByteBits(m_detailsValues[index]);
                            }
                        }

                        break;

                    case 16:
                        if (bitIndex != 0)
                        {
                            bitIndex = 0;
                            index++;
                            index += (index % 2);
                        }
                        else
                        {
                            index += (index % 2);
                        }

                        for (int j = 0; j < length; j++)
                        {
                            try
                            {
                                m_responseValues.Add(BitConverter.ToInt16(
                                                         new byte[2] {
                                    m_detailsValues[index], m_detailsValues[index + 1]
                                }, 0));
                            }
                            catch
                            {
                            }
                            finally
                            {
                                index += 2;
                            }
                        }

                        break;

                    case 32:
                        if (bitIndex != 0)
                        {
                            bitIndex = 0;
                            index++;
                            index += (index % 2);
                        }
                        else
                        {
                            index += (index % 2);
                        }

                        for (int j = 0; j < length; j++)
                        {
                            switch (operatorName)
                            {
                            case Utils.Operands.OP_MF:
                                m_responseValues.Add(Utils.HexEncoding.ConvertBytesToSingle(new byte[4]
                                {
                                    m_detailsValues[index + 2],
                                    m_detailsValues[index + 3],
                                    m_detailsValues[index + 0],
                                    m_detailsValues[index + 1]
                                }));
                                break;

                            case Utils.Operands.OP_TIMER_CURRENT:
                            case Utils.Operands.OP_TIMER_PRESET:
                                UInt32 uint_Value = BitConverter.ToUInt32(m_detailsValues, index);
                                if ((requestedMessage.Details.m_dataRequests[i] as ReadOperands)
                                    .TimerValueFormat.Equals(TimerValueFormat.TimeFormat))
                                {
                                    m_responseValues.Add(Utils.z_GetTimeUnits(Convert.ToInt32(uint_Value)));
                                }
                                else
                                {
                                    m_responseValues.Add(uint_Value);
                                }

                                break;

                            case Utils.Operands.OP_ML:
                            case Utils.Operands.OP_XL:
                            case Utils.Operands.OP_SL:
                                Int32 value = BitConverter.ToInt32(m_detailsValues, index);
                                m_responseValues.Add(value);
                                break;

                            case Utils.Operands.OP_DW:
                            case Utils.Operands.OP_XDW:
                            case Utils.Operands.OP_SDW:
                                uint_Value = BitConverter.ToUInt32(m_detailsValues, index);
                                m_responseValues.Add(uint_Value);
                                break;
                            }

                            index += 4;
                        }

                        break;

                    default:
                        System.Diagnostics.Debug.Assert(false);
                        break;
                    }

                    object[] objects = new object[m_responseValues.Count];
                    Array.Copy(m_responseValues.ToArray(), objects, m_responseValues.Count);
                    m_dataRequests[i].ResponseValues = objects;
                    m_responseValues.Clear();
                }
            }
        }
Example #21
0
        public int[] HashElement(string element)
        {
            List <int> results = new List <int>();

            using (RC4TableHash _streamCipher = new RC4TableHash())
            {
                //_streamCipher.Reset(); // Reset the internal state of the stream cipher

                byte[] elementBytes = ByteBits.GetBytes(element);
                _streamCipher.Shuffle(elementBytes.Length);
                _streamCipher.KeySchedule(elementBytes);
                _streamCipher.Shuffle(elementBytes.Length);

                int        counter    = 0;
                BigInteger grandTotal = 0;
                foreach (byte bite in elementBytes)
                {
                    grandTotal += BigInteger.Pow(bite * byte.MaxValue, counter);
                    counter++;
                }



                int shuffle;
                counter = 0;
                foreach (byte bite in elementBytes)                 // Shuffle by some amount that should be unique for the element
                {
                    // We are using mod 255 here because it would be too slow if we didn't restrict the rounds of shuffling
                    shuffle = (int)BigInteger.ModPow(bite * byte.MaxValue, counter, byte.MaxValue - 1);
                    _streamCipher.Shuffle(shuffle);
                    counter++;
                }

                // Now, grab some bytes from the stream cipher
                int maxValue    = _filterSize - 1;
                int bytesToTake = (int)Math.Ceiling(Math.Log(_filterSize, 2) / 8);

                counter = 0;
                List <byte> bytes;
                while (counter < _hashesPerElement)
                {
                    bytes = _streamCipher.GetBytes().Take(bytesToTake).ToList();

                    // Pad bytes to a multiple of 4
                    while (bytes.Count % 4 != 0)
                    {
                        bytes.Add(0);
                    }

                    int hashValue = Math.Abs(BitConverter.ToInt32(bytes.ToArray(), 0));
                    if (hashValue > maxValue)
                    {
                        hashValue = hashValue % maxValue;
                    }

                    results.Add(hashValue);
                    counter++;
                }
            }

            return(results.ToArray());
        }
 public static Boolean GetBit(this Byte value, ByteBits bitIndex)
 {
     var mask = bitIndex.GetMask();
     return ByteExtensions.GetBit(value, mask);
 }