Beispiel #1
0
        public static byte[] ComputeHash(byte[] buffer, int offset, int length)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }
            if (offset < 0 || buffer.Length < offset)
            {
                throw new ArgumentOutOfRangeException("offset");
            }
            if (length < 0 || (buffer.Length - offset) < length)
            {
                throw new ArgumentOutOfRangeException("length");
            }

            uint x = 0xFFFFFFFF;

            fixed(byte *p_buffer = buffer)
            {
                var t_buffer = p_buffer + offset;

                x = _compute(x, t_buffer, length);
            }

            return(NetworkConverter.GetBytes(x ^ 0xFFFFFFFF));
        }
Beispiel #2
0
        public static void Write(Stream stream, byte type, Stream exportStream)
        {
            stream.WriteByte(type);
            stream.Write(NetworkConverter.GetBytes((int)exportStream.Length), 0, 4);

            byte[] buffer = null;

            try
            {
                buffer = _bufferManager.TakeBuffer(1024 * 4);
                int length = 0;

                while ((length = exportStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    stream.Write(buffer, 0, length);
                }
            }
            finally
            {
                if (buffer != null)
                {
                    _bufferManager.ReturnBuffer(buffer);
                }
            }
        }
Beispiel #3
0
        private byte[] Function()
        {
            if (_blockIndex == uint.MaxValue)
            {
                throw new InvalidOperationException("Derived key too long.");
            }

            byte[] currentHash;

            {
                var input = new byte[this.Salt.Length + 4];
                Unsafe.Copy(this.Salt, 0, input, 0, this.Salt.Length);
                Unsafe.Copy(NetworkConverter.GetBytes(_blockIndex), 0, input, this.Salt.Length, 4);

                _blockIndex++;

                currentHash = this.Algorithm.ComputeHash(input);
            }

            byte[] finalHash = currentHash;

            for (int i = 2; i <= this.IterationCount; i++)
            {
                currentHash = this.Algorithm.ComputeHash(currentHash, 0, currentHash.Length);

                Unsafe.Xor(finalHash, currentHash, finalHash);
            }

            return(finalHash);
        }
Beispiel #4
0
        private static Stream AddType(Stream stream, string type)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            List <Stream> streams  = new List <Stream>();
            Encoding      encoding = new UTF8Encoding(false);

            // Type
            if (type != null)
            {
                BufferStream bufferStream = new BufferStream(_bufferManager);
                bufferStream.SetLength(4);
                bufferStream.Seek(4, SeekOrigin.Begin);

                using (WrapperStream wrapperStream = new WrapperStream(bufferStream, true))
                    using (StreamWriter writer = new StreamWriter(wrapperStream, encoding))
                    {
                        writer.Write(type);
                    }

                bufferStream.Seek(0, SeekOrigin.Begin);
                bufferStream.Write(NetworkConverter.GetBytes((int)bufferStream.Length - 4), 0, 4);

                streams.Add(bufferStream);
            }

            streams.Add(new WrapperStream(stream, true));

            return(new UniteStream(streams));
        }
Beispiel #5
0
        private static Stream AddPadding(Stream stream, int size)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            try
            {
                byte[] seedBuffer = new byte[4];
                _random.GetBytes(seedBuffer);
                Random random = new Random(NetworkConverter.ToInt32(seedBuffer));

                BufferStream metadataStream = new BufferStream(_bufferManager);
                byte[]       lengthBuffer   = NetworkConverter.GetBytes((int)stream.Length);
                metadataStream.Write(lengthBuffer, 0, lengthBuffer.Length);

                int paddingLength = size - ((int)stream.Length + 4);

                BufferStream paddingStream = new BufferStream(_bufferManager);

                {
                    byte[] buffer = null;

                    try
                    {
                        buffer = _bufferManager.TakeBuffer(1024);

                        while (paddingLength > 0)
                        {
                            int writeSize = Math.Min(paddingLength, buffer.Length);

                            random.NextBytes(buffer);
                            paddingStream.Write(buffer, 0, writeSize);

                            paddingLength -= writeSize;
                        }
                    }
                    finally
                    {
                        _bufferManager.ReturnBuffer(buffer);
                    }
                }

                return(new UniteStream(metadataStream, new WrapperStream(stream, true), paddingStream));
            }
            catch (Exception e)
            {
                throw new ArgumentException(e.Message, e);
            }
        }
Beispiel #6
0
        public void Test_NetworkConverter()
        {
            Assert.IsTrue(NetworkConverter.ToHexString(new byte[] { 0x00, 0x9e, 0x0f }) == "009e0f", "ToHexString");
            Assert.IsTrue(CollectionUtilities.Equals(NetworkConverter.FromHexString("1af4b"), new byte[] { 0x01, 0xaf, 0x4b }), "FromHexString");

            Assert.IsTrue(NetworkConverter.ToBoolean(new byte[] { 0x01 }), "ToBoolean");
            Assert.IsTrue(NetworkConverter.ToChar(new byte[] { 0x00, 0x41 }) == 'A', "ToChar");
            Assert.IsTrue(NetworkConverter.ToInt16(new byte[] { 0x74, 0xab }) == 0x74ab, "ToInt16");
            Assert.IsTrue(NetworkConverter.ToUInt16(new byte[] { 0x74, 0xab }) == 0x74ab, "ToUInt16");
            Assert.IsTrue(NetworkConverter.ToInt32(new byte[] { 0x74, 0xab, 0x05, 0xc1 }) == 0x74ab05c1, "ToInt32");
            Assert.IsTrue(NetworkConverter.ToUInt32(new byte[] { 0x74, 0xab, 0x05, 0xc1 }) == 0x74ab05c1, "ToUInt32");
            Assert.IsTrue(NetworkConverter.ToInt64(new byte[] { 0x74, 0xab, 0xa5, 0xbb, 0xf5, 0x39, 0x7b, 0x15 }) == 0x74aba5bbf5397b15, "ToInt64");
            Assert.IsTrue(NetworkConverter.ToUInt64(new byte[] { 0x74, 0xab, 0xa5, 0xbb, 0xf5, 0x39, 0x7b, 0x15 }) == 0x74aba5bbf5397b15, "ToUInt64");
            Assert.IsTrue(NetworkConverter.ToSingle(new byte[] { 0x4a, 0x8a, 0xd0, 0x64 }) == 4548658.0, "ToSingle");
            Assert.IsTrue(NetworkConverter.ToDouble(new byte[] { 0x41, 0xb8, 0xa6, 0xb9, 0x83, 0x27, 0x97, 0xa3 }) == 413579651.15465754, "ToDouble");

            Assert.IsTrue(CollectionUtilities.Equals(NetworkConverter.GetBytes(true), new byte[] { 0x01 }), "GetBytes #bool");
            Assert.IsTrue(CollectionUtilities.Equals(NetworkConverter.GetBytes((char)'A'), new byte[] { 0x00, 0x41 }), "GetBytes #char");
            Assert.IsTrue(CollectionUtilities.Equals(NetworkConverter.GetBytes((short)0x74ab), new byte[] { 0x74, 0xab }), "GetBytes #short");
            Assert.IsTrue(CollectionUtilities.Equals(NetworkConverter.GetBytes((ushort)0x74ab), new byte[] { 0x74, 0xab }), "GetBytes #ushort");
            Assert.IsTrue(CollectionUtilities.Equals(NetworkConverter.GetBytes((int)0x74ab05c1), new byte[] { 0x74, 0xab, 0x05, 0xc1 }), "GetBytes #int");
            Assert.IsTrue(CollectionUtilities.Equals(NetworkConverter.GetBytes((uint)0x74ab05c1), new byte[] { 0x74, 0xab, 0x05, 0xc1 }), "GetBytes #uint");
            Assert.IsTrue(CollectionUtilities.Equals(NetworkConverter.GetBytes((long)0x74aba5bbf5397b15), new byte[] { 0x74, 0xab, 0xa5, 0xbb, 0xf5, 0x39, 0x7b, 0x15 }), "GetBytes #long");
            Assert.IsTrue(CollectionUtilities.Equals(NetworkConverter.GetBytes((ulong)0x74aba5bbf5397b15), new byte[] { 0x74, 0xab, 0xa5, 0xbb, 0xf5, 0x39, 0x7b, 0x15 }), "GetBytes #ulong");
            Assert.IsTrue(CollectionUtilities.Equals(NetworkConverter.GetBytes((float)4548658.0), new byte[] { 0x4a, 0x8a, 0xd0, 0x64 }), "GetBytes #float");
            Assert.IsTrue(CollectionUtilities.Equals(NetworkConverter.GetBytes((double)413579651.15465754), new byte[] { 0x41, 0xb8, 0xa6, 0xb9, 0x83, 0x27, 0x97, 0xa3 }), "GetBytes #double");

            Assert.IsTrue(NetworkConverter.ToInt32(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x74, 0xab, 0x05, 0xc1 }, 4) == 0x74ab05c1, "ToInt32");

            for (int i = 0; i < 1024; i++)
            {
                byte[] buffer = new byte[_random.Next(0, 128)];
                _random.NextBytes(buffer);

                var s = NetworkConverter.ToBase64UrlString(buffer);
                Assert.IsTrue(CollectionUtilities.Equals(buffer, NetworkConverter.FromBase64UrlString(s)));
            }

            for (int i = 0; i < 1024; i++)
            {
                byte[] buffer = new byte[_random.Next(0, 128)];
                _random.NextBytes(buffer);

                var s = NetworkConverter.ToHexString(buffer);
                Assert.IsTrue(CollectionUtilities.Equals(buffer, NetworkConverter.FromHexString(s)));
            }
        }
Beispiel #7
0
        private static ArraySegment <byte> ToBuffer(IEnumerable <byte[]> buffers, BufferManager bufferManager)
        {
            int length = buffers.Sum(n => n.Length);

            byte[] buffer = bufferManager.TakeBuffer(length);

            using (MemoryStream memoryStream = new MemoryStream(buffer))
            {
                foreach (var buffer2 in buffers)
                {
                    memoryStream.Write(NetworkConverter.GetBytes((int)buffer2.Length), 0, 4);
                    memoryStream.Write(buffer2, 0, buffer2.Length);
                }
            }

            return(new ArraySegment <byte>(buffer, 0, length));
        }
Beispiel #8
0
        public override void Connect(TimeSpan timeout, Information options)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(this.GetType().FullName);
            }

            lock (this.ThisLock)
            {
                try
                {
                    Stopwatch stopwatch = new Stopwatch();
                    stopwatch.Start();

                    using (BufferStream stream = new BufferStream(_bufferManager))
                    {
                        byte[] buffer = NetworkConverter.GetBytes((uint)_myCompressAlgorithm);
                        stream.Write(buffer, 0, buffer.Length);
                        stream.Flush();
                        stream.Seek(0, SeekOrigin.Begin);

                        _connection.Send(stream, CheckTimeout(stopwatch.Elapsed, timeout));
                    }

                    using (Stream stream = _connection.Receive(CheckTimeout(stopwatch.Elapsed, timeout)))
                    {
                        byte[] buffer = new byte[4];
                        stream.Read(buffer, 0, buffer.Length);

                        _otherCompressAlgorithm = (CompressAlgorithm)NetworkConverter.ToUInt32(buffer);
                    }
                }
                catch (ConnectionException ex)
                {
                    throw ex;
                }
                catch (Exception ex)
                {
                    throw new ConnectionException(ex.Message, ex);
                }

                _connect = true;
            }
        }
Beispiel #9
0
        public static byte[] ComputeHash(IList <ArraySegment <byte> > value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            uint x = 0xFFFFFFFF;

            for (int i = 0; i < value.Count && value[i].Array != null; i++)
            {
                for (int j = 0; j < value[i].Count; j++)
                {
                    x = _table[(x ^ value[i].Array[value[i].Offset + j]) & 0xFF] ^ (x >> 8);
                }
            }

            return(NetworkConverter.GetBytes(x ^ 0xFFFFFFFF));
        }
Beispiel #10
0
        public byte[] GetBytes(byte[] value, int length)
        {
            byte[] buffer = new byte[value.Length + 4];
            Unsafe.Copy(value, 0, buffer, 0, value.Length);

            using (MemoryStream stream = new MemoryStream())
            {
                for (int i = 0; stream.Length < length; i++)
                {
                    Unsafe.Copy(NetworkConverter.GetBytes(i), 0, buffer, value.Length, 4);

                    var hash = _hashAlgorithm.ComputeHash(buffer);

                    stream.Write(hash, 0, hash.Length);
                    stream.Flush();
                }

                return(stream.ToArray());
            }
        }
Beispiel #11
0
        public static byte[] ComputeHash(IList <ArraySegment <byte> > value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            uint x = 0xFFFFFFFF;

            for (int i = 0; i < value.Count && value[i].Array != null; i++)
            {
                fixed(byte *p_buffer = value[i].Array)
                {
                    var t_buffer = p_buffer + value[i].Offset;

                    x = _compute(x, t_buffer, value[i].Count);
                }
            }

            return(NetworkConverter.GetBytes(x ^ 0xFFFFFFFF));
        }
Beispiel #12
0
            public override Stream Export(BufferManager bufferManager)
            {
                using (DeadlockMonitor.Lock(this.ThisLock))
                {
                    List <Stream> streams = new List <Stream>();

                    // CommandMessages
                    foreach (var m in this.CommandMessages)
                    {
                        Stream exportStream = m.Export(bufferManager);

                        BufferStream bufferStream = new BufferStream(bufferManager);
                        bufferStream.Write(NetworkConverter.GetBytes((int)exportStream.Length), 0, 4);
                        bufferStream.WriteByte((byte)SerializeId.CommandMessage);

                        streams.Add(new JoinStream(bufferStream, exportStream));
                    }

                    return(new JoinStream(streams));
                }
            }
Beispiel #13
0
        public static bool VerifyFileCertificate(Certificate certificate, string name, Stream stream)
        {
            BufferManager bufferManager = BufferManager.Instance;
            List <Stream> streams       = new List <Stream>();
            Encoding      encoding      = new UTF8Encoding(false);

            // Name
            {
                BufferStream bufferStream = new BufferStream(bufferManager);
                bufferStream.SetLength(5);
                bufferStream.Seek(5, SeekOrigin.Begin);

                using (WrapperStream wrapperStream = new WrapperStream(bufferStream, true))
                    using (StreamWriter writer = new StreamWriter(wrapperStream, encoding))
                    {
                        writer.Write(Path.GetFileName(name));
                    }

                bufferStream.Seek(0, SeekOrigin.Begin);
                bufferStream.Write(NetworkConverter.GetBytes((int)bufferStream.Length - 5), 0, 4);
                bufferStream.WriteByte((byte)FileSerializeId.Name);

                streams.Add(bufferStream);
            }
            // Stream
            {
                Stream exportStream = new WrapperStream(stream, true);

                BufferStream bufferStream = new BufferStream(bufferManager);
                bufferStream.Write(NetworkConverter.GetBytes((int)exportStream.Length), 0, 4);
                bufferStream.WriteByte((byte)FileSerializeId.Stream);

                streams.Add(new UniteStream(bufferStream, exportStream));
            }

            using (var uniteStream = new UniteStream(streams))
            {
                return(certificate.Verify(uniteStream));
            }
        }
Beispiel #14
0
        public override Stream Export(BufferManager bufferManager)
        {
            using (DeadlockMonitor.Lock(this.ThisLock))
            {
                List <Stream> streams  = new List <Stream>();
                Encoding      encoding = new UTF8Encoding(false);

                // Command
                if (this.Command != null)
                {
                    BufferStream bufferStream = new BufferStream(bufferManager);
                    bufferStream.SetLength(5);
                    bufferStream.Seek(5, SeekOrigin.Begin);

                    using (CacheStream cacheStream = new CacheStream(bufferStream, 1024, true, bufferManager))
                        using (StreamWriter writer = new StreamWriter(cacheStream, encoding))
                        {
                            writer.Write(this.Command);
                        }

                    bufferStream.Seek(0, SeekOrigin.Begin);
                    bufferStream.Write(NetworkConverter.GetBytes((int)bufferStream.Length - 5), 0, 4);
                    bufferStream.WriteByte((byte)SerializeId.Command);

                    streams.Add(bufferStream);
                }
                // Content
                if (this.Content != null)
                {
                    BufferStream bufferStream = new BufferStream(bufferManager);
                    bufferStream.Write(NetworkConverter.GetBytes((int)this.Content.Count), 0, 4);
                    bufferStream.WriteByte((byte)SerializeId.Content);
                    bufferStream.Write(this.Content.Array, this.Content.Offset, this.Content.Count);

                    streams.Add(bufferStream);
                }

                return(new JoinStream(streams));
            }
        }
Beispiel #15
0
        public static byte[] ComputeHash(Stream inputStream)
        {
            if (inputStream == null)
            {
                throw new ArgumentNullException("inputStream");
            }

            uint x = 0xFFFFFFFF;

            byte[] buffer = new byte[1024 * 4];
            int    length = 0;

            fixed(byte *p_buffer = buffer)
            {
                while ((length = inputStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    x = _compute(x, p_buffer, length);
                }
            }

            return(NetworkConverter.GetBytes(x ^ 0xFFFFFFFF));
        }
Beispiel #16
0
        public static byte[] ComputeHash(Stream inputStream)
        {
            if (inputStream == null)
            {
                throw new ArgumentNullException("inputStream");
            }

            uint x = 0xFFFFFFFF;

            byte[] buffer = new byte[1024 * 4];
            int    length = 0;

            while (0 < (length = inputStream.Read(buffer, 0, buffer.Length)))
            {
                for (int i = 0; i < length; i++)
                {
                    x = _table[(x ^ buffer[i]) & 0xFF] ^ (x >> 8);
                }
            }

            return(NetworkConverter.GetBytes(x ^ 0xFFFFFFFF));
        }
Beispiel #17
0
        public static void Write(Stream stream, byte type, string value)
        {
            Encoding encoding = _threadLocalEncoding.Value;

            byte[] buffer = null;

            try
            {
                buffer = _bufferManager.TakeBuffer(encoding.GetMaxByteCount(value.Length));
                var length = encoding.GetBytes(value, 0, value.Length, buffer, 0);

                stream.WriteByte(type);
                stream.Write(NetworkConverter.GetBytes(length), 0, 4);
                stream.Write(buffer, 0, length);
            }
            finally
            {
                if (buffer != null)
                {
                    _bufferManager.ReturnBuffer(buffer);
                }
            }
        }
Beispiel #18
0
        public override Stream Export(BufferManager bufferManager)
        {
            List <Stream> streams  = new List <Stream>();
            Encoding      encoding = new UTF8Encoding(false);

            // Id
            if (this.Id != null)
            {
                BufferStream bufferStream = new BufferStream(bufferManager);
                bufferStream.Write(NetworkConverter.GetBytes((int)this.Id.Length), 0, 4);
                bufferStream.WriteByte((byte)SerializeId.Id);
                bufferStream.Write(this.Id, 0, this.Id.Length);

                streams.Add(bufferStream);
            }
            // Name
            if (this.Name != null)
            {
                BufferStream bufferStream = new BufferStream(bufferManager);
                bufferStream.SetLength(5);
                bufferStream.Seek(5, SeekOrigin.Begin);

                using (WrapperStream wrapperStream = new WrapperStream(bufferStream, true))
                    using (StreamWriter writer = new StreamWriter(wrapperStream, encoding))
                    {
                        writer.Write(this.Name);
                    }

                bufferStream.Seek(0, SeekOrigin.Begin);
                bufferStream.Write(NetworkConverter.GetBytes((int)bufferStream.Length - 5), 0, 4);
                bufferStream.WriteByte((byte)SerializeId.Name);

                streams.Add(bufferStream);
            }

            return(new JoinStream(streams));
        }
Beispiel #19
0
        public static byte[] ComputeHash(byte[] buffer, int offset, int length)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }
            else if (offset < 0 || buffer.Length < offset)
            {
                throw new ArgumentOutOfRangeException("offset");
            }
            else if (length < 0 || (buffer.Length - offset) < length)
            {
                throw new ArgumentOutOfRangeException("length");
            }

            uint x = 0xFFFFFFFF;

            for (int i = 0; i < length; i++)
            {
                x = _table[(x ^ buffer[offset + i]) & 0xFF] ^ (x >> 8);
            }

            return(NetworkConverter.GetBytes(x ^ 0xFFFFFFFF));
        }
Beispiel #20
0
            public override Stream Export(BufferManager bufferManager)
            {
                using (DeadlockMonitor.Lock(this.ThisLock))
                {
                    List <Stream> streams  = new List <Stream>();
                    Encoding      encoding = new UTF8Encoding(false);

                    // Name
                    if (this.Name != null)
                    {
                        BufferStream bufferStream = new BufferStream(bufferManager);
                        bufferStream.SetLength(5);
                        bufferStream.Seek(5, SeekOrigin.Begin);

                        using (CacheStream cacheStream = new CacheStream(bufferStream, 1024, true, bufferManager))
                            using (StreamWriter writer = new StreamWriter(cacheStream, encoding))
                            {
                                writer.Write(this.Name);
                            }

                        bufferStream.Seek(0, SeekOrigin.Begin);
                        bufferStream.Write(NetworkConverter.GetBytes((int)bufferStream.Length - 5), 0, 4);
                        bufferStream.WriteByte((byte)SerializeId.Name);

                        streams.Add(bufferStream);
                    }
                    // State
                    if (this.State != 0)
                    {
                        BufferStream bufferStream = new BufferStream(bufferManager);
                        bufferStream.SetLength(5);
                        bufferStream.Seek(5, SeekOrigin.Begin);

                        using (CacheStream cacheStream = new CacheStream(bufferStream, 1024, true, bufferManager))
                            using (StreamWriter writer = new StreamWriter(cacheStream, encoding))
                            {
                                writer.Write(this.State.ToString());
                            }

                        bufferStream.Seek(0, SeekOrigin.Begin);
                        bufferStream.Write(NetworkConverter.GetBytes((int)bufferStream.Length - 5), 0, 4);
                        bufferStream.WriteByte((byte)SerializeId.State);

                        streams.Add(bufferStream);
                    }
                    // Managers
                    foreach (var m in this.Managers)
                    {
                        BufferStream bufferStream = new BufferStream(bufferManager);
                        bufferStream.Write(NetworkConverter.GetBytes((int)m.Length), 0, 4);
                        bufferStream.WriteByte((byte)SerializeId.Manager);
                        bufferStream.Write(m, 0, m.Length);

                        streams.Add(bufferStream);
                    }
                    // Members
                    foreach (var m in this.Members)
                    {
                        BufferStream bufferStream = new BufferStream(bufferManager);
                        bufferStream.Write(NetworkConverter.GetBytes((int)m.Length), 0, 4);
                        bufferStream.WriteByte((byte)SerializeId.Member);
                        bufferStream.Write(m, 0, m.Length);

                        streams.Add(bufferStream);
                    }

                    return(new AddStream(streams));
                }
            }
Beispiel #21
0
        protected override Stream Export(BufferManager bufferManager, int count)
        {
            //if (count > 256) throw new ArgumentException();

            lock (this.ThisLock)
            {
                List <Stream> streams  = new List <Stream>();
                Encoding      encoding = new UTF8Encoding(false);

                // Name
                if (this.Name != null)
                {
                    BufferStream bufferStream = new BufferStream(bufferManager);
                    bufferStream.WriteByte((byte)SerializeId.Name);

                    bufferStream.SetLength(5);
                    bufferStream.Seek(5, SeekOrigin.Begin);

                    using (WrapperStream wrapperStream = new WrapperStream(bufferStream, true))
                        using (StreamWriter writer = new StreamWriter(wrapperStream, encoding))
                        {
                            writer.Write(this.Name);
                        }

                    bufferStream.Seek(0, SeekOrigin.Begin);
                    bufferStream.Write(NetworkConverter.GetBytes((int)bufferStream.Length - 5), 1, 4);

                    streams.Add(bufferStream);
                }
                // CreationTime
                if (this.CreationTime != DateTime.MinValue)
                {
                    BufferStream bufferStream = new BufferStream(bufferManager);
                    bufferStream.WriteByte((byte)SerializeId.CreationTime);

                    bufferStream.SetLength(5);
                    bufferStream.Seek(5, SeekOrigin.Begin);

                    using (WrapperStream wrapperStream = new WrapperStream(bufferStream, true))
                        using (StreamWriter writer = new StreamWriter(wrapperStream, encoding))
                        {
                            writer.Write(this.CreationTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ", System.Globalization.DateTimeFormatInfo.InvariantInfo));
                        }

                    bufferStream.Seek(0, SeekOrigin.Begin);
                    bufferStream.Write(NetworkConverter.GetBytes((int)bufferStream.Length - 5), 1, 4);

                    streams.Add(bufferStream);
                }
                // Comment
                if (this.Comment != null)
                {
                    BufferStream bufferStream = new BufferStream(bufferManager);
                    bufferStream.WriteByte((byte)SerializeId.Comment);

                    bufferStream.SetLength(5);
                    bufferStream.Seek(5, SeekOrigin.Begin);

                    using (WrapperStream wrapperStream = new WrapperStream(bufferStream, true))
                        using (StreamWriter writer = new StreamWriter(wrapperStream, encoding))
                        {
                            writer.Write(this.Comment);
                        }

                    bufferStream.Seek(0, SeekOrigin.Begin);
                    bufferStream.Write(NetworkConverter.GetBytes((int)bufferStream.Length - 5), 1, 4);

                    streams.Add(bufferStream);
                }
                // Seeds
                foreach (var s in this.Seeds)
                {
                    Stream exportStream = s.Export(bufferManager);

                    BufferStream bufferStream = new BufferStream(bufferManager);
                    bufferStream.WriteByte((byte)SerializeId.Seed);
                    bufferStream.Write(NetworkConverter.GetBytes((int)exportStream.Length), 0, 4);

                    streams.Add(new UniteStream(bufferStream, exportStream));
                }
                // D_Boxes
                foreach (var b in this.D_Boxes)
                {
                    Stream exportStream = b.Export(bufferManager, count + 1);

                    BufferStream bufferStream = new BufferStream(bufferManager);
                    bufferStream.WriteByte((byte)SerializeId.D_Box);
                    bufferStream.Write(NetworkConverter.GetBytes((int)exportStream.Length), 0, 4);

                    streams.Add(new UniteStream(bufferStream, exportStream));
                }

                // Certificate
                if (this.Certificate != null)
                {
                    Stream exportStream = this.Certificate.Export(bufferManager);

                    BufferStream bufferStream = new BufferStream(bufferManager);
                    bufferStream.WriteByte((byte)SerializeId.Certificate);
                    bufferStream.Write(NetworkConverter.GetBytes((int)exportStream.Length), 0, 4);

                    streams.Add(new UniteStream(bufferStream, exportStream));
                }

                return(new UniteStream(streams));
            }
        }
Beispiel #22
0
        public override void Send(Stream stream, TimeSpan timeout, Information options)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(this.GetType().FullName);
            }
            if (!_connect)
            {
                throw new ConnectionException();
            }
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            if (stream.Length == 0)
            {
                throw new ArgumentOutOfRangeException("stream");
            }

            lock (_sendLock)
            {
                using (RangeStream targetStream = new RangeStream(stream, stream.Position, stream.Length - stream.Position, true))
                {
                    try
                    {
                        _sendStopwatch.Restart();

                        Stream headerStream = new BufferStream(_bufferManager);
                        headerStream.Write(NetworkConverter.GetBytes((int)targetStream.Length), 0, 4);

                        byte[] sendBuffer = null;

                        try
                        {
                            sendBuffer = _bufferManager.TakeBuffer(1024 * 4);

                            using (Stream dataStream = new UniteStream(headerStream, new WrapperStream(targetStream, true)))
                            {
                                for (; ;)
                                {
                                    int sendLength = (int)Math.Min(dataStream.Length - dataStream.Position, sendBuffer.Length);
                                    if (sendLength == 0)
                                    {
                                        break;
                                    }

                                    if (_bandwidthLimit != null)
                                    {
                                        sendLength = _bandwidthLimit.GetOutBandwidth(this, sendLength);
                                        if (sendLength < 0)
                                        {
                                            throw new ConnectionException();
                                        }
                                    }

                                    dataStream.Read(sendBuffer, 0, sendLength);

                                    var time = BaseConnection.CheckTimeout(_sendStopwatch.Elapsed, timeout);
                                    time = (time < _sendTimeSpan) ? time : _sendTimeSpan;

                                    _cap.Send(sendBuffer, 0, sendLength, time);

                                    _aliveStopwatch.Restart();
                                    _sentByteCount.Add(sendLength);
                                }
                            }
                        }
                        finally
                        {
                            _bufferManager.ReturnBuffer(sendBuffer);
                        }

                        _aliveTimer.Change(1000 * 30);
                    }
                    catch (ConnectionException e)
                    {
                        throw e;
                    }
                    catch (Exception e)
                    {
                        throw new ConnectionException(e.Message, e);
                    }
                }
            }
        }
Beispiel #23
0
 public static void Write(Stream stream, byte type, byte[] value)
 {
     stream.WriteByte(type);
     stream.Write(NetworkConverter.GetBytes((int)value.Length), 0, 4);
     stream.Write(value, 0, value.Length);
 }
Beispiel #24
0
 public static void Write(Stream stream, byte type, long value)
 {
     stream.WriteByte(type);
     stream.Write(NetworkConverter.GetBytes((int)8), 0, 4);
     stream.Write(NetworkConverter.GetBytes(value), 0, 8);
 }
Beispiel #25
0
 public override string ToString()
 {
     return(new IPAddress(NetworkConverter.GetBytes(this.Value)).ToString());
 }
Beispiel #26
0
        public override void Send(Stream stream, TimeSpan timeout, Information options)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(this.GetType().FullName);
            }
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            if (stream.Length == 0)
            {
                throw new ArgumentOutOfRangeException("stream");
            }
            if (!_connect)
            {
                throw new ConnectionException();
            }

            lock (_sendLock)
            {
                try
                {
                    using (RangeStream targetStream = new RangeStream(stream, stream.Position, stream.Length - stream.Position, true))
                    {
                        if (_version.HasFlag(SecureConnectionVersion.Version3))
                        {
                            using (BufferStream bufferStream = new BufferStream(_bufferManager))
                            {
                                bufferStream.SetLength(8);
                                bufferStream.Seek(8, SeekOrigin.Begin);

                                if (_informationVersion3.CryptoAlgorithm.HasFlag(SecureVersion3.CryptoAlgorithm.Aes256))
                                {
                                    byte[] iv = new byte[16];
                                    _random.GetBytes(iv);
                                    bufferStream.Write(iv, 0, iv.Length);

                                    using (var aes = Aes.Create())
                                    {
                                        aes.KeySize = 256;
                                        aes.Mode    = CipherMode.CBC;
                                        aes.Padding = PaddingMode.PKCS7;

                                        using (CryptoStream cs = new CryptoStream(new WrapperStream(bufferStream, true), aes.CreateEncryptor(_informationVersion3.MyCryptoKey, iv), CryptoStreamMode.Write))
                                        {
                                            byte[] sendBuffer = null;

                                            try
                                            {
                                                sendBuffer = _bufferManager.TakeBuffer(1024 * 4);

                                                int i = -1;

                                                while ((i = targetStream.Read(sendBuffer, 0, sendBuffer.Length)) > 0)
                                                {
                                                    cs.Write(sendBuffer, 0, i);
                                                }
                                            }
                                            finally
                                            {
                                                if (sendBuffer != null)
                                                {
                                                    _bufferManager.ReturnBuffer(sendBuffer);
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    throw new ConnectionException();
                                }

                                _totalSendSize += (bufferStream.Length - 8);

                                bufferStream.Seek(0, SeekOrigin.Begin);

                                byte[] totalSendSizeBuff = NetworkConverter.GetBytes(_totalSendSize);
                                bufferStream.Write(totalSendSizeBuff, 0, totalSendSizeBuff.Length);

                                if (_informationVersion3.HashAlgorithm.HasFlag(SecureVersion3.HashAlgorithm.Sha256))
                                {
                                    bufferStream.Seek(0, SeekOrigin.Begin);
                                    byte[] hmacBuff = HmacSha256.ComputeHash(bufferStream, _informationVersion3.MyHmacKey);

                                    bufferStream.Seek(0, SeekOrigin.End);
                                    bufferStream.Write(hmacBuff, 0, hmacBuff.Length);
                                }
                                else
                                {
                                    throw new ConnectionException();
                                }

                                bufferStream.Seek(0, SeekOrigin.Begin);

                                _connection.Send(bufferStream, timeout, options);
                            }
                        }
                        else
                        {
                            throw new ConnectionException();
                        }
                    }
                }
                catch (ConnectionException e)
                {
                    throw e;
                }
                catch (Exception e)
                {
                    throw new ConnectionException(e.Message, e);
                }
            }
        }
Beispiel #27
0
        private static Stream Encrypt(Stream stream, IExchangeEncrypt publicKey)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            if (publicKey == null)
            {
                throw new ArgumentNullException("publicKey");
            }

            try
            {
                BufferStream outStream = null;

                try
                {
                    outStream = new BufferStream(_bufferManager);
                    outStream.WriteByte((byte)ConvertCryptoAlgorithm.Aes256);

                    byte[] cryptoKey = new byte[32];
                    _random.GetBytes(cryptoKey);

                    {
                        var encryptedBuffer = Exchange.Encrypt(publicKey, cryptoKey);
                        outStream.Write(NetworkConverter.GetBytes((int)encryptedBuffer.Length), 0, 4);
                        outStream.Write(encryptedBuffer, 0, encryptedBuffer.Length);
                    }

                    byte[] iv = new byte[32];
                    _random.GetBytes(iv);
                    outStream.Write(iv, 0, iv.Length);

                    using (Stream inStream = new WrapperStream(stream, true))
                    {
                        using (var rijndael = new RijndaelManaged()
                        {
                            KeySize = 256, BlockSize = 256, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7
                        })
                            using (CryptoStream cs = new CryptoStream(inStream, rijndael.CreateEncryptor(cryptoKey, iv), CryptoStreamMode.Read))
                            {
                                byte[] buffer = null;

                                try
                                {
                                    buffer = _bufferManager.TakeBuffer(1024 * 4);

                                    int i = -1;

                                    while ((i = cs.Read(buffer, 0, buffer.Length)) > 0)
                                    {
                                        outStream.Write(buffer, 0, i);
                                    }
                                }
                                finally
                                {
                                    if (buffer != null)
                                    {
                                        _bufferManager.ReturnBuffer(buffer);
                                    }
                                }
                            }
                    }

                    outStream.Seek(0, SeekOrigin.Begin);
                }
                catch (Exception)
                {
                    if (outStream != null)
                    {
                        outStream.Dispose();
                    }

                    throw;
                }

                return(outStream);
            }
            catch (Exception e)
            {
                throw new ArgumentException(e.Message, e);
            }
        }