using
System;
using
System.Security.Cryptography;
using
System.Runtime.CompilerServices;
public
static
class
PasswordGenerator
{
private
static
readonly
RNGCryptoServiceProvider SharedRng =
new
RNGCryptoServiceProvider();
private
const
string
CharSet =
"ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%^&*()-_=+[]{}|;:,.<>?"
;
private
const
int
CharSetSize = CharSet.Length;
public
static
string
GenStr(
int
length)
{
var
result =
new
char
[length];
Span<
byte
> bytes =
stackalloc
byte
[length * 4];
SharedRng.GetBytes(bytes);
for
(
int
i = 0, j = 0; i < length; i++, j += 4)
{
uint
randomIndex = (
uint
)(bytes[j] << 24 | bytes[j + 1] << 16 | bytes[j + 2] << 8 | bytes[j + 3]);
result[i] = CharSet[randomIndex % CharSetSize];
}
return
new
string
(result);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private
static
uint
GetRandomUInt32(Span<
byte
> bytes,
ref
int
index)
{
return
(
uint
)(bytes[index] << 24 | bytes[index + 1] << 16 | bytes[index + 2] << 8 | bytes[index + 3]);
}
}
class
Program
{
static
void
Main()
{
string
password = PasswordGenerator.GenStr(32);
Console.WriteLine(password);
}
}