Reputation: 9384
I have a Client-Server-Application where I want to send an encrypted object from the server to the client.
The client is sending a request to the server like:
byte[] encryptedResponse = authenticationService.SendRequest(sessionId, requestData);
Then the client gets an encrypted response-byte-array. Then he calls
byte[] clearResponse = Cryptography.DecryptSymmetric(key, iv, encryptedResponse);
In clearResponse is now the clear binary-serialized object from the server.
Client and Server are sharing an Interface-Library which contains the IUser-Interface which looks like:
public interface IUser : ISerializable
{
Guid UserId { get; }
string Username { get; }
}
The Server contains an implementation of this interface which looks like:
[Serializable]
internal class User : IUser
{
public User(){}
public User(SerializationInfo info, StreamingContext context)
{
Id = Guid.Parse(info.GetString(XmlNodes.UserId));
Username = info.GetString(XmlNodes.Username);
}
public Guid Id { get; set; }
public string Username { get; set; }
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue(XmlNodes.UserId, Id.ToString());
info.AddValue(XmlNodes.Username, Username);
}
}
The server uses the following code to serialize the user for the client:
byte[] responseData;
IUser user = new User { Id = Guid.NewGuid(), Username = "Dummy" };
using(MemoryStream memoryStream = new MemoryStream())
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, user);
responseData = memoryStream.ToArray();
}
// encrypt the responseData and send it to the client.
Now if I try to deserialize the user with:
using(MemoryStream memoryStream = new MemoryStream(clearResponse))
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
IUser user = (IUser)binaryFormatter.Deserialize(memoryStream)
}
I get an exception.
An unhandled exception of type 'System.Runtime.Serialization.SerializationException' occurred in mscorlib.dll
Additional information: The Assembly "Users, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" could not be found.
How can I deserialize a type where I only know the interface?
Upvotes: 1
Views: 773
Reputation: 23093
Using BinaryFormatter
you can't as the type is part of the data.
You could use XmlSerializer
and send the resulting string
as (possibly encrypted) byte[]
to the cliend. Then the client needs just a "compatible type" to deserialize it.
If you want to stick with BinaryFormatter
you could also move the User
type to a shared library (if not already) and reference this by the server and client.
Upvotes: 1