Currently i'm using BinaryFormatter to serialize my objects (which are string[] and byte[])
BinaryFormatter has security vulnerabilities when method. the Deserialize method can be used as a vector for attackers to perform DoS attacks against consuming apps.
There is a option to add serializationbinder to BinaryFormatter and implement the method to BindToType where we can limit what types are allowed to be deserialized.
I'm looking for BinaryFormatter alternative to serialize and Deserialize the objects in my code.
{
class Program
{
static void Main(string[] args)
{
string[] cars = { "Volvo", "BMW", "Ford", "Mazda" };
var item = new Item
{
Name = "Orange"
};
var bytes = SerializeData(item);
var deserializedData = DeserializeData(bytes);
}
private static byte[] SerializeData(object obj)
{
var binaryFormatter = new BinaryFormatter();
using (var memoryStream = new MemoryStream())
{
binaryFormatter.Serialize(memoryStream, obj);
return memoryStream.ToArray();
}
}
private static object DeserializeData(byte[] bytes)
{
var binaryFormatter = new BinaryFormatter
{
Binder = new TestSerializationBinder()
};
using (var memoryStream = new MemoryStream(bytes))
return binaryFormatter.Deserialize(memoryStream);
}
}
[Serializable]
public class Item
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
}
public class TestSerializationBinder : SerializationBinder
{
public override Type BindToType(string assemblyName, string typeName)
{
if (typeName.Equals("TestBinder.Item"))
return typeof(Item);
if (typeName.Equals("System.String[]"))
return typeof(string[]);
return null;
}
}
}bina```
This can be achieved by using the
JsonSerializerinSystem.Text.Json. It might seem a bit confusing to have binary serialization in a namespace that seems to focus on json but it is what it is. This namespace has been available since around .net core 3 and is hopefully available to you as well.To serialize any object to a byte[]
To deserialize this byte[] back to an object
If this is not the case Newtonsoft also has similar ways of serializing to byte[]