Make .txt file unreadable / uneditable

前端 未结 10 1708
北海茫月
北海茫月 2020-12-29 03:29

I have a program which saves a little .txt file with a highscore in it:

 // Create a file to write to. 
string createHighscore = _higscore + Environment.NewL         


        
10条回答
  •  被撕碎了的回忆
    2020-12-29 03:48

    You can serialize it and deserialize with encryption with CryptoStream :

    Serialize file :

    • Create and open FileStream in write mode
    • Create Cryptostream and pass your filestream
    • Write contents to Cryptostream (encrypt)

    Deserialize file :

    • Create and open FileStream in read mode
    • Create Cryptostream and pass your filestream
    • Read from Cryptostream (decrypt)

    You can find examples and more information here :

    msdn.microsoft.com/en-us/library/system.security.cryptography.cryptostream.aspx

    http://www.codeproject.com/Articles/6465/Using-CryptoStream-in-C

    Example :

    byte[] key = { 1, 2, 3, 4, 5, 6, 7, 8 }; // Where to store these keys is the tricky part, 
    byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };
    string path = @"C:\path\to.file";
    
    DESCryptoServiceProvider des = new DESCryptoServiceProvider();
    
    // Encryption and serialization
    using (var fStream = new FileStream(path, FileMode.Create, FileAccess.Write))
    using (var cryptoStream = new CryptoStream(fStream , des.CreateEncryptor(key, iv), CryptoStreamMode.Write))
    {
        BinaryFormatter serializer = new BinaryFormatter();
    
        // This is where you serialize your data
        serializer.Serialize(cryptoStream, yourData);
    }
    
    
    
    // Decryption
    using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
    using (var cryptoStream = new CryptoStream(fs, des.CreateDecryptor(key, iv), CryptoStreamMode.Read))
    {
        BinaryFormatter serializer = new BinaryFormatter();
    
        // Deserialize your data from file
        yourDataType yourData = (yourDataType)serializer.Deserialize(cryptoStream);
    }
    

提交回复
热议问题