【问题标题】:For-loop has Unexpected Side-EffectFor-loop 有意想不到的副作用
【发布时间】:2015-09-27 06:11:28
【问题描述】:

所以我一直在用 C# 编写一个小字节密码,一切都很顺利,直到我尝试做一些 for 循环来测试运行时性能。这就是事情开始变得非常奇怪的地方。请允许我向您展示,而不是试图解释它:

首先,这里是工作代码(for 循环被注释掉):

using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DreamforceFramework.Framework.Cryptography;

namespace TestingApp
{
    static class Program
    {
        static void Main(string[] args)
        {

            string myData = "This is a test.";
            byte[] myDataEncrypted;
            string myDecryptedData = null;
            Stopwatch watch = new Stopwatch();
            Console.WriteLine("Warming up for Encryption...");
            //for (int i = 0; i < 20; i++)
            //{
            //    // Warm up the algorithm for a proper speed benchmark.
            //    myDataEncrypted = DreamforceByteCipher.Encrypt(myData, "Dreamforce");
            //}
            watch.Start();
            myDataEncrypted = DreamforceByteCipher.Encrypt(myData, "Dreamforce");
            watch.Stop();
            Console.WriteLine("Encryption Time: " + watch.Elapsed);
            Console.WriteLine("Warming up for Decryption...");
            //for (int i = 0; i < 20; i++)
            //{
            //    // Warm up the algorithm for a proper speed benchmark.
            //    myDecryptedData = DreamforceByteCipher.Decrypt(myDataEncrypted, "Dreamforce");
            //}
            watch.Reset();
            watch.Start();
            myDecryptedData = DreamforceByteCipher.Decrypt(myDataEncrypted, "Dreamforce");
            watch.Stop();
            Console.WriteLine("Decryption Time: " + watch.Elapsed);
            Console.WriteLine(myDecryptedData);
            Console.Read();
        }
    }
}

还有我的 ByteCipher(我在最初发生错误后高度简化了它,试图找出问题所在):

using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using DreamforceFramework.Framework.Utilities;

namespace DreamforceFramework.Framework.Cryptography
{
    /// <summary>
    /// DreamforceByteCipher
    /// Gordon Kyle Wallace, "Krythic"
    /// Copyright (C) 2015 Gordon Kyle Wallace, "Krythic" - All Rights Reserved
    /// </summary>
    public static class DreamforceByteCipher
    {

        public static byte[] Encrypt(string data, string password)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(data);
            string passwordHash = DreamforceHashing.GenerateSHA256(password);
            byte[] hashedPasswordBytes = Encoding.ASCII.GetBytes(passwordHash);
            int passwordShiftIndex = 0;
            bool twistPath = false;
            for (int i = 0; i < bytes.Length; i++)
            {
                int shift = hashedPasswordBytes[passwordShiftIndex];
                bytes[i] = twistPath
                    ? (byte)(
                        (data[i] + (shift * i)))
                    : (byte)(
                        (data[i] - (shift * i)));
                passwordShiftIndex = (passwordShiftIndex + 1) % 64;
                twistPath = !twistPath;
            }
            return bytes;
        }

        /// <summary>
        /// Decrypts a byte array back into a string.
        /// </summary>
        /// <param name="data"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string Decrypt(byte[] data, string password)
        {
            string passwordHash = DreamforceHashing.GenerateSHA256(password);
            byte[] hashedPasswordBytes = Encoding.UTF8.GetBytes(passwordHash);
            int passwordShiftIndex = 0;
            bool twistPath = false;
            for (int i = 0; i < data.Length; i++)
            {
                int shift = hashedPasswordBytes[passwordShiftIndex];
                data[i] = twistPath
                    ? (byte)(
                        (data[i] - (shift * i)))
                    : (byte)(
                        (data[i] + (shift * i)));
                passwordShiftIndex = (passwordShiftIndex + 1) % 64;
                twistPath = !twistPath;
            }
            return Encoding.ASCII.GetString(data);
        }
    }
}

注释掉 for 循环后,这是我得到的输出:

最后一行显示全部解密成功。

现在……这就是事情变得奇怪的地方。如果取消注释 for 循环并运行程序,输出如下:

解密失败。这绝对没有意义,因为保存解密数据的变量应该每次都重写。我是否在 C#/.NET 中遇到了导致这种奇怪行为的错误?

一个简单的解决方案: http://pastebin.com/M3xa9yQK

【问题讨论】:

  • public static string Decrypt 中,您更改data。数组是通过引用传递的,所以下一次调用Decrypt 是为了接收修改后的data
  • Krythic,我希望你很清楚,如果你刚刚问过“我的代码在哪里是我的错误?”你的问题不会被否决。也许它甚至可以被赞成。
  • 您的Encrypt 方法将data 字符串转换为bytes,但仍使用data 中的字符而不是bytes 中的字节。如果您将字符编码为几个字节(例如汉字),这是错误的。
  • 当您被否决时,请不要过于个人化。我们希望 SO 成为一个提供高质量问题和答案的地方,对正在寻找答案的每个人都有用,作为一种数据库。如果您被否决,您仍然可以编辑您的问题(或答案)并有机会再次被投赞成票。
  • 也许“For-loop 有意想不到的副作用”。还问“错误在哪里?”而不是怀疑 C# 或 .NET 中的错误。

标签: c# .net loops debugging


【解决方案1】:

您的Decrypt 方法修改了data 输入数组。因此,在数据不再加密之前,您只能对任何给定的输入字节数组调用一次Decrypt。以一个简单的控制台应用为例:

class Program
{
    public static void Main(string[] args)
    {
        var arr = new byte[] { 10 };
        Console.WriteLine(arr[0]); // prints 10
        DoSomething(arr);
        Console.WriteLine(arr[0]); // prints 11
    }

    private static void DoSomething(byte[] arr)
    {
        arr[0] = 11;
    }
}

所以,回答你的问题,不。您还没有在 .NET 中发现错误。您在代码中发现了一个非常简单的错误。

【讨论】:

  • 就是这样。代表我的一个小疏忽。谢谢。
猜你喜欢
  • 2018-12-17
  • 1970-01-01
  • 1970-01-01
  • 2018-07-08
  • 1970-01-01
  • 2016-03-11
  • 2017-11-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多