我需要生成具有指定长度的加密强随机字母数字字符串,仅使用以下字符。
有没有办法在 C# 中实现这一点?
class RandomNumberGenerator
生成加密安全的随机数来执行此操作,例如:
string allowed = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
int strlen = 10; // Or whatever
char[] randomChars = new char[strlen];
for (int i = 0; i < strlen; i++)
{
randomChars[i] = allowed[RandomNumberGenerator.GetInt32(0, allowed.Length)];
}
string result = new string(randomChars);
Console.WriteLine(result);
尝试以下操作:
int randomArrayLength = 256;
char[] characters = {
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
int numberOfChar = characters.Length;
Random rand = new Random();
string results = string.Join("", Enumerable.Range(0, randomArrayLength).Select(x => characters[rand.Next(numberOfChar)]));