当我们网站上的用户丢失密码并转到丢失密码页面时,我们需要给他一个新的临时密码。我并不介意这有多随机,或者它是否符合所有“所需的”强密码规则,我想做的只是给他们一个他们以后可以更改的密码。

该应用程序是用c#编写的Web应用程序。所以我想刻薄一点,走一条简单的路线,用Guid的一部分。即。

Guid.NewGuid().ToString("d").Substring(1,8)

Suggesstions吗?想法吗?


当前回答

public string GenerateToken(int length)
{
    using (RNGCryptoServiceProvider cryptRNG = new RNGCryptoServiceProvider())
    {
        byte[] tokenBuffer = new byte[length];
        cryptRNG.GetBytes(tokenBuffer);
        return Convert.ToBase64String(tokenBuffer);
    }
}

(你也可以让这个方法所在的类实现IDisposable,持有对RNGCryptoServiceProvider的引用,并正确地处理它,以避免重复实例化它。)

It's been noted that as this returns a base-64 string, the output length is always a multiple of 4, with the extra space using = as a padding character. The length parameter specifies the length of the byte buffer, not the output string (and is therefore perhaps not the best name for that parameter, now I think about it). This controls how many bytes of entropy the password will have. However, because base-64 uses a 4-character block to encode each 3 bytes of input, if you ask for a length that's not a multiple of 3, there will be some extra "space", and it'll use = to fill the extra.

If you don't like using base-64 strings for any reason, you can replace the Convert.ToBase64String() call with either a conversion to regular string, or with any of the Encoding methods; eg. Encoding.UTF8.GetString(tokenBuffer) - just make sure you pick a character set that can represent the full range of values coming out of the RNG, and that produces characters that are compatible with wherever you're sending or storing this. Using Unicode, for example, tends to give a lot of Chinese characters. Using base-64 guarantees a widely-compatible set of characters, and the characteristics of such a string shouldn't make it any less secure as long as you use a decent hashing algorithm.

其他回答

灵感来自@kitsu的回答。但使用RandomNumberGenerator而不是Random或RNGCryptoServiceProvider(在。net 6中已弃用),并添加了一些特殊字符。

可选参数,用于排除在使用System.Text.Json.JsonSerializer.Serialize时将转义的字符—例如&,它转义为\u0026—以便您可以保证序列化字符串的长度与密码的长度匹配。

适用于。net Core 3.0及以上版本。

public static class PasswordGenerator
{
    const string lower = "abcdefghijklmnopqrstuvwxyz";
    const string upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    const string number = "1234567890";
    const string special = "!@#$%^&*()[]{},.:`~_-=+"; // excludes problematic characters like ;'"/\
    const string specialJsonSafe = "!@#$%^*()[]{},.:~_-="; // excludes problematic characters like ;'"/\ and &`+

    const int lowerLength = 26; // lower.Length
    const int upperLength = 26; // upper.Length;
    const int numberLength = 10; // number.Length;
    const int specialLength = 23; // special.Length;
    const int specialJsonSafeLength = 20; // specialJsonSafe.Length;

    public static string Generate(int length = 96, bool jsonSafeSpecialCharactersOnly = false)
    {
        Span<char> result = length < 1024 ? stackalloc char[length] : new char[length].AsSpan();

        for (int i = 0; i < length; ++i)
        {
            switch (RandomNumberGenerator.GetInt32(4))
            {
                case 0:
                    result[i] = lower[RandomNumberGenerator.GetInt32(0, lowerLength)];
                    break;
                case 1:
                    result[i] = upper[RandomNumberGenerator.GetInt32(0, upperLength)];
                    break;
                case 2:
                    result[i] = number[RandomNumberGenerator.GetInt32(0, numberLength)];
                    break;
                case 3:
                    if (jsonSafeSpecialCharactersOnly)
                    {
                        result[i] = specialJsonSafe[RandomNumberGenerator.GetInt32(0, specialJsonSafeLength)];
                    }
                    else
                    {
                        result[i] = special[RandomNumberGenerator.GetInt32(0, specialLength)];
                    }
                    break;
            }
        }

        return result.ToString();
    }
}

由于Random是不安全的,RNGCryptoServiceProvider是过时的,我最终这样做:

  // possible characters that password can have
  private const string passChars =
       "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
       "abcdefghijklmnopqrstuvwxyz" +
       "0123456789" +
       "!@#$%.-_"
       ;

    public static string GetRandomPassword(int length)
    {
        char[] p = new char[length];
        for (int i = 0; i < length; i++)
            p[i] = passChars[RandomNumberGenerator.GetInt32(0, passChars.Length)];
        return new string(p);
    }

如何在c#中生成随机密码。 输出:(https://prnt.sc/11fac8v) 运行:https://onlinegdb.com/HJe5OHBLu

    private static Random random = new Random();
    public static void Main()
    {
        Console.WriteLine("Random password with length of 8 character.");
        Console.WriteLine("===========================================");
        Console.WriteLine("Capital latters : 2");
        Console.WriteLine("Number latters : 2");
        Console.WriteLine("Special latters : 2");
        Console.WriteLine("Small latters : 2");
        Console.WriteLine("===========================================");
        Console.Write("The Random Password : ");
        Console.WriteLine(RandomStringCap(2) + RandomStringNum(2) + RandomStringSpe(2) + RandomStringSml(2));
        Console.WriteLine("===========================================");
    }
    public static string RandomStringCap(int length)
    {
        const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        return new string(Enumerable.Repeat(chars, length)
                         .Select(s => s[random.Next(s.Length)]).ToArray());
    }
    public static string RandomStringNum(int length)
    {
        const string chars = "0123456789";
        return new string(Enumerable.Repeat(chars, length)
                         .Select(s => s[random.Next(s.Length)]).ToArray());
    }
    public static string RandomStringSml(int length)
    {
        const string chars = "abcdefghijklmnopqrstuvwxyz";
        return new string(Enumerable.Repeat(chars, length)
                         .Select(s => s[random.Next(s.Length)]).ToArray());
    }
    public static string RandomStringSpe(int length)
    {
        const string chars = "!@#$%^&*_-=+";
        return new string(Enumerable.Repeat(chars, length)
                         .Select(s => s[random.Next(s.Length)]).ToArray());
    }

我喜欢生成密码,就像生成软件密钥一样。您应该从遵循良好实践的字符数组中进行选择。采用@Radu094回答的内容并修改它以遵循良好的实践。不要把每个字母都放在字符数组中。有些信在电话里更难读懂。

您还应该考虑对生成的密码使用校验和,以确保它是由您生成的。实现这一点的一个好方法是使用LUHN算法。

public string GenerateToken(int length)
{
    using (RNGCryptoServiceProvider cryptRNG = new RNGCryptoServiceProvider())
    {
        byte[] tokenBuffer = new byte[length];
        cryptRNG.GetBytes(tokenBuffer);
        return Convert.ToBase64String(tokenBuffer);
    }
}

(你也可以让这个方法所在的类实现IDisposable,持有对RNGCryptoServiceProvider的引用,并正确地处理它,以避免重复实例化它。)

It's been noted that as this returns a base-64 string, the output length is always a multiple of 4, with the extra space using = as a padding character. The length parameter specifies the length of the byte buffer, not the output string (and is therefore perhaps not the best name for that parameter, now I think about it). This controls how many bytes of entropy the password will have. However, because base-64 uses a 4-character block to encode each 3 bytes of input, if you ask for a length that's not a multiple of 3, there will be some extra "space", and it'll use = to fill the extra.

If you don't like using base-64 strings for any reason, you can replace the Convert.ToBase64String() call with either a conversion to regular string, or with any of the Encoding methods; eg. Encoding.UTF8.GetString(tokenBuffer) - just make sure you pick a character set that can represent the full range of values coming out of the RNG, and that produces characters that are compatible with wherever you're sending or storing this. Using Unicode, for example, tends to give a lot of Chinese characters. Using base-64 guarantees a widely-compatible set of characters, and the characteristics of such a string shouldn't make it any less secure as long as you use a decent hashing algorithm.