DateTime.Now.Ticks太慢了

时间:2013-03-14 11:56:26

标签: c#

我正在制作一个可以生成密码的密码生成器。

 var listOfCharacters = "abcdefghijklmnopqrstuvwxyz" //the chars which are using
    chars = listOfCharacters.ToCharArray();

  string password = string.Empty;

            for (int i = 0; i < length; i++) 
            {
                int x = random.Next(0, chars.Length); //with random he is picking a random char from my list from position 0 - 26 (a - z)

                 password += chars.GetValue(x); // putting x (the char which is picked) in the new generated password

            }
            if (length < password.Length) password = password.Substring(0, length); // if the password contains the correct length he will be returns


            return password;

我的随机:

random = new Random((int)DateTime.Now.Ticks);

我正在寻找一种比使用Ticks更快的生成密码的方法,因为它对我来说不够快。我正在寻找一个简单的代码,我可以轻松放入上面的代码中。我只是C#的初学者。所以我仍然可以使用int x = random.Next(0, chars.Length);而不是Random.next更快的。{/ p>

编辑: 当我想要两个在短时间内生成两个密码时。要求减慢

我的测试代码:

   [TestMethod]
    public void PasswordGeneratorShouldRenderUniqueNextPassword()
    {
        // Create an instance, and generate two passwords
        var generator = new PasswordGenerator();
        var firstPassword = generator.Generate(8); //8 is the length of the password
        var secondPassword = generator.Generate(8);

        // Verify that both passwords are unique
        Assert.AreNotEqual(firstPassword, secondPassword);
    }

4 个答案:

答案 0 :(得分:0)

在启动时创建一次Random实例,或使用RNGCryptoServiceProvider

// Create the random instance only once.
private static Random _Random = new Random();

static void Main(string[] args)
{
    var listOfCharacters = "abcdefghijklmnopqrstuvwxyz".ToList();
    var result = new StringBuilder();

    for (int i = 0; i < 20; i++)
    {
        // Consider creating the provider only once!
        var provider = new RNGCryptoServiceProvider();
        // The same is true for the byte array.
        var bytes = new byte[4];

        provider.GetBytes(bytes);
        var number = BitConverter.ToInt32(bytes, 0);
        var index = Math.Abs(number % listOfCharacters.Count);

        result.Append(listOfCharacters[index]);
    }

    Console.WriteLine(result.ToString());
    Console.ReadKey();
}

偏差测试

    static void Main(string[] args)
    {
        var listOfCharacters = "abcdefghijklmnopqrstuvwxyz".ToList();
        var occurences = new Dictionary<char, int>();

        foreach (var character in listOfCharacters)
        {
            occurences.Add(character, 0);
        }

        var provider = new RNGCryptoServiceProvider();
        var bytes = new byte[4];

        for (int i = 0; i < 1000000; i++)
        {
            provider.GetBytes(bytes);
            var number = BitConverter.ToInt32(bytes, 0);
            var index = Math.Abs(number % listOfCharacters.Count);

            occurences[listOfCharacters[index]]++;
        }

        var orderedOccurences = occurences.OrderBy(kvp => kvp.Value);
        var minKvp = orderedOccurences.First();
        var maxKvp = orderedOccurences.Last();

        Console.WriteLine("Min occurence: " + minKvp.Key + " Times: " + minKvp.Value);
        Console.WriteLine("Max occurence: " + maxKvp.Key + " Times: " + maxKvp.Value);
        Console.WriteLine("Difference: " + (maxKvp.Value - minKvp.Value));

        Console.ReadKey();
    }

结果是在最高出现和最低出现之间的值介于700到800之间,这意味着偏差在某处0.08%,并且具有最大差异的两个字符总是不同。所以我真的看不出任何偏见。

答案 1 :(得分:0)

您可以使用Guid的哈希码作为Random实例的种子值。对于你的情况,它应该是随机的。

random = new Random(Guid.NewGuid().GetHashCode());

答案 2 :(得分:0)

以下程序在我的计算机上生成约500个密码/毫秒:

class Program
{
    static void Main(string[] args)
    {
        var g = new Generator();
        IEnumerable<string> passwords = new List<string>();
        var startTime = DateTime.Now;
        passwords = g.GetPassword().ToList();
    }
}

class Generator
{
    Random r = new Random(Guid.NewGuid().GetHashCode());
    string randomCharsList;
    const int length = 8;
    const int randomLength = 8000;
    const string listOfCharacters = "abcdefghijklmnopqrstuvwxyz";
    public Generator()
    {
        CreateRandom();
    }

    private void CreateRandom()
    {
        var randomChars = new StringBuilder();
        string password = string.Empty;

        for (int i = 0; i < randomLength + length; i++)
        {
            var random = new Random(i * Guid.NewGuid().ToByteArray().First());
            int x = random.Next(0, listOfCharacters.Length);
            randomChars.Append(listOfCharacters[x]);
        }
        randomCharsList = randomChars.ToString();
    }

    public IEnumerable<string> GetPassword()
    {
        int pos;
        var startTime = DateTime.Now;
        while ((DateTime.Now - startTime).Milliseconds < 1)
        {
            pos = r.Next(randomLength);
            yield return randomCharsList.Substring(pos, length);
        }
    }
}

答案 3 :(得分:0)

只是想在这里添加一个关于生成随机数的线程安全问题的注释(例如我们遇到此问题的高容量网络服务器)。

本质上,Random类不是线程安全的,如果发生冲突,它将返回0(不是我所期望的),不用说可以真正破坏你的逻辑:)所以如果在多线程环境中使用那么make一定要保护对任何共享Random对象的访问。

有关详细信息,请参阅https://msdn.microsoft.com/en-us/library/system.random(v=vs.110).aspx处的'System.Random类和线程安全'部分。

希望这有助于某人。