生成唯一密码

时间:2013-03-13 15:58:15

标签: 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);
}

我想这里的东西是错的:

 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;

随机:

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

4 个答案:

答案 0 :(得分:5)

如果您很快生成两个密码,它们将在相同的时间点生成。


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


最快的方法是使用Random()的默认构造函数,它将为你做种子。

检查the documentation后,默认构造函数使用基于时间的种子,因此您使用它时会遇到同样的问题。无论如何,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));
}

但是,如果您希望人类能够阅读,记住并输入您生成的密码,那么您在可能的角色范围内应该会受到更多限制。


我已更新此部分,以提供详细,现代,无偏见的答案。

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

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;
        }
    }
}

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

var validChars = new[] { 'A', 'B', 'C' };

对于ilustration我只包括3 char s,实际上你需要包含更多char个。然后,为了生成随机密码8 char s,您可以拨打此电话。

var randomPassword = GetPassword(validChars, 8);

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

答案 1 :(得分:0)

您的问题是您的问题是您使用默认的随机构造函数,它使用当前日期/时间作为种子。 DateTime.Ticks的分辨率为100纳秒。这很快,但不够快,不足以进行单元测试,即在不到100 ns的时间内生成两个密码。

一种解决方案是在密码生成器中使用静态Random实例。

public class PasswordGenerator
{
    private static Random random = new Random();

    public string Generate()
    {
        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;
    }
}

答案 2 :(得分:0)

DateTime.Now.Ticks不是很准确,虽然它似乎代表了很短的时间,实际上代表了几毫秒。

由于您的密码算法可能需要十分之一毫秒,这导致DateTime.Now.Ticks具有相同的值。

两种替代方法是提供一种方法来给种子(这将允许你使用第三个随机数生成器来创建种子)或传入一个随机对象(这将确保两个是从同一种子顺序创建的,创造不同的价值观。)

答案 3 :(得分:0)

我会在Random构造函数中创建PasswordGenerator对象,以确保每次调用Generate方法时,您将获得一个(或多或少)随机数字

public PassworGenerator()
{
    random = new Random(/* seed */);
}