- Home /
unity2d : BinaryFormatter files are not secure
hi, i'm trying to save and load sensitive data using BinaryFormatter . but the problem is when i try to open the BinaryFormatter file with an editor , i can easly read and modify the data that i had saved . This is un exemple from the code i used to save and load data :
[Serializable]
public class setLitecoin
{
public string litecoin;
public setLitecoin(string lite)
{
litecoin = lite;
}
}
public static void saveLitecoin(string litecoin)
{
BinaryFormatter bf = new BinaryFormatter();
FileStream stream = new FileStream(Application.persistentDataPath + "/player.litecoin", FileMode.Create);
setLitecoin setlitecoin = new setLitecoin(litecoin);
bf.Serialize(stream, setlitecoin);
stream.Close();
}
public static string loadLitecoin()
{
if (!File.Exists(Application.persistentDataPath + "/player.litecoin"))
{
saveLitecoin("");
}
BinaryFormatter bf = new BinaryFormatter();
FileStream stream = new FileStream(Application.persistentDataPath + "/player.litecoin", FileMode.Open);
setLitecoin litecoin = bf.Deserialize(stream) as setLitecoin;
stream.Close();
return litecoin.litecoin;
}
Answer by CodesCove · Aug 25, 2020 at 02:32 PM
BinaryFormatter serializes and deserializes data and does not make it, and cannot make it, secure. If you serialize a string with BinaryFormatter you can still read it from the serialized stream pretty easily. It is actually one of the most unsecured methods for various reasons (see the link). https://docs.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide
If you want secure streams then consider alternatives like CryptoStream. For example check this out: https://docs.microsoft.com/en-us/dotnet/standard/security/encrypting-data.
Of course you need then some extra work to handle encryption keys etc..