2

我需要防止一些孩子修改 json 文本文件并将“fartface”放入其中。我当前的代码从文本文件中获取一个字符串,如下所示:

using (StreamReader file = File.OpenText(basePath + "jsontxt"))
{
    string s = file.ReadToEnd();

我可以对我的 jsontxt 文件应用 XOR,这足以防止恶意放屁玩笑,但是在我的 wpf C# 应用程序中,当文件被读入字符串时,我不确定如何实现字节 XOR。

4

4 回答 4

4

尝试将字符串作为字节数组获取,并简单地用一些密钥对每个字节进行异或:

Byte[] byteString;
using (StreamReader file = File.OpenText(basePath + "jsontxt"))
{
   Byte secretByte = 125;
   string s = file.ReadToEnd();
   byteString = Encoding.UTF8.GetBytes(s);
   foreach(Byte b in byteString)
   {
      b ^= secretByte;
   }
}
//here save stream
于 2013-04-16T16:12:52.700 回答
1

You should use System.IO.CryptoStream, Microsoft's stream decorator for reading/writing encrypted streams. Simple!

To read the encrypted text, something like this suffices:

static IEnumerable<string> ReadEncryptedTextFile( string path , byte[] key , byte[] iv , Encoding encoding )
{
  string value ;
  using ( Stream s = File.OpenRead(path) )
  using ( SymmetricAlgorithm algorithm = SymmetricAlgorithm.Create() )
  using ( ICryptoTransform transform = algorithm.CreateDecryptor( key , iv ) )
  using ( CryptoStream cs = new CryptoStream( s , transform , CryptoStreamMode.Read ) )
  using ( TextReader sr = new StreamReader(cs,encoding))
  {
      string line ;
      while ( null != ( line = sr.ReadLine() ) )
      {
          yield return line ;
      }
  }
}

To write the encrypted text, something like this:

static void WriteEncryptedTextFile ( IEnumerable<string> lines , string path , byte[] key , byte[] iv , Encoding encoding )
{
  using ( Stream             s         = File.OpenWrite(path) )
  using ( SymmetricAlgorithm algorithm = SymmetricAlgorithm.Create() )
  using ( ICryptoTransform   transform = algorithm.CreateEncryptor( key , iv ) )
  using ( CryptoStream       cs        = new CryptoStream( s , transform , CryptoStreamMode.Write ) )
  using ( TextWriter         tw        = new StreamWriter( cs , encoding ) )
  {
    foreach ( string line in lines )
    {
      tw.WriteLine( line ) ;
    }
  }
  return ;
}

You might want to dial in the specific algorithm you use (and each algorithm has requirements about key and iv size).

于 2013-04-16T19:45:13.757 回答
1

我看到这个想法有两个问题。

首先,您会发现很难得出一个 XOR 值,当应用该值时,它会始终产生可读的字符。在这种情况下,您的文件将成为二进制文件,而不是文本文件。

其次,假设您可以想出一种方法来保证文件的可读性,这不会阻止人们对其进行修改。

如果要加密文件,请使用真正的加密技术。或者至少将您的字符串转换为字节数组,对字节进行异或,然后将文件写入二进制文件。要读回它,请将文件作为二进制文件读入byte[](即File.ReadAllBytes),对字节进行异或,然后将该字节缓冲区转换为字符串。

于 2013-04-16T16:17:47.760 回答
-1

我假设您正在尝试实施某种类型的验证以确保文件未被修改。为什么不直接获取字符串的哈希码并进行检查呢?

using (StreamReader file = File.OpenText(basePath + "jsontxt"))
{
    string s = file.ReadToEnd();
}
if (verificationCode != s.GetHashCode())
{
    // Malicious fart joke eminent!
}

您可以通过在文件目录上运行 Powershell 脚本轻松生成您的验证码……您没有提及如何存储 XOR 值以进行检查,但您可以将脚本写入您可以检查的位置。 .

$files = Get-Item "C:\test\*.js"

foreach ($file in $files)
{
    $text = Get-Content $file
    $file.BaseName +" "+ $text.GetHashCode()
}
于 2013-04-16T16:32:03.170 回答