目前我正在使用 BinaryFormatter 来序列化我的对象(它们是 string[] 和 byte[])
BinaryFormatter 方法时存在安全漏洞。 Deserialize 方法可用作攻击者对消费应用程序执行 DoS 攻击的载体。
有一个选项可以将 serializationbinder 添加到 BinaryFormatter 并将方法实现到 BindToType,我们可以在其中限制允许反序列化的类型。
我正在寻找 BinaryFormatter 替代品来序列化和反序列化我代码中的对象。
{
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```