This page is not yet available in Spanish. We are working on its translation. If you have any questions or feedback about our current translation project, feel free to reach out to us!
This rule prevents the usage of BinaryFormatter for serialization due to its inherent security vulnerabilities. BinaryFormatter has been found to be susceptible to deserialization attacks, where a malicious actor can control the input to the deserialization operation and exploit this to execute arbitrary code, manipulate program execution, or induce application crashes.
This security risk makes it crucial to avoid BinaryFormatter. Instead, opt for safer alternatives for serialization and deserialization. An alternative is System.Text.Json, which is not only secure, but also offers better performance. Additional alternatives include DataContractSerializer, MessagePack, and protobuf-net.
usingSystem;usingSystem.IO;usingSystem.Runtime.Serialization.Formatters.Binary;[Serializable]publicclassUser{publicstringUsername{get;set;}publicstringPassword{get;set;}}classProgram{staticvoidMain(string[]args){// Serializing the objectUseruser=newUser{Username="admin",Password="password123"};BinaryFormatterformatter=newBinaryFormatter();using(FileStreamstream=newFileStream("user.dat",FileMode.Create)){formatter.Serialize(stream,user);}// Deserializing the objectusing(FileStreamstream=newFileStream("user.dat",FileMode.Open)){UserdeserializedUser=(User)formatter.Deserialize(stream);Console.WriteLine($"Username: {deserializedUser.Username}, Password: {deserializedUser.Password}");}}}
Compliant Code Examples
usingSystem;usingSystem.IO;usingSystem.Text.Json;[Serializable]publicclassUser{publicstringUsername{get;set;}publicstringPassword{get;set;}}classProgram{staticvoidMain(string[]args){// Serializing the objectUseruser=newUser{Username="admin",Password="password123"};varoptions=newJsonSerializerOptions{WriteIndented=true};stringjsonString=JsonSerializer.Serialize(user,options);File.WriteAllText("user.json",jsonString);// Deserializing the objectstringreadJsonString=File.ReadAllText("user.json");UserdeserializedUser=JsonSerializer.Deserialize<User>(readJsonString);Console.WriteLine($"Username: {deserializedUser.Username}, Password: {deserializedUser.Password}");}}