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); }
public void ObjectGraphAck_Serialize() { ObjectGraphAck msgOut, msgIn; EnhancedMemoryStream ms = new EnhancedMemoryStream(); Msg.ClearTypes(); Msg.LoadTypes(Assembly.GetExecutingAssembly()); msgOut = new ObjectGraphAck("hello world", Compress.Always); Msg.Save(ms, msgOut); ms.Seek(0, SeekOrigin.Begin); msgIn = (ObjectGraphAck)Msg.Load(ms); Assert.AreEqual("hello world", msgIn.Graph); //----------------------------------- ms.SetLength(0); msgOut = new ObjectGraphAck(new string[] { "a", "b", "c" }, Compress.Always); Msg.Save(ms, msgOut); ms.Seek(0, SeekOrigin.Begin); msgIn = (ObjectGraphAck)Msg.Load(ms); CollectionAssert.AreEqual(new string[] { "a", "b", "c" }, (string[])msgIn.Graph); //----------------------------------- ms.SetLength(0); msgOut = new ObjectGraphAck(new TimeoutException("timeout")); Msg.Save(ms, msgOut); ms.Seek(0, SeekOrigin.Begin); msgIn = (ObjectGraphAck)Msg.Load(ms); Assert.AreEqual("timeout", msgIn.Exception); //----------------------------------- ms.SetLength(0); msgOut = new ObjectGraphAck(null, Compress.Always); Msg.Save(ms, msgOut); ms.Seek(0, SeekOrigin.Begin); msgIn = (ObjectGraphAck)Msg.Load(ms); Assert.IsNull(msgIn.Graph); }
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); }
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); }
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); }
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); }
public void BlobPropertyMsg_Serialize() { BlobPropertyMsg msgOut, msgIn; EnhancedMemoryStream ms = new EnhancedMemoryStream(); Msg.ClearTypes(); Msg.LoadTypes(Assembly.GetExecutingAssembly()); msgOut = new BlobPropertyMsg(); 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 = null; Msg.Save(ms, msgOut); ms.Seek(0, SeekOrigin.Begin); msgIn = (BlobPropertyMsg)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.IsNull(msgIn._Data); ms.SetLength(0); msgOut._Data = new byte[] { 0, 1, 2 }; Msg.Save(ms, msgOut); ms.Seek(0, SeekOrigin.Begin); msgIn = (BlobPropertyMsg)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); }
public void Msg_Serialize_EnvelopeMsg() { EnvelopeTestMsg evMsgOut, evMsgIn; EnvelopeMsg envelopeMsg; EnhancedStream es = new EnhancedMemoryStream(); Msg.ClearTypes(); Msg.LoadTypes(Assembly.GetExecutingAssembly()); // EnvelopeTestMsg is tagged with [MsgIgnore] so it won't loaded // into the map by Msg.LoadTypes(). This means that Msg.Load() // should return a EnvelopeMsg instance. evMsgOut = new EnvelopeTestMsg(); evMsgOut.Value = "The hills are alive, with the sound of music. ahhhhhhhhh"; Msg.LoadType(typeof(EnvelopeTestMsg)); Msg.Save(es, evMsgOut); Msg.ClearTypes(); Msg.LoadTypes(Assembly.GetExecutingAssembly()); es.Seek(0, SeekOrigin.Begin); envelopeMsg = (EnvelopeMsg)Msg.Load(es); Assert.IsNotNull(envelopeMsg); Assert.AreEqual(EnvelopeTestMsg.GetTypeID(), envelopeMsg.TypeID); // Serialize the EnvelopeMsg instance and then call Msg.LoadType() to // force the mapping of EnvelopeTestMsg and then make sure that // Msg.Load() was able to deserialize if properly. es.SetLength(0); Msg.Save(es, envelopeMsg); Msg.LoadType(typeof(EnvelopeTestMsg)); es.Seek(0, SeekOrigin.Begin); evMsgIn = (EnvelopeTestMsg)Msg.Load(es); Assert.AreEqual(evMsgOut.Value, evMsgIn.Value); }
public void SecureFile_Stream_GetPublicKey() { 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; for (int i = 0; i < 100; i++) { original.WriteByte((byte)i); } // Verify that the public key is saved when requested (the default) secure = new SecureFile(original, SecureFileMode.Encrypt, publicKey); Assert.IsTrue(secure.SavePublicKey); Assert.AreEqual(publicKey, secure.PublicKey); original.Position = 0; secure.EncryptTo(encrypted, CryptoAlgorithm.AES, 256); secure.Close(); secure = null; encrypted.Position = 0; Assert.AreEqual(publicKey, SecureFile.GetPublicKey(encrypted)); // Verify that the public key is not saved if SavePublicKey=false encrypted.SetLength(0); secure = new SecureFile(original, SecureFileMode.Encrypt, publicKey); secure.SavePublicKey = false; original.Position = 0; secure.EncryptTo(encrypted, CryptoAlgorithm.AES, 256); secure.Close(); secure = null; encrypted.Position = 0; Assert.IsNull(SecureFile.GetPublicKey(encrypted)); }
public void Msg_Serialize_GetConfigAck() { GetConfigAck msgIn, msgOut; EnhancedStream es = new EnhancedMemoryStream(); msgOut = new GetConfigAck(new Exception("Test exception")); Msg.Save(es, msgOut); es.Seek(0, SeekOrigin.Begin); msgIn = (GetConfigAck)Msg.Load(es); Assert.AreEqual("Test exception", msgIn.Exception); Assert.IsNull(msgIn.ConfigText); msgOut = new GetConfigAck("config info"); es.SetLength(0); Msg.Save(es, msgOut); es.Seek(0, SeekOrigin.Begin); msgIn = (GetConfigAck)Msg.Load(es); Assert.IsNull(msgIn.Exception); Assert.AreEqual("config info", msgIn.ConfigText); }
/// <summary> /// Decrypts a byte array encrypted using <see cref="Encrypt(string ,byte[],string,int,int,out SymmetricKey)" />. /// </summary> /// <param name="rsaKey">The decrypting RSA key as XML or as a secure key container name.</param> /// <param name="cipherText">The encrypted data.</param> /// <param name="symmetricKey">Returns as the symmetric encryption algorithm arguments.</param> /// <returns>The decrypted data.</returns> /// <exception cref="CryptographicException">Thrown is the encrypted data block is incorrectly formatted.</exception> /// <remarks> /// Note that applications should take some care to ensure that the <paramref name="symmetricKey" /> /// value return is disposed so that the symmetric encryption key will be cleared. /// </remarks> public static byte[] Decrypt(string rsaKey, byte[] cipherText, out SymmetricKey symmetricKey) { EnhancedMemoryStream input = new EnhancedMemoryStream(cipherText); EnhancedMemoryStream ms = new EnhancedMemoryStream(cipherText.Length); BlockDecryptor decryptor = null; byte[] symKey; byte[] symIV; string algorithm; try { // Read the header fields if (input.ReadInt32() != Magic) { throw new CryptographicException(BadFormatMsg); } if (input.ReadInt32() != 0) { throw new CryptographicException("Unsupported secure data format version."); } // Decrypt the encryption info ms.WriteBytesNoLen(AsymmetricCrypto.Decrypt(CryptoAlgorithm.RSA, rsaKey, input.ReadBytes16())); ms.Position = 0; algorithm = ms.ReadString16(); symKey = ms.ReadBytes16(); symIV = ms.ReadBytes16(); symmetricKey = new SymmetricKey(algorithm, symKey, symIV); decryptor = new BlockDecryptor(algorithm, symKey, symIV); // Decrypt the contents ms.SetLength(0); ms.WriteBytesNoLen(decryptor.Decrypt(input.ReadBytes32())); ms.Position = 0; if (ms.ReadInt32() != Magic) { throw new CryptographicException("Secure data content is corrupt."); } ms.Position += 8; // Skip over the salt return(ms.ReadBytes32()); } finally { if (decryptor != null) { decryptor.Dispose(); } input.Close(); ms.Close(); } }
/// <summary> /// Encrypts a byte array using a combination of an asymmetric RSA key and the /// specified symmetric encryption algorithm and a one-time key generated by /// the method. /// </summary> /// <param name="rsaKey">The encrypting RSA key as XML or as a secure key container name.</param> /// <param name="plainText">The data to be encrypted.</param> /// <param name="algorithm">The symmetric encryption algorithm name.</param> /// <param name="keySize">The one-time symmetric key size to generate in bits.</param> /// <param name="paddedSize">Specifies the minimum padded size of the encrypted content.</param> /// <param name="symmetricKey">Returns as the symmetric encryption algorithm arguments.</param> /// <returns>The encrypted result.</returns> /// <remarks> /// <para> /// Note that applications should take some care to ensure that the <paramref name="symmetricKey" /> /// value return is disposed so that the symmetric encryption key will be cleared. /// </para> /// <para> /// The current supported cross platform encryption algorithms /// are: "DES", "RC2", "TripleDES", and "AES" (Rijndael). /// </para> /// </remarks> /// <exception cref="ArgumentException">Thrown if the requested encryption algorithm is unknown.</exception> public static byte[] Encrypt(string rsaKey, byte[] plainText, string algorithm, int keySize, int paddedSize, out SymmetricKey symmetricKey) { EnhancedMemoryStream output = new EnhancedMemoryStream(Math.Max(plainText.Length, paddedSize) + 512); EnhancedMemoryStream ms = new EnhancedMemoryStream(512); BlockEncryptor encryptor = null; byte[] symKey; byte[] symIV; Crypto.GenerateSymmetricKey(algorithm, keySize, out symKey, out symIV); encryptor = new BlockEncryptor(algorithm, symKey, symIV); symmetricKey = new SymmetricKey(algorithm, (byte[])symKey.Clone(), (byte[])symIV.Clone()); try { // Write header fields output.WriteInt32(Magic); output.WriteInt32(0); // Write encryption Info ms.WriteString16(algorithm); ms.WriteBytes16(symKey); ms.WriteBytes16(symIV); ms.WriteBytesNoLen(Crypto.GetSalt8()); output.WriteBytes16(AsymmetricCrypto.Encrypt(CryptoAlgorithm.RSA, rsaKey, ms.ToArray())); // Write encrypted contents ms.SetLength(0); ms.WriteInt32(Magic); ms.WriteBytesNoLen(Crypto.GetSalt8()); ms.WriteBytes32(plainText); for (int i = plainText.Length; i < paddedSize; i++) { ms.WriteByte((byte)i); // Padding bytes } output.WriteBytes32(encryptor.Encrypt(ms.ToArray())); // That's it, we're done. return(output.ToArray()); } finally { if (symKey != null) { Array.Clear(symKey, 0, symKey.Length); } if (symIV != null) { Array.Clear(symIV, 0, symIV.Length); } if (encryptor != null) { encryptor.Dispose(); } output.Close(); ms.Close(); } }