生成唯一密码

3 c# unit-testing

我正在制作一个应用程序来生成密码,现在我已经编写了一个单元测试,以测试当你生成2个密码时它们是唯一的,但我遇到的问题是它们不是唯一的,而是相同的.

单元测试:

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

    // Verify that both passwords are unique
    Assert.AreNotEqual(firstPassword, secondPassword);
}
Run Code Online (Sandbox Code Playgroud)

我想这里的东西是错的:

 for (int i = 0; i < length; i++)
 {
     int x = random.Next(0, length);

     if (!password.Contains(chars.GetValue(x).ToString()))
         password += chars.GetValue(x);
     else
         i--;
 }
 if (length < password.Length) password = password.Substring(0, length);

 return password;
Run Code Online (Sandbox Code Playgroud)

随机:

 Random random = new Random((int)DateTime.Now.Ticks);
Run Code Online (Sandbox Code Playgroud)

Jod*_*ell 5

如果您很快生成两个密码,它们将在同一个刻度上生成.


如果您只想生成随机的人类可读密码,请查看此处.如果你想知道为什么Random这个目的不好,你怎么做更合适的事情继续阅读.


最快的方法是使用默认构造函数Random(),它将为您进行种子处理.

检查文档后,默认构造函数使用基于时间的种子,因此您使用它时会遇到相同的问题.无论如何,Random该类太可预测,无法用于安全密码生成.

如果你想要更多的力量,你可以做到这一点,

using System.Security.Cryptography;

static string GetPassword(int length = 13)
{
   var rng = new RNGCryptoServiceProvider();
   var buffer = new byte[length * sizeof(char)];
   rng.GetNonZeroBytes(buffer);
   return new string(Encoding.Unicode.GetChars(buffer));
}
Run Code Online (Sandbox Code Playgroud)

但是,如果您希望人类能够阅读,记住并输入您生成的密码,那么您的可能角色范围应该更加有限.


我已经更新了这部分,以提供详细,现代,无偏见的答案.

如果要将输出限制为某一组字符,可以执行以下操作.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;

/// <summary>
/// Get a random password.
/// </summary>
/// <param name="valid">A list of valid password chars.</param>
/// <param name="length">The length of the password.</returns>
/// <returns>A random password.</returns>
public static string GetPassword(IList<char> valid, int length = 13)
{
    return new string(GetRandomSelection(valid, length).ToArray());
}

/// <summary>
/// Gets a random selection from <paramref name="valid"/>.
/// </summary>
/// <typeparam name="T">The item type.</typeparam>
/// <param name="valid">List of valid possibilities.</param>
/// <param name="length">The length of the result sequence.</param>
/// <returns>A random sequence</returns>
private static IEnumerable<T> GetRandomSelection<T>(
        IList<T> valid,
        int length)
{
    // The largest multiple of valid.Count less than ulong.MaxValue.
    // This upper limit prevents bias in the results.
    var max = ulong.MaxValue - (ulong.MaxValue % (ulong)valid.Count);

    // A finite sequence of random ulongs.
    var ulongs = RandomUInt64Sequence(max, length).Take(length);

    // A sequence of indecies.
    var indecies = ulongs.Select((u => (int)(u % (ulong)valid.Count)));

    return indecies.Select(i => valid[i]);
}

/// <summary>
/// An infinite sequence of random <see cref="ulong"/>s.
/// </summary>
/// <param name="max">
/// The maximum inclusive <see cref="ulong"/> to return.
/// </param>
/// <param name="poolSize">
/// The size, in <see cref="ulong"/>s, of the pool used to
/// optimize <see cref="RNGCryptoServiceProvider"/> calls.
/// </param>
/// <returns>A random <see cref="ulong"/> sequence.</returns>
private static IEnumerable<ulong RandomUInt64Sequence(
        ulong max = UInt64.MaxValue,
        int poolSize = 100)
{
    var rng = new RNGCryptoServiceProvider();
    var pool = new byte[poolSize * sizeof(ulong)];

    while (true)
    {
        rng.GetBytes(pool);
        for (var i = 0; i < poolSize; i++)
        {
            var candidate = BitConvertor.ToUInt64(pool, i * sizeof(ulong));
            if (candidate > max)
            {
                continue;
            }

            yield return candidate;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以像这样使用此代码,首先您需要一组char可能在您的密码中的有效a,

var validChars = new[] { 'A', 'B', 'C' };
Run Code Online (Sandbox Code Playgroud)

对于ilustration我只包括3 char秒,在实践中你需要更多的chars被包括在内.然后,为了生成随机密码8 char秒,你可以拨打这个电话.

var randomPassword = GetPassword(validChars, 8);
Run Code Online (Sandbox Code Playgroud)

实际上,您可能希望密码至少为13 char秒.