aspnetcore(netcoreapp1.0)中System.Web.Security.Membership.GeneratePassword的替代方案

时间:2016-08-17 11:28:13

标签: asp.net asp.net-mvc asp.net-core asp.net-core-1.0 .net-standard-1.5

System.Web.Security.Membership.GeneratePasswordAspNetCore)中是否有netcoreapp1.0替代。

最简单的方法是使用一个足够长的Guid.NewGuid().ToString("n")来配合密码,但它不是完全随机的。

1 个答案:

答案 0 :(得分:28)

这是一个类/方法,基于适用于.NET Core的Membership.GeneratePassword的源代码:

public static class Password
{
    private static readonly char[] Punctuations = "!@#$%^&*()_-+=[{]};:>|./?".ToCharArray();

    public static string Generate(int length, int numberOfNonAlphanumericCharacters)
    {
        if (length < 1 || length > 128)
        {
            throw new ArgumentException(nameof(length));
        }

        if (numberOfNonAlphanumericCharacters > length || numberOfNonAlphanumericCharacters < 0)
        {
            throw new ArgumentException(nameof(numberOfNonAlphanumericCharacters));
        }

        using (var rng = RandomNumberGenerator.Create())
        {
            var byteBuffer = new byte[length];

            rng.GetBytes(byteBuffer);

            var count = 0;
            var characterBuffer = new char[length];

            for (var iter = 0; iter < length; iter++)
            {
                var i = byteBuffer[iter] % 87;

                if (i < 10)
                {
                    characterBuffer[iter] = (char)('0' + i);
                }
                else if (i < 36)
                {
                    characterBuffer[iter] = (char)('A' + i - 10);
                }
                else if (i < 62)
                {
                    characterBuffer[iter] = (char)('a' + i - 36);
                }
                else
                {
                    characterBuffer[iter] = Punctuations[i - 62];
                    count++;
                }
            }

            if (count >= numberOfNonAlphanumericCharacters)
            {
                return new string(characterBuffer);
            }

            int j;
            var rand = new Random();

            for (j = 0; j < numberOfNonAlphanumericCharacters - count; j++)
            {
                int k;
                do
                {
                    k = rand.Next(0, length);
                }
                while (!char.IsLetterOrDigit(characterBuffer[k]));

                characterBuffer[k] = Punctuations[rand.Next(0, Punctuations.Length)];
            }

            return new string(characterBuffer);
        }
    }
}

我在CrossSiteScriptingValidation.IsDangerousString上省略了do...while循环。如果需要,您可以将其添加回自己。

你这样使用它:

var password = Password.Generate(32, 12);

另外,请务必参考"System.Security.Cryptography.Algorithms": "4.2.0"