1

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

 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更快。

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

我的测试代码:

   [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

4 回答 4

0

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

random = new Random(Guid.NewGuid().GetHashCode());
于 2013-03-14T12:17:44.437 回答
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);
        }
    }
}
于 2013-03-14T12:48:19.430 回答
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% 的某个地方,并且具有最大差异的两个字符总是不同的。所以我真的看不到任何偏见。

于 2013-03-14T12:05:51.570 回答
0

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

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

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

希望这可以帮助某人。

于 2016-01-23T22:05:21.893 回答