Oto klasa/Sposób, w oparciu o źródła Membership.GeneratePassword
o który działa na .NET Rdzeń:
public static class Password
{
private static readonly char[] Punctuations = "[email protected]#$%^&*()_-+=[{]};:>|./?".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);
}
}
}
Mam pominąć pętlę do...while
nad CrossSiteScriptingValidation.IsDangerousString
. Możesz go dodać z powrotem, jeśli jej potrzebujesz.
go używać tak:
var password = Password.Generate(32, 12);
Ponadto, upewnij się odwoływać "System.Security.Cryptography.Algorithms": "4.2.0"
.
Co robi "System.Web.Security.Membership.GeneratePassword', czego nie chcesz? – bsoulier
Wszystko, co robi ta metoda, to [wygeneruj losowe hasło] (https://msdn.microsoft.com/en-us/library/system.web.security.membership.generatepassword (v = vs.110) .aspx), które super łatwe do zrobienia samemu. – DavidG