我如何在c#中生成一个随机的8个字符的字母数字字符串?
当前回答
更新。net 6。RNGCryptoServiceProvider被标记为obsolete。相反,调用RandomNumberGenerator.Create()。答案中的代码已相应更新。
根据评论更新。原始实现生成a-h的时间为1.95%,其余字符的时间为1.56%。更新生成所有字符~1.61%的时间。 FRAMEWORK支持- . net Core 3(以及未来支持. net Standard 2.1或以上版本的平台)提供了一个加密的方法RandomNumberGenerator.GetInt32(),在期望的范围内生成一个随机整数。
与目前提出的一些替代方案不同,这个方案在密码学上是合理的。
using System;
using System.Security.Cryptography;
using System.Text;
namespace UniqueKey
{
public class KeyGenerator
{
internal static readonly char[] chars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
public static string GetUniqueKey(int size)
{
byte[] data = new byte[4*size];
using (var crypto = RandomNumberGenerator.Create())
{
crypto.GetBytes(data);
}
StringBuilder result = new StringBuilder(size);
for (int i = 0; i < size; i++)
{
var rnd = BitConverter.ToUInt32(data, i * 4);
var idx = rnd % chars.Length;
result.Append(chars[idx]);
}
return result.ToString();
}
public static string GetUniqueKeyOriginal_BIASED(int size)
{
char[] chars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
byte[] data = new byte[size];
using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider())
{
crypto.GetBytes(data);
}
StringBuilder result = new StringBuilder(size);
foreach (byte b in data)
{
result.Append(chars[b % (chars.Length)]);
}
return result.ToString();
}
}
}
基于这里对替代方案的讨论,并根据下面的评论进行了更新/修改。
下面是一个小型测试工具,演示了旧输出和更新输出中的字符分布。关于随机性分析的深入讨论,请访问random.org。
using System;
using System.Collections.Generic;
using System.Linq;
using UniqueKey;
namespace CryptoRNGDemo
{
class Program
{
const int REPETITIONS = 1000000;
const int KEY_SIZE = 32;
static void Main(string[] args)
{
Console.WriteLine("Original BIASED implementation");
PerformTest(REPETITIONS, KEY_SIZE, KeyGenerator.GetUniqueKeyOriginal_BIASED);
Console.WriteLine("Updated implementation");
PerformTest(REPETITIONS, KEY_SIZE, KeyGenerator.GetUniqueKey);
Console.ReadKey();
}
static void PerformTest(int repetitions, int keySize, Func<int, string> generator)
{
Dictionary<char, int> counts = new Dictionary<char, int>();
foreach (var ch in UniqueKey.KeyGenerator.chars) counts.Add(ch, 0);
for (int i = 0; i < REPETITIONS; i++)
{
var key = generator(KEY_SIZE);
foreach (var ch in key) counts[ch]++;
}
int totalChars = counts.Values.Sum();
foreach (var ch in UniqueKey.KeyGenerator.chars)
{
Console.WriteLine($"{ch}: {(100.0 * counts[ch] / totalChars).ToString("#.000")}%");
}
}
}
}
更新7/25/2022
根据评论中的一个问题,我很好奇这种分布是否真的是随机的。
我不是统计学家,但我可以在电视上扮演一个。如果一位真正的统计学家愿意插话,那将是最受欢迎的。
有62个可能的输出值(A-Za-Z0-9)和int。用于选择数组索引的最大值。int。MaxValue % 62是1,所以一个字符被选中的概率是其他字符的十亿分之一。我们可以通过在索引之前随机旋转输出值数组来进一步减少选择偏差。
t检验或其他统计度量将是确定输出结果中是否存在偏差的最佳方法,但这不是我在午休时间可以完成的工作,因此我留给您对上述代码的修改,以度量与预期的偏差。注意,它趋于零。
using System.Security.Cryptography;
using System.Text;
const int REPETITIONS = 1_000_000;
const int KEY_SIZE = 32;
int TASK_COUNT = Environment.ProcessorCount - 1;
var expectedPercentage = 100.0 / KeyGenerator.chars.Length;
var done = false;
var iterationNr = 1;
var totalRandomSymbols = 0L;
var grandTotalCounts = new Dictionary<char, long>();
foreach (var ch in KeyGenerator.chars) grandTotalCounts.Add(ch, 0);
while (!done)
{
var experiments = Enumerable.Range(0, TASK_COUNT).Select(i => Task.Run(Experiment)).ToArray();
Task.WaitAll(experiments);
var totalCountsThisRun = experiments.SelectMany(e => e.Result)
.GroupBy(e => e.Key)
.Select(e => new { e.Key, Count = e.Select(_ => _.Value).Sum() })
.ToDictionary(e => e.Key, e => e.Count);
foreach (var ch in KeyGenerator.chars)
grandTotalCounts[ch] += totalCountsThisRun[ch];
var totalChars = grandTotalCounts.Values.Sum();
totalRandomSymbols += totalChars;
var distributionScores = KeyGenerator.chars.Select(ch =>
new
{
Symbol = ch,
OverUnder = (100.0 * grandTotalCounts[ch] / totalChars) - expectedPercentage
});
Console.WriteLine($"Iteration {iterationNr++}. Total random symbols: {totalRandomSymbols:N0}");
foreach (var chWithValue in distributionScores.OrderByDescending(c => c.OverUnder))
{
Console.WriteLine($"{chWithValue.Symbol}: {chWithValue.OverUnder:#.00000}%");
}
done = Console.KeyAvailable;
}
Dictionary<char, long> Experiment()
{
var counts = new Dictionary<char, long>();
foreach (var ch in KeyGenerator.chars) counts.Add(ch, 0);
for (int i = 0; i < REPETITIONS; i++)
{
var key = KeyGenerator.GetUniqueKey(KEY_SIZE);
foreach (var ch in key) counts[ch]++;
}
return counts;
}
public class KeyGenerator
{
internal static readonly char[] chars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
public static string GetUniqueKey(int size)
{
byte[] data = new byte[4 * size];
using (var crypto = RandomNumberGenerator.Create())
{
crypto.GetBytes(data);
}
StringBuilder result = new StringBuilder(size);
for (int i = 0; i < size; i++)
{
var rnd = BitConverter.ToUInt32(data, i * 4);
var idx = rnd % chars.Length;
result.Append(chars[idx]);
}
return result.ToString();
}
}
其他回答
一种简单且高度安全的方法可能是生成加密Aes密钥。
public static string GenerateRandomString()
{
using Aes crypto = Aes.Create();
crypto.GenerateKey();
return Convert.ToBase64String(crypto.Key);
}
更新。net 6。RNGCryptoServiceProvider被标记为obsolete。相反,调用RandomNumberGenerator.Create()。答案中的代码已相应更新。
根据评论更新。原始实现生成a-h的时间为1.95%,其余字符的时间为1.56%。更新生成所有字符~1.61%的时间。 FRAMEWORK支持- . net Core 3(以及未来支持. net Standard 2.1或以上版本的平台)提供了一个加密的方法RandomNumberGenerator.GetInt32(),在期望的范围内生成一个随机整数。
与目前提出的一些替代方案不同,这个方案在密码学上是合理的。
using System;
using System.Security.Cryptography;
using System.Text;
namespace UniqueKey
{
public class KeyGenerator
{
internal static readonly char[] chars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
public static string GetUniqueKey(int size)
{
byte[] data = new byte[4*size];
using (var crypto = RandomNumberGenerator.Create())
{
crypto.GetBytes(data);
}
StringBuilder result = new StringBuilder(size);
for (int i = 0; i < size; i++)
{
var rnd = BitConverter.ToUInt32(data, i * 4);
var idx = rnd % chars.Length;
result.Append(chars[idx]);
}
return result.ToString();
}
public static string GetUniqueKeyOriginal_BIASED(int size)
{
char[] chars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
byte[] data = new byte[size];
using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider())
{
crypto.GetBytes(data);
}
StringBuilder result = new StringBuilder(size);
foreach (byte b in data)
{
result.Append(chars[b % (chars.Length)]);
}
return result.ToString();
}
}
}
基于这里对替代方案的讨论,并根据下面的评论进行了更新/修改。
下面是一个小型测试工具,演示了旧输出和更新输出中的字符分布。关于随机性分析的深入讨论,请访问random.org。
using System;
using System.Collections.Generic;
using System.Linq;
using UniqueKey;
namespace CryptoRNGDemo
{
class Program
{
const int REPETITIONS = 1000000;
const int KEY_SIZE = 32;
static void Main(string[] args)
{
Console.WriteLine("Original BIASED implementation");
PerformTest(REPETITIONS, KEY_SIZE, KeyGenerator.GetUniqueKeyOriginal_BIASED);
Console.WriteLine("Updated implementation");
PerformTest(REPETITIONS, KEY_SIZE, KeyGenerator.GetUniqueKey);
Console.ReadKey();
}
static void PerformTest(int repetitions, int keySize, Func<int, string> generator)
{
Dictionary<char, int> counts = new Dictionary<char, int>();
foreach (var ch in UniqueKey.KeyGenerator.chars) counts.Add(ch, 0);
for (int i = 0; i < REPETITIONS; i++)
{
var key = generator(KEY_SIZE);
foreach (var ch in key) counts[ch]++;
}
int totalChars = counts.Values.Sum();
foreach (var ch in UniqueKey.KeyGenerator.chars)
{
Console.WriteLine($"{ch}: {(100.0 * counts[ch] / totalChars).ToString("#.000")}%");
}
}
}
}
更新7/25/2022
根据评论中的一个问题,我很好奇这种分布是否真的是随机的。
我不是统计学家,但我可以在电视上扮演一个。如果一位真正的统计学家愿意插话,那将是最受欢迎的。
有62个可能的输出值(A-Za-Z0-9)和int。用于选择数组索引的最大值。int。MaxValue % 62是1,所以一个字符被选中的概率是其他字符的十亿分之一。我们可以通过在索引之前随机旋转输出值数组来进一步减少选择偏差。
t检验或其他统计度量将是确定输出结果中是否存在偏差的最佳方法,但这不是我在午休时间可以完成的工作,因此我留给您对上述代码的修改,以度量与预期的偏差。注意,它趋于零。
using System.Security.Cryptography;
using System.Text;
const int REPETITIONS = 1_000_000;
const int KEY_SIZE = 32;
int TASK_COUNT = Environment.ProcessorCount - 1;
var expectedPercentage = 100.0 / KeyGenerator.chars.Length;
var done = false;
var iterationNr = 1;
var totalRandomSymbols = 0L;
var grandTotalCounts = new Dictionary<char, long>();
foreach (var ch in KeyGenerator.chars) grandTotalCounts.Add(ch, 0);
while (!done)
{
var experiments = Enumerable.Range(0, TASK_COUNT).Select(i => Task.Run(Experiment)).ToArray();
Task.WaitAll(experiments);
var totalCountsThisRun = experiments.SelectMany(e => e.Result)
.GroupBy(e => e.Key)
.Select(e => new { e.Key, Count = e.Select(_ => _.Value).Sum() })
.ToDictionary(e => e.Key, e => e.Count);
foreach (var ch in KeyGenerator.chars)
grandTotalCounts[ch] += totalCountsThisRun[ch];
var totalChars = grandTotalCounts.Values.Sum();
totalRandomSymbols += totalChars;
var distributionScores = KeyGenerator.chars.Select(ch =>
new
{
Symbol = ch,
OverUnder = (100.0 * grandTotalCounts[ch] / totalChars) - expectedPercentage
});
Console.WriteLine($"Iteration {iterationNr++}. Total random symbols: {totalRandomSymbols:N0}");
foreach (var chWithValue in distributionScores.OrderByDescending(c => c.OverUnder))
{
Console.WriteLine($"{chWithValue.Symbol}: {chWithValue.OverUnder:#.00000}%");
}
done = Console.KeyAvailable;
}
Dictionary<char, long> Experiment()
{
var counts = new Dictionary<char, long>();
foreach (var ch in KeyGenerator.chars) counts.Add(ch, 0);
for (int i = 0; i < REPETITIONS; i++)
{
var key = KeyGenerator.GetUniqueKey(KEY_SIZE);
foreach (var ch in key) counts[ch]++;
}
return counts;
}
public class KeyGenerator
{
internal static readonly char[] chars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
public static string GetUniqueKey(int size)
{
byte[] data = new byte[4 * size];
using (var crypto = RandomNumberGenerator.Create())
{
crypto.GetBytes(data);
}
StringBuilder result = new StringBuilder(size);
for (int i = 0; i < size; i++)
{
var rnd = BitConverter.ToUInt32(data, i * 4);
var idx = rnd % chars.Length;
result.Append(chars[idx]);
}
return result.ToString();
}
}
对于加密和非加密,有效地:
public static string GenerateRandomString(int length, string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890") =>
new Random().GenerateRandomString(length, charset);
public static string GenerateRandomString(this Random random, int length, string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890") =>
RandomString(random.NextBytes, length, charset.ToCharArray());
public static string GenerateRandomCryptoString(int length, string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890")
{
using (var crypto = new System.Security.Cryptography.RNGCryptoServiceProvider())
return crypto.GenerateRandomCryptoString(length, charset);
}
public static string GenerateRandomCryptoString(this RNGCryptoServiceProvider random, int length, string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890") =>
RandomString(random.GetBytes, length, charset.ToCharArray());
private static string RandomString(Action<byte[]> fillRandomBuffer, int length, char[] charset)
{
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), $"{nameof(length)} must be greater or equal to 0");
if (charset is null)
throw new ArgumentNullException(nameof(charset));
if (charset.Length == 0)
throw new ArgumentException($"{nameof(charset)} must contain at least 1 character", nameof(charset));
var maxIdx = charset.Length;
var chars = new char[length];
var randomBuffer = new byte[length * 4];
fillRandomBuffer(randomBuffer);
for (var i = 0; i < length; i++)
chars[i] = charset[BitConverter.ToUInt32(randomBuffer, i * 4) % maxIdx];
return new string(chars);
}
使用生成器和LINQ。不是最快的选项(特别是因为它不会一次生成所有字节),但相当整洁和可扩展:
private static readonly Random _random = new Random();
public static string GenerateRandomString(int length, string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890") =>
new string(_random.GetGenerator().RandomChars(charset.ToCharArray()).Take(length).ToArray());
public static string GenerateRandomCryptoString(int length, string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890")
{
using (var crypto = new System.Security.Cryptography.RNGCryptoServiceProvider())
return new string(crypto.GetGenerator().RandomChars(charset.ToCharArray()).Take(length).ToArray());
}
public static IEnumerable<char> RandomChars(this Func<uint, IEnumerable<uint>> randomGenerator, char[] charset)
{
if (charset is null)
throw new ArgumentNullException(nameof(charset));
if (charset.Length == 0)
throw new ArgumentException($"{nameof(charset)} must contain at least 1 character", nameof(charset));
return randomGenerator((uint)charset.Length).Select(r => charset[r]);
}
public static Func<uint, IEnumerable<uint>> GetGenerator(this Random random)
{
if (random is null)
throw new ArgumentNullException(nameof(random));
return GeneratorFunc_Inner;
IEnumerable<uint> GeneratorFunc_Inner(uint maxValue)
{
if (maxValue > int.MaxValue)
throw new ArgumentOutOfRangeException(nameof(maxValue));
return Generator_Inner();
IEnumerable<uint> Generator_Inner()
{
var randomBytes = new byte[4];
while (true)
{
random.NextBytes(randomBytes);
yield return BitConverter.ToUInt32(randomBytes, 0) % maxValue;
}
}
}
}
public static Func<uint, IEnumerable<uint>> GetGenerator(this System.Security.Cryptography.RNGCryptoServiceProvider random)
{
if (random is null)
throw new ArgumentNullException(nameof(random));
return Generator_Inner;
IEnumerable<uint> Generator_Inner(uint maxValue)
{
var randomBytes = new byte[4];
while (true)
{
random.GetBytes(randomBytes);
yield return BitConverter.ToUInt32(randomBytes, 0) % maxValue;
}
}
}
一个更简单的版本,使用LINQ只用于非加密字符串:
private static readonly Random _random = new Random();
public static string RandomString(int length, string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890") =>
new string(_random.GenerateChars(charset).Take(length).ToArray());
public static IEnumerable<char> GenerateChars(this Random random, string charset)
{
if (charset is null) throw new ArgumentNullException(nameof(charset));
if (charset.Length == 0) throw new ArgumentException($"{nameof(charset)} must contain at least 1 character", nameof(charset));
return random.Generator(charset.Length).Select(r => charset[r]);
}
public static IEnumerable<int> Generator(this Random random, int maxValue)
{
if (random is null) throw new ArgumentNullException(nameof(random));
return Generator_Inner();
IEnumerable<int> Generator_Inner() { while (true) yield return random.Next(maxValue); }
}
我听说LINQ是新的黑色,所以下面是我使用LINQ的尝试:
private static Random random = new Random();
public static string RandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
(注意:Random类的使用使得它不适用于任何与安全性相关的事情,比如创建密码或令牌。如果你需要强随机数生成器,请使用RNGCryptoServiceProvider类。)
非常简单的解决方案。它使用ASCII值,只是在它们之间生成“随机”字符。
public static class UsernameTools
{
public static string GenerateRandomUsername(int length = 10)
{
Random random = new Random();
StringBuilder sbuilder = new StringBuilder();
for (int x = 0; x < length; ++x)
{
sbuilder.Append((char)random.Next(33, 126));
}
return sbuilder.ToString();
}
}