英文:
How can I generate cryptographically strong random strings with a given length
问题
需要生成指定长度的具有密码强度的随机字母数字字符串,只使用以下字符:
- A-Z
- a-z
- 0-9
在C#中是否有实现这个功能的方法?
英文:
I need to generate cryptographically strong random alphanumeric strings with a specified length, only using the following characters.
- A-Z
- a-z
- 0-9
Is there a way to accomplish this in C#?
答案1
得分: 3
你可以使用 class RandomNumberGenerator
来生成具有密码学安全性的随机数,以执行这项任务,例如:
string allowed = "ABCDEFGHIJKLMONOPQRSTUVWXYZabcdefghijklmonopqrstuvwxyz0123456789";
int strlen = 10; // 或其他值
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);
英文:
You can use class RandomNumberGenerator
to generate cryptographically-secure random numbers to do this, for example:
string allowed = "ABCDEFGHIJKLMONOPQRSTUVWXYZabcdefghijklmonopqrstuvwxyz0123456789";
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);
答案2
得分: -3
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)]));
英文:
Try following :
<!-- begin snippet: js hide: false console: true babel: false -->
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)]));
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论