Пример #1
0
        public void AuthServiceMsgs_Msg_AuthMsgAndAck()
        {
            EnhancedStream       es = new EnhancedMemoryStream();
            AuthMsg              authMsgIn, authMsgOut;
            AuthAck              authAckIn, authAckOut;
            string               rsaKey = AsymmetricCrypto.CreatePrivateKey(CryptoAlgorithm.RSA, 1024);
            SymmetricKey         saClient, saServer;
            string               r, a, p;
            AuthenticationResult authResult;

            authMsgOut = new AuthMsg(AuthMsg.EncryptCredentials(rsaKey, "realm", "account", "password", out saClient));

            Msg.Save(es, authMsgOut);
            es.Position = 0;
            authMsgIn   = (AuthMsg)Msg.Load(es);

            AuthMsg.DecryptCredentials(rsaKey, authMsgIn.EncryptedCredentials, out r, out a, out p, out saServer);

            Assert.AreEqual("realm", r);
            Assert.AreEqual("account", a);
            Assert.AreEqual("password", p);

            authAckOut = new AuthAck(AuthAck.EncryptResult(saServer, new AuthenticationResult(AuthenticationStatus.Authenticated, "Test", TimeSpan.FromMinutes(25))));

            es.SetLength(0);
            Msg.Save(es, authAckOut);
            es.Position = 0;
            authAckIn   = (AuthAck)Msg.Load(es);

            authResult = AuthAck.DecryptResult(saClient, authAckIn.EncryptedResult);
        }
Пример #2
0
        public void SecureFile_Stream_Validate()
        {
            string privateKey              = AsymmetricCrypto.CreatePrivateKey(CryptoAlgorithm.RSA, 1024);
            string publicKey               = AsymmetricCrypto.GetPublicKey(CryptoAlgorithm.RSA, privateKey);
            EnhancedMemoryStream original  = new EnhancedMemoryStream();
            EnhancedMemoryStream encrypted = new EnhancedMemoryStream();
            SecureFile           secure    = null;
            byte b;

            for (int i = 0; i < 100; i++)
            {
                original.WriteByte((byte)i);
            }

            secure            = new SecureFile(original, SecureFileMode.Encrypt, publicKey);
            original.Position = 0;
            secure.EncryptTo(encrypted, CryptoAlgorithm.AES, 256);
            secure.Close();
            secure = null;

            encrypted.Position = 0;
            Assert.IsTrue(SecureFile.Validate(encrypted, privateKey));

            encrypted.Position = encrypted.Length - 1;
            b = (byte)encrypted.ReadByte();
            encrypted.Position = encrypted.Length - 1;
            encrypted.WriteByte((byte)(~b));

            encrypted.Position = 0;
            Assert.IsFalse(SecureFile.Validate(encrypted, privateKey));
        }
Пример #3
0
        public void AuthServiceMsgs_Msg_AuthControlMsg()
        {
            EnhancedStream es = new EnhancedMemoryStream();
            AuthControlMsg msgIn, msgOut;

            msgOut = new AuthControlMsg("my command", "a=test1;b=test2;c=test3");

            Msg.Save(es, msgOut);
            es.Position = 0;
            msgIn       = (AuthControlMsg)Msg.Load(es);

            Assert.AreEqual("my command", msgIn.Command);
            Assert.AreEqual("test1", msgIn.Get("a", null));
            Assert.AreEqual("test2", msgIn.Get("b", null));
            Assert.AreEqual("test3", msgIn.Get("c", null));
            Assert.AreEqual("foobar", msgIn.Get("d", "foobar"));

            msgOut = new AuthControlMsg("hello", null);

            Msg.Save(es, msgOut);
            es.Position = 0;
            msgIn       = (AuthControlMsg)Msg.Load(es);

            Assert.AreEqual("my command", msgIn.Command);
        }
Пример #4
0
        public void SecureFile_Stream_LargeContent()
        {
            string privateKey              = AsymmetricCrypto.CreatePrivateKey(CryptoAlgorithm.RSA, 1024);
            string publicKey               = AsymmetricCrypto.GetPublicKey(CryptoAlgorithm.RSA, privateKey);
            EnhancedMemoryStream original  = new EnhancedMemoryStream();
            EnhancedMemoryStream encrypted = new EnhancedMemoryStream();
            EnhancedMemoryStream decrypted = new EnhancedMemoryStream();
            SecureFile           secure    = null;

            for (int i = 0; i < 128000; i++)
            {
                original.WriteByte((byte)i);
            }

            secure            = new SecureFile(original, SecureFileMode.Encrypt, publicKey);
            original.Position = 0;
            secure.EncryptTo(encrypted, CryptoAlgorithm.AES, 256);
            secure.Close();
            secure = null;

            encrypted.Position = 0;
            secure             = new SecureFile(encrypted, SecureFileMode.Decrypt, privateKey);
            secure.DecryptTo(decrypted);
            secure.Close();
            secure = null;

            original.Position  = 0;
            encrypted.Position = 0;
            CollectionAssert.AreNotEqual(original.ReadBytesToEnd(), encrypted.ReadBytesToEnd());

            original.Position  = 0;
            decrypted.Position = 0;
            CollectionAssert.AreEqual(original.ReadBytesToEnd(), decrypted.ReadBytesToEnd());
        }
Пример #5
0
        public void SecureFile_Stream_NoContent()
        {
            string privateKey              = AsymmetricCrypto.CreatePrivateKey(CryptoAlgorithm.RSA, 1024);
            string publicKey               = AsymmetricCrypto.GetPublicKey(CryptoAlgorithm.RSA, privateKey);
            EnhancedMemoryStream original  = new EnhancedMemoryStream();
            EnhancedMemoryStream encrypted = new EnhancedMemoryStream();
            EnhancedMemoryStream decrypted = new EnhancedMemoryStream();
            SecureFile           secure    = null;

            secure            = new SecureFile(original, SecureFileMode.Encrypt, publicKey);
            original.Position = 0;
            secure.EncryptTo(encrypted, CryptoAlgorithm.AES, 256);
            secure.Close();
            secure = null;

            original.Position  = 0;
            encrypted.Position = 0;
            Assert.AreNotEqual(original.ReadBytesToEnd(), encrypted.ReadBytesToEnd());

            encrypted.Position = 0;
            secure             = new SecureFile(encrypted, SecureFileMode.Decrypt, privateKey);
            secure.DecryptTo(decrypted);
            secure.Close();
            secure = null;

            Assert.AreEqual(0, decrypted.Length);
        }
Пример #6
0
        public void Package_AutoAddFolders()
        {
            Package package;
            EnhancedMemoryStream es = new EnhancedMemoryStream();
            PackageEntry         entry;

            //-------------------------

            package = new Package();
            package.Create(es);

            entry = package.AddFile("/Foo/Bar/Test1.dat", new byte[] { 1, 1, 1, 1 });
            Assert.IsTrue(entry.IsFile);
            Assert.IsTrue(package["/Foo"].IsFolder);
            Assert.IsTrue(package["/Foo/Bar"].IsFolder);
            Assert.IsTrue(package["/Foo/Bar/Test1.dat"].IsFile);

            package.Close(true);

            //-------------------------

            es.Position = 0;
            package     = new Package(es);

            Assert.IsTrue(entry.IsFile);
            Assert.IsTrue(package["/Foo"].IsFolder);
            Assert.IsTrue(package["/Foo/Bar"].IsFolder);
            Assert.IsTrue(package["/Foo/Bar/Test1.dat"].IsFile);
            CollectionAssert.AreEqual(new byte[] { 1, 1, 1, 1 }, package["/Foo/Bar/Test1.dat"].GetContents());

            package.Close();
        }
Пример #7
0
        public void Package_Empty()
        {
            Package              package;
            PackageEntry         root;
            EnhancedMemoryStream es = new EnhancedMemoryStream();

            //-------------------------

            package = new Package();
            package.Create(es);

            root = package.RootFolder;
            Assert.IsNotNull(root);
            Assert.IsNull(root.Parent);
            Assert.AreSame(root, package["/"]);
            Assert.IsNull(root["foo"]);
            Assert.IsTrue(root.IsFolder);
            Assert.AreEqual(0, root.Children.Length);
            Assert.AreEqual("/", root.FullName);
            Assert.AreEqual("", root.Name);

            package.Close(true);

            //-------------------------

            es.Position = 0;
            package     = new Package(es);
            Assert.IsNotNull(root);
            root = package.RootFolder;
            Assert.AreSame(root, package["/"]);
            Assert.IsNull(root["foo"]);
            Assert.AreEqual(0, root.Children.Length);

            package.Close();
        }
Пример #8
0
        public void MailHelper_MessageSerializeBasic()
        {
            MailMessage          message;
            EnhancedMemoryStream stream;

            // Write

            message            = new MailMessage("*****@*****.**", "*****@*****.**");
            message.From       = new MailAddress("*****@*****.**");
            message.Subject    = "Test Message";
            message.IsBodyHtml = true;
            message.Body       = "<html><body>Test</body></html>";

            stream = new EnhancedMemoryStream();
            MailHelper.WriteMessage(stream, message);

            // Read

            stream.Position = 0;
            message         = MailHelper.ReadMessage(stream);

            Assert.AreEqual("*****@*****.**", message.From.ToString());
            Assert.AreEqual(1, message.To.Count);
            Assert.AreEqual("*****@*****.**", message.To[0].ToString());

            Assert.AreEqual("Test Message", message.Subject);
            Assert.IsTrue(message.IsBodyHtml);
            Assert.AreEqual("<html><body>Test</body></html>", message.Body);
        }
Пример #9
0
        public void SentinelServiceMsgs_LogEventMsg_Serialize()
        {
            LogEventMsg    msgIn, msgOut;
            EnhancedStream es  = new EnhancedMemoryStream();
            EventLog       log = new EventLog("Application");
            EventLogEntry  entry;

            // Clear the log and then add an entry so we can retrieve it right
            // away (hopefully getting the same entry back).

            log.Source = "Application";
            log.Clear();
            log.WriteEntry("Test entry", EventLogEntryType.Information, 0, 0, new byte[] { 0, 1, 2, 3 });
            entry = log.Entries[0];

            msgOut = new LogEventMsg("Application", entry);

            Msg.Save(es, msgOut);
            es.Seek(0, SeekOrigin.Begin);
            msgIn = (LogEventMsg)Msg.Load(es);

            Assert.AreEqual("Application", msgIn.LogName);
            Assert.AreEqual(entry.EntryType, msgIn.EntryType);
            Assert.AreEqual(entry.TimeGenerated.ToUniversalTime(), msgIn.Time);
            Assert.AreEqual(entry.MachineName, msgIn.MachineName);
            Assert.AreEqual(entry.Message, msgIn.Message);
            CollectionAssert.AreEqual(new byte[] { 0, 1, 2, 3 }, msgIn.Data);
        }
Пример #10
0
        /// <summary>
        /// Constructs an instance by parsing a serialized string.
        /// </summary>
        /// <param name="serialized">The serialized visitor information.</param>
        /// <exception cref="ArgumentNullException">Thrown if <c>null</c> is passed.</exception>
        /// <exception cref="ArgumentException">Thrown if the parameter passed does not represent a valid <see cref="UniqueVisitor" /> instance.</exception>
        /// <remarks>
        /// <para>
        /// The <paramref name="serialized" /> value must have been generated by
        /// a previous call to <see cref="ToString" />.
        /// </para>
        /// </remarks>
        public UniqueVisitor(string serialized)
        {
            if (serialized == null)
            {
                throw new ArgumentNullException("serialized");
            }

            try
            {
                using (var ms = new EnhancedMemoryStream(Convert.FromBase64String(serialized)))
                {
                    if (ms.ReadInt16() != Magic)
                    {
                        throw new FormatException("Bad magic number.");
                    }

                    this.IssueDateUtc = new DateTime(ms.ReadInt64(), DateTimeKind.Utc);
                    this.ID           = new Guid(ms.ReadBytes(32));
                }
            }
            catch (Exception e)
            {
                throw new ArgumentException("Invalid unique serialized visitor.", "seralized", e);
            }
        }
Пример #11
0
        public void Msg_Serialize_RouteAdvertiseMsg()
        {
            RouterAdvertiseMsg msgIn, msgOut;
            EnhancedStream     es = new EnhancedMemoryStream();

            Msg.ClearTypes();
            Msg.LoadTypes(Assembly.GetExecutingAssembly());

            msgOut = new RouterAdvertiseMsg(MsgEP.Parse("physical://root.com:80/hub/leaf"), "appname", "appdescription",
                                            new MsgRouterInfo(new Version(1000, 0)), 10, 20, Helper.NewGuid(), false, true);
            msgOut._FromEP = MsgEP.Parse("physical://root.com:80/hub/leaf?c=mcast://1.2.3.4:57");

            Msg.Save(es, msgOut);
            es.Seek(0, SeekOrigin.Begin);
            msgIn = (RouterAdvertiseMsg)Msg.Load(es);

            Assert.AreEqual("physical://root.com:80/hub/leaf", msgIn.RouterEP.ToString());
            Assert.AreEqual("appname", msgIn.AppName);
            Assert.AreEqual("appdescription", msgIn.AppDescription);
            Assert.AreEqual(new Version(1000, 0), msgIn.RouterInfo.ProtocolVersion);
            Assert.AreEqual(IPAddress.Parse("1.2.3.4"), msgIn.IPAddress);
            Assert.AreEqual(10, msgIn.UdpPort);
            Assert.AreEqual(20, msgIn.TcpPort);
            Assert.AreEqual(msgOut.LogicalEndpointSetID, msgIn.LogicalEndpointSetID);
            Assert.IsFalse(msgIn.ReplyAdvertise);
            Assert.IsTrue(msgIn.DiscoverLogical);
            Assert.IsTrue(msgIn.RouterInfo.IsP2P);
        }
Пример #12
0
        /// <summary>
        /// Decrypts authentication <see cref="Credentials" /> from a
        /// byte array using the specified public asymmetric private key and
        /// algorithm.
        /// </summary>
        /// <param name="encrypted">The encrypted credential bytes.</param>
        /// <param name="algorithm">The encryption algorithm.</param>
        /// <param name="key">The private key.</param>
        /// <returns>The decrypted <see cref="Credentials" />.</returns>
        /// <remarks>
        /// <note>
        /// The current implementation supports only the "RSA" provider.
        /// </note>
        /// </remarks>
        /// <exception cref="SecurityException">Thrown if the credentials are corrupt.</exception>
        public static Credentials DecryptCredentials(byte[] encrypted, string algorithm, string key)
        {
            try
            {
                var decrypted = Decrypt(algorithm, key, encrypted);

                using (var ms = new EnhancedMemoryStream(decrypted))
                {
                    string realm;
                    string account;
                    string password;

                    if (ms.ReadInt32() != Crypto.CredentialMagic)
                    {
                        throw new SecurityException(Crypto.CorruptCredentialsMsg);
                    }

                    realm    = ms.ReadString16();
                    account  = ms.ReadString16();
                    password = ms.ReadString16();

                    return(new Credentials(realm, account, password));
                }
            }
            catch (Exception e)
            {
                throw new SecurityException(Crypto.CorruptCredentialsMsg, e);
            }
        }
Пример #13
0
        public void ClusterMemberMsg_Basic()
        {
            EnhancedStream   es = new EnhancedMemoryStream();
            ClusterMemberMsg msgIn, msgOut;

            Msg.ClearTypes();
            Msg.LoadTypes(Assembly.GetExecutingAssembly());

            msgOut = new ClusterMemberMsg("logical://test", "my command");
            msgOut.ProtocolCaps = unchecked ((ClusterMemberProtocolCaps)0xFFFFFFFF);
            msgOut.Flags        = (ClusterMemberMsgFlag)0x7FFFFFFF;
            msgOut._Set("hello", "world!");
            msgOut._Data = new byte[] { 0, 1, 2, 3, 4, 5 };

            Msg.Save(es, msgOut);
            es.Position = 0;
            msgIn       = (ClusterMemberMsg)Msg.Load(es);

            Assert.IsNotNull(msgIn);
            Assert.AreEqual("logical://test", (string)msgIn.SenderEP);
            Assert.AreEqual(unchecked ((ClusterMemberProtocolCaps)0xFFFFFFFF), msgIn.ProtocolCaps);
            Assert.AreEqual((ClusterMemberMsgFlag)0x7FFFFFFF, msgIn.Flags);
            Assert.AreEqual("my command", msgIn.Command);
            Assert.AreEqual("world!", msgIn["hello"]);
            CollectionAssert.AreEqual(new byte[] { 0, 1, 2, 3, 4, 5 }, msgOut._Data);
        }
Пример #14
0
        /// <summary>
        /// Decrypts and deserializes a message from a byte buffer.
        /// </summary>
        /// <param name="buffer">The buffer.</param>
        /// <param name="sharedKey">The shared encryption key.</param>
        /// <exception cref="FormatException">Thrown if the buffer does not contain a valid message.</exception>
        public DynDnsMessage(byte[] buffer, SymmetricKey sharedKey)
        {
            try
            {
                using (var ms = new EnhancedMemoryStream(Crypto.Decrypt(buffer, sharedKey)))
                {
                    if (ms.ReadInt32Le() != Magic)
                    {
                        throw new Exception();
                    }

                    this.Version = ms.ReadByte();
                    if (this.Version < FormatVer)
                    {
                        throw new FormatException(string.Format("DynDnsMessage version [{0}] is not supported.", this.Version));
                    }

                    this.TimeStampUtc = new DateTime(ms.ReadInt64Le());
                    this.Flags        = (DynDnsMessageFlag)ms.ReadInt32Le();
                    this.HostEntry    = new DynDnsHostEntry(ms.ReadString16());
                }
            }
            catch (Exception e)
            {
                throw new FormatException("Invalid Dynamic DNS message.", e);
            }
        }
Пример #15
0
        public void Msg_Serialize_BaseMsg()
        {
            Msg            msg;
            EnhancedStream es = new EnhancedMemoryStream();

            Msg.ClearTypes();
            Msg.LoadTypes(Assembly.GetExecutingAssembly());

            msg          = new Msg();
            msg._Version = 77;
            msg._Flags  |= MsgFlag.Broadcast;
            es.SetLength(0);
            Msg.Save(es, msg);

            es.Seek(0, SeekOrigin.Begin);
            msg = (Msg)Msg.Load(es);
            Assert.IsNotNull(msg);
            Assert.AreEqual(77, msg._Version);
            Assert.AreEqual(MsgFlag.Broadcast, msg._Flags);

            msg          = new Msg();
            msg._Version = 77;
            msg._Flags  |= MsgFlag.Broadcast | MsgFlag.OpenSession;
            es.SetLength(0);
            Msg.Save(es, msg);

            es.Seek(0, SeekOrigin.Begin);
            msg = (Msg)Msg.Load(es);
            Assert.IsNotNull(msg);
            Assert.AreEqual(77, msg._Version);
            Assert.AreEqual(MsgFlag.Broadcast | MsgFlag.OpenSession, msg._Flags);
        }
Пример #16
0
        public void Msg_Serialize_SecurityToken()
        {
            Msg            msgIn, msgOut;
            EnhancedStream es = new EnhancedMemoryStream();

            Msg.ClearTypes();
            Msg.LoadTypes(Assembly.GetExecutingAssembly());

            msgOut = new Msg();
            Assert.IsNull(msgOut._SecurityToken);

            Msg.Save(es, msgOut);
            es.Seek(0, SeekOrigin.Begin);
            msgIn = Msg.Load(es);

            Assert.IsNull(msgOut._SecurityToken);

            msgOut._SecurityToken = new byte[] { 0, 1, 2, 3, 4 };

            es.SetLength(0);
            Msg.Save(es, msgOut);
            es.Seek(0, SeekOrigin.Begin);
            msgIn = Msg.Load(es);

            CollectionAssert.AreEqual(msgOut._SecurityToken, msgIn._SecurityToken);
        }
Пример #17
0
        public void Msg_Serialize_Guids()
        {
            Msg            msgIn, msgOut;
            EnhancedStream es = new EnhancedMemoryStream();

            Msg.ClearTypes();
            Msg.LoadTypes(Assembly.GetExecutingAssembly());

            msgOut = new Msg();
            Assert.AreEqual(Guid.Empty, msgOut._MsgID);
            Assert.AreEqual(Guid.Empty, msgOut._SessionID);

            Msg.Save(es, msgOut);
            es.Seek(0, SeekOrigin.Begin);
            msgIn = Msg.Load(es);

            Assert.AreEqual(Guid.Empty, msgIn._MsgID);
            Assert.AreEqual(Guid.Empty, msgIn._SessionID);

            msgOut._MsgID     = Helper.NewGuid();
            msgOut._SessionID = Helper.NewGuid();

            es.SetLength(0);
            Msg.Save(es, msgOut);
            es.Seek(0, SeekOrigin.Begin);
            msgIn = Msg.Load(es);

            Assert.AreEqual(msgOut._MsgID, msgIn._MsgID);
            Assert.AreEqual(msgOut._SessionID, msgIn._SessionID);
        }
Пример #18
0
        public void EnhancedMemoryStream_Bytes32()
        {
            var es = new EnhancedMemoryStream();

            byte[] read, write;

            es.WriteBytes32(null);
            es.Seek(0, SeekOrigin.Begin);
            read = es.ReadBytes32();
            Assert.IsNull(read);

            write = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            es.Seek(0, SeekOrigin.Begin);
            es.WriteBytes32(write);
            es.Seek(0, SeekOrigin.Begin);
            read = es.ReadBytes32();
            CollectionAssert.AreEqual(write, read);

            write = new byte[40000];
            for (int i = 0; i < write.Length; i++)
            {
                write[i] = (byte)i;
            }

            es.Seek(0, SeekOrigin.Begin);
            es.WriteBytes32(write);
            es.Seek(0, SeekOrigin.Begin);
            read = es.ReadBytes32();
            CollectionAssert.AreEqual(write, read);
        }
Пример #19
0
        public void ReliableTransferMsg_Basic()
        {
            EnhancedStream      es = new EnhancedMemoryStream();
            ReliableTransferMsg msgIn, msgOut;
            Guid id = Helper.NewGuid();

            Msg.ClearTypes();
            Msg.LoadTypes(Assembly.GetExecutingAssembly());

            msgOut            = new ReliableTransferMsg(ReliableTransferMsg.ErrorCmd);
            msgOut.Direction  = TransferDirection.Download;
            msgOut.TransferID = id;
            msgOut.Args       = "Hello";
            msgOut.BlockData  = new byte[] { 0, 1, 2, 3, 4 };
            msgOut.BlockIndex = 10;
            msgOut.BlockSize  = 1024;
            msgOut.Exception  = "Error";

            Msg.Save(es, msgOut);
            es.Position = 0;
            msgIn       = (ReliableTransferMsg)Msg.Load(es);

            Assert.IsNotNull(msgIn);
            Assert.AreEqual(TransferDirection.Download, msgIn.Direction);
            Assert.AreEqual(id, msgIn.TransferID);
            Assert.AreEqual("Hello", msgIn.Args);
            CollectionAssert.AreEqual(new byte[] { 0, 1, 2, 3, 4 }, msgIn.BlockData);
            Assert.AreEqual(10, msgIn.BlockIndex);
            Assert.AreEqual(1024, msgIn.BlockSize);
            Assert.AreEqual("Error", msgIn.Exception);
        }
Пример #20
0
        /// <summary>
        /// Constructs a key chain by decrypting bytes returned by a previous
        /// call to <see cref="Encrypt" />.
        /// </summary>
        /// <param name="key">The <see cref="SymmetricKey" /> to be used for decrypting.</param>
        /// <param name="encrypted">The encrypted key chain.</param>
        /// <exception cref="CryptographicException">Thrown if the decrypted key chain is malformed.</exception>
        public KeyChain(SymmetricKey key, byte[] encrypted)
        {
            try
            {
                using (var ms = new EnhancedMemoryStream(Crypto.Decrypt(encrypted, key)))
                {
                    if (ms.ReadInt32() != Magic)
                    {
                        throw new Exception();
                    }

                    int count;

                    count = ms.ReadInt32();
                    keys  = new Dictionary <string, string>(count);

                    for (int i = 0; i < count; i++)
                    {
                        Add(ms.ReadString16());
                    }
                }
            }
            catch (Exception e)
            {
                throw new CryptographicException("Key chain is malformed.", e);
            }
        }
Пример #21
0
        public void BlobPropertyMsg_SerializeBase()
        {
            _BlobPropMsg         msgOut, msgIn;
            EnhancedMemoryStream ms = new EnhancedMemoryStream();

            Msg.ClearTypes();
            Msg.LoadTypes(Assembly.GetExecutingAssembly());

            msgOut = new _BlobPropMsg();
            msgOut._Set("string", "hello");
            msgOut._Set("bool", true);
            msgOut._Set("int", 10);
            msgOut._Set("timespan", new TimeSpan(0, 0, 0, 0, 55));
            msgOut._Set("endpoint", new IPEndPoint(IPAddress.Parse("127.0.0.1"), 56));
            msgOut._Set("bytes", new byte[] { 5, 6, 7, 8 });
            msgOut._Data = new byte[] { 0, 1, 2 };
            msgOut.Value = "foobar";

            Msg.Save(ms, msgOut);

            ms.Seek(0, SeekOrigin.Begin);
            msgIn = (_BlobPropMsg)Msg.Load(ms);

            Assert.AreEqual(msgOut["string"], msgIn["string"]);
            Assert.AreEqual(msgOut["bool"], msgIn["bool"]);
            Assert.AreEqual(msgOut["int"], msgIn["int"]);
            Assert.AreEqual(msgOut["timespan"], msgIn["timespan"]);
            Assert.AreEqual(msgOut["endpoint"], msgIn["endpoint"]);
            Assert.AreEqual(msgOut["bytes"], msgIn["bytes"]);
            CollectionAssert.AreEqual(msgOut._Data, msgIn._Data);
            Assert.AreEqual("foobar", msgIn.Value);
        }
Пример #22
0
        public void PropertyMsg_Serialize()
        {
            PropertyMsg          msgOut, msgIn;
            EnhancedMemoryStream ms = new EnhancedMemoryStream();

            Msg.ClearTypes();
            Msg.LoadTypes(Assembly.GetExecutingAssembly());

            msgOut = new PropertyMsg();
            msgOut._Set("string", "hello");
            msgOut._Set("bool", true);
            msgOut._Set("int", 10);
            msgOut._Set("timespan", new TimeSpan(0, 0, 0, 0, 55));
            msgOut._Set("endpoint", new IPEndPoint(IPAddress.Parse("127.0.0.1"), 56));
            msgOut._Set("bytes", new byte[] { 5, 6, 7, 8 });
            msgOut._Set("address", IPAddress.Parse("10.20.30.40"));

            Msg.Save(ms, msgOut);

            ms.Seek(0, SeekOrigin.Begin);
            msgIn = (PropertyMsg)Msg.Load(ms);

            Assert.AreEqual(msgOut["string"], msgIn["string"]);
            Assert.AreEqual(msgOut["bool"], msgIn["bool"]);
            Assert.AreEqual(msgOut["int"], msgIn["int"]);
            Assert.AreEqual(msgOut["timespan"], msgIn["timespan"]);
            Assert.AreEqual(msgOut["endpoint"], msgIn["endpoint"]);
            Assert.AreEqual(msgOut["bytes"], msgIn["bytes"]);
            Assert.AreEqual(msgOut["address"], msgIn["address"]);
        }
Пример #23
0
        public void Msg_Serialize_TestMsg()
        {
            _TestMsg2      msgIn, msgOut;
            EnhancedStream es = new EnhancedMemoryStream();

            Msg.ClearTypes();
            Msg.LoadTypes(Assembly.GetExecutingAssembly());

            msgOut             = new _TestMsg2();
            msgOut.BoolValue   = false;
            msgOut.ByteValue   = 0xAA;
            msgOut.BytesValue  = new byte[] { 0, 1, 2, 3 };
            msgOut.FloatValue  = 10.77F;
            msgOut.Int16Value  = 32000;
            msgOut.Int32Value  = 100000;
            msgOut.Int64Value  = 8000000000;
            msgOut.StringValue = "Hello World!";
            Msg.Save(es, msgOut);

            es.Seek(0, SeekOrigin.Begin);
            msgIn = (_TestMsg2)Msg.Load(es);
            Assert.AreEqual(msgOut.BoolValue, msgIn.BoolValue);
            Assert.AreEqual(msgOut.ByteValue, msgIn.ByteValue);
            CollectionAssert.AreEqual(msgOut.BytesValue, msgIn.BytesValue);
            Assert.AreEqual(msgOut.FloatValue, msgIn.FloatValue);
            Assert.AreEqual(msgOut.Int16Value, msgIn.Int16Value);
            Assert.AreEqual(msgOut.Int32Value, msgIn.Int32Value);
            Assert.AreEqual(msgOut.Int64Value, msgIn.Int64Value);
            Assert.AreEqual(msgOut.StringValue, msgIn.StringValue);

            Assert.AreEqual(0, msgIn._Version);
            Assert.IsNull(msgIn._ToEP);
            Assert.IsNull(msgIn._FromEP);
        }
Пример #24
0
        public void AppStoreMsgs_Ack()
        {
            EnhancedStream es = new EnhancedMemoryStream();

            AppPackageInfo[] packages = new AppPackageInfo[] {
                new AppPackageInfo(AppRef.Parse("appref://myapps/app01.zip?version=1.2.3.4"), "app01.zip", "", new byte[] { 0, 1, 2 }, 55, DateTime.MinValue),
                new AppPackageInfo(AppRef.Parse("appref://myapps/app02.zip?version=5.6.7.8"), "app02.zip", "", new byte[] { 3, 4, 5 }, 66, DateTime.MinValue)
            };

            AppStoreAck msgIn, msgOut;

            msgOut          = new AppStoreAck();
            msgOut.StoreEP  = "logical://foo/bar";
            msgOut.Packages = packages;

            Msg.Save(es, msgOut);
            es.Position = 0;
            msgIn       = (AppStoreAck)Msg.Load(es);

            Assert.IsNotNull(msgIn);
            Assert.AreEqual("logical://foo/bar", msgIn.StoreEP);

            Assert.AreEqual(2, msgIn.Packages.Length);

            Assert.AreEqual(AppRef.Parse("appref://myapps/app01.zip?version=1.2.3.4"), msgIn.Packages[0].AppRef);
            CollectionAssert.AreEqual(new byte[] { 0, 1, 2 }, msgIn.Packages[0].MD5);
            Assert.AreEqual(55, msgIn.Packages[0].Size);

            Assert.AreEqual(AppRef.Parse("appref://myapps/app02.zip?version=5.6.7.8"), msgIn.Packages[1].AppRef);
            CollectionAssert.AreEqual(new byte[] { 3, 4, 5 }, msgIn.Packages[1].MD5);
            Assert.AreEqual(66, msgIn.Packages[1].Size);
        }
Пример #25
0
        public void ReliableMessengerMsgs_DeliveryMsg_Serialize()
        {
            DeliveryMsg    msgIn, msgOut;
            EnhancedStream es  = new EnhancedMemoryStream();
            DateTime       now = Helper.UtcNowRounded;
            Guid           id  = Helper.NewGuid();
            PropertyMsg    query;
            PropertyMsg    response;

            Msg.ClearTypes();
            Msg.LoadTypes(Assembly.GetExecutingAssembly());

            query           = new PropertyMsg();
            query["hello"]  = "world";
            response        = new PropertyMsg();
            response["foo"] = "bar";

            msgOut = new DeliveryMsg(DeliveryOperation.Attempt, now, "logical://foo", "logical://bar", query, id,
                                     "clusterInfo", "clusterParam", new TimeoutException("Timeout"), response);
            Msg.Save(es, msgOut);
            es.Seek(0, SeekOrigin.Begin);
            msgIn = (DeliveryMsg)Msg.Load(es);

            Assert.IsNotNull(msgIn);
            Assert.AreEqual(DeliveryOperation.Attempt, msgIn.Operation);
            Assert.AreEqual(now, msgIn.Timestamp);
            Assert.AreEqual(MsgEP.Parse("logical://foo"), msgIn.TargetEP);
            Assert.AreEqual(MsgEP.Parse("logical://bar"), msgIn.ConfirmEP);
            Assert.IsInstanceOfType(msgIn.Query, typeof(PropertyMsg));
            Assert.AreEqual("world", ((PropertyMsg)msgIn.Query)["hello"]);
            Assert.AreEqual(id, msgIn.TopologyID);
            Assert.AreEqual("clusterInfo", msgIn.TopologyInfo);
            Assert.AreEqual("clusterParam", msgIn.TopologyParam);
            Assert.IsInstanceOfType(msgIn.Exception, typeof(TimeoutException));
            Assert.AreEqual("Timeout", msgIn.Exception.Message);
            Assert.IsInstanceOfType(msgIn.Response, typeof(PropertyMsg));
            Assert.AreEqual("bar", ((PropertyMsg)msgIn.Response)["foo"]);

            msgOut = new DeliveryMsg(DeliveryOperation.Confirmation, now, "logical://foo", null, query, id,
                                     null, null, new ArgumentException("Test"), null);
            es.SetLength(0);
            Msg.Save(es, msgOut);
            es.Seek(0, SeekOrigin.Begin);
            msgIn = (DeliveryMsg)Msg.Load(es);

            Assert.IsNotNull(msgIn);
            Assert.AreEqual(DeliveryOperation.Confirmation, msgIn.Operation);
            Assert.AreEqual(now, msgIn.Timestamp);
            Assert.AreEqual(MsgEP.Parse("logical://foo"), msgIn.TargetEP);
            Assert.IsNull(msgIn.ConfirmEP);
            Assert.IsInstanceOfType(msgIn.Query, typeof(PropertyMsg));
            Assert.AreEqual("world", ((PropertyMsg)msgIn.Query)["hello"]);
            Assert.AreEqual(id, msgIn.TopologyID);
            Assert.IsNull(msgIn.TopologyInfo);
            Assert.IsNull(msgIn.TopologyParam);
            Assert.IsInstanceOfType(msgIn.Exception, typeof(SessionException));
            Assert.AreEqual("Test", msgIn.Exception.Message);
            Assert.IsNull(msgIn.Response);
        }
Пример #26
0
        public void Hashers_MD5()
        {
            EnhancedMemoryStream ms;

            byte[] data;
            byte[] digest1, digest2;

            digest1 = MD5Hasher.Compute(new byte[] { 0, 1, 2, 3 }, 0, 4);
            Assert.AreEqual(16, digest1.Length);
            Assert.AreEqual(16, MD5Hasher.DigestSize);

            digest2 = MD5Hasher.Compute(new byte[] { 1, 1, 2, 3 }, 0, 4);
            Assert.AreNotEqual(digest1, digest2);

            digest1 = MD5Hasher.Compute(new byte[0]);
            Assert.AreEqual(16, digest1.Length);
            Assert.AreEqual(16, MD5Hasher.DigestSize);

            digest1 = MD5Hasher.Compute(new byte[] { 0, 1, 2, 3 });
            ms      = new EnhancedMemoryStream();

            ms.Seek(0, SeekOrigin.Begin);
            ms.Write(new byte[] { 0, 1, 2, 3 }, 0, 4);
            ms.Seek(0, SeekOrigin.Begin);
            digest2 = MD5Hasher.Compute(ms, 4);
            CollectionAssert.AreEqual(digest1, digest2);
            Assert.AreEqual(16, digest2.Length);
            Assert.AreEqual(0, ms.Position);

            data = new byte[2048];
            for (int i = 0; i < data.Length; i++)
            {
                data[i] = (byte)i;
            }

            digest1 = MD5Hasher.Compute(data);

            ms.Seek(0, SeekOrigin.Begin);
            ms.Write(data, 0, data.Length);
            ms.Seek(0, SeekOrigin.Begin);

            digest2 = MD5Hasher.Compute(ms, data.Length);
            CollectionAssert.AreEqual(digest1, digest2);
            Assert.AreEqual(16, digest2.Length);
            Assert.AreEqual(0, ms.Position);

            digest1 = MD5Hasher.Compute("hello");
            digest2 = MD5Hasher.Compute("world");
            CollectionAssert.AreNotEqual(digest1, digest2);
            CollectionAssert.AreEqual(digest1, MD5Hasher.Compute("hello"));

            // These really aren't very good tests for folding but
            // at least they'll verify that it doesn't crash

            Assert.AreEqual(MD5Hasher.FoldOnce(new byte[] { 0, 1, 2, 3 }), MD5Hasher.FoldOnce(new byte[] { 0, 1, 2, 3 }));
            Assert.AreNotEqual((object)MD5Hasher.FoldOnce(new byte[] { 1, 1, 2, 3 }), (object)MD5Hasher.FoldOnce(new byte[] { 0, 1, 2, 3 }));
            Assert.AreEqual(MD5Hasher.FoldTwice(new byte[] { 0, 1, 2, 3 }), MD5Hasher.FoldTwice(new byte[] { 0, 1, 2, 3 }));
            Assert.AreNotEqual(MD5Hasher.FoldTwice(new byte[] { 1, 1, 2, 3 }), MD5Hasher.FoldTwice(new byte[] { 0, 1, 2, 3 }));
        }
Пример #27
0
        /// <summary>
        /// Serializes the message and save the result to the message's
        /// <see cref="Msg._MsgFrame" /> property.
        /// </summary>
        /// <param name="msg">The message to be serialized.</param>
        private void Serialize(Msg msg)
        {
            var ms = new EnhancedMemoryStream(DefMsgSize);
            int cbMsg;

            cbMsg         = Msg.Save(ms, msg);
            msg._MsgFrame = router.EncryptFrame(ms.GetBuffer(), cbMsg);
        }
Пример #28
0
        public void EnhancedMemoryStream_ReadWriteBytesNoLen()
        {
            var es = new EnhancedMemoryStream();

            es.WriteBytesNoLen(new byte[] { 0, 1, 2, 3 });
            es.Seek(0, SeekOrigin.Begin);
            CollectionAssert.AreEqual(new byte[] { 0, 1, 2, 3 }, es.ReadBytes(4));
        }
Пример #29
0
        private void Verify(EnhancedMemoryStream ms, int cb)
        {
            byte[] buffer = ms.GetBuffer();

            for (int i = 0; i < cb; i++)
            {
                Assert.AreEqual((byte)i, buffer[i], string.Format("pos={0}", i));
            }
        }
Пример #30
0
 private void InitServer()
 {
     msServer        = null;
     simServerError  = false;
     simServerCancel = false;
     serverNotify    = false;
     serverException = null;
     serverArgs      = null;
 }