我如何在c#中生成一个随机的8个字符的字母数字字符串?
当前回答
非常简单的解决方案。它使用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();
}
}
其他回答
这是我从Dot Net Perls的Sam Allen那里偷来的一个例子
如果你只需要8个字符,那么在系统中使用Path.GetRandomFileName()。IO命名空间。Sam说使用“Path.”这里的GetRandomFileName方法有时更优越,因为它使用RNGCryptoServiceProvider来获得更好的随机性。然而,它被限制为11个随机字符。”
GetRandomFileName总是返回一个12个字符的字符串,第9个字符是句点。所以你需要去掉句点(因为这不是随机的),然后从字符串中取出8个字符。实际上,你可以只取前8个字符而不用考虑句点。
public string Get8CharacterRandomString()
{
string path = Path.GetRandomFileName();
path = path.Replace(".", ""); // Remove period.
return path.Substring(0, 8); // Return 8 character string
}
PS:谢谢,Sam
问:为什么我要浪费时间使用Enumerable ?范围,而不是输入“ABCDEFGHJKLMNOPQRSTUVWXYZ0123456789”?
using System;
using System.Collections.Generic;
using System.Linq;
public class Test
{
public static void Main()
{
var randomCharacters = GetRandomCharacters(8, true);
Console.WriteLine(new string(randomCharacters.ToArray()));
}
private static List<char> getAvailableRandomCharacters(bool includeLowerCase)
{
var integers = Enumerable.Empty<int>();
integers = integers.Concat(Enumerable.Range('A', 26));
integers = integers.Concat(Enumerable.Range('0', 10));
if ( includeLowerCase )
integers = integers.Concat(Enumerable.Range('a', 26));
return integers.Select(i => (char)i).ToList();
}
public static IEnumerable<char> GetRandomCharacters(int count, bool includeLowerCase)
{
var characters = getAvailableRandomCharacters(includeLowerCase);
var random = new Random();
var result = Enumerable.Range(0, count)
.Select(_ => characters[random.Next(characters.Count)]);
return result;
}
}
答案:魔术弦不好。有没有人注意到在我的字符串顶部没有“I”?我妈妈教我不要用魔法弦就是因为这个原因……
注意事项1:正如许多像@dtb这样的人所说,不要使用系统。随机的,如果你需要密码安全…
注2:这个答案不是最有效或最短的,但我想用空间把答案和问题分开。我回答这个问题的目的,更多的是为了警告人们不要使用神奇的字符串,而不是提供一个花哨的创新答案。
在查看了其他答案并考虑了CodeInChaos的评论,以及CodeInChaos仍然有偏见(尽管较少)的答案之后,我认为需要一个最终的终极剪切和粘贴解决方案。所以在更新我的答案时,我决定全力以赴。
For an up to date version of this code, please visit the new Hg repository on Bitbucket: https://bitbucket.org/merarischroeder/secureswiftrandom. I recommend you copy and paste the code from: https://bitbucket.org/merarischroeder/secureswiftrandom/src/6c14b874f34a3f6576b0213379ecdf0ffc7496ea/Code/Alivate.SolidSwiftRandom/SolidSwiftRandom.cs?at=default&fileviewer=file-view-default (make sure you click the Raw button to make it easier to copy and make sure you have the latest version, I think this link goes to a specific version of the code, not the latest).
更新说明:
Relating to some other answers - If you know the length of the output, you don't need a StringBuilder, and when using ToCharArray, this creates and fills the array (you don't need to create an empty array first) Relating to some other answers - You should use NextBytes, rather than getting one at a time for performance Technically you could pin the byte array for faster access.. it's usually worth it when your iterating more than 6-8 times over a byte array. (Not done here) Use of RNGCryptoServiceProvider for best randomness Use of caching of a 1MB buffer of random data - benchmarking shows cached single bytes access speed is ~1000x faster - taking 9ms over 1MB vs 989ms for uncached. Optimised rejection of bias zone within my new class.
问题的最终解决方案:
static char[] charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".ToCharArray();
static int byteSize = 256; //Labelling convenience
static int biasZone = byteSize - (byteSize % charSet.Length);
public string GenerateRandomString(int Length) //Configurable output string length
{
byte[] rBytes = new byte[Length]; //Do as much before and after lock as possible
char[] rName = new char[Length];
SecureFastRandom.GetNextBytesMax(rBytes, biasZone);
for (var i = 0; i < Length; i++)
{
rName[i] = charSet[rBytes[i] % charSet.Length];
}
return new string(rName);
}
但是你需要我的新(未经测试的)类:
/// <summary>
/// My benchmarking showed that for RNGCryptoServiceProvider:
/// 1. There is negligable benefit of sharing RNGCryptoServiceProvider object reference
/// 2. Initial GetBytes takes 2ms, and an initial read of 1MB takes 3ms (starting to rise, but still negligable)
/// 2. Cached is ~1000x faster for single byte at a time - taking 9ms over 1MB vs 989ms for uncached
/// </summary>
class SecureFastRandom
{
static byte[] byteCache = new byte[1000000]; //My benchmark showed that an initial read takes 2ms, and an initial read of this size takes 3ms (starting to raise)
static int lastPosition = 0;
static int remaining = 0;
/// <summary>
/// Static direct uncached access to the RNGCryptoServiceProvider GetBytes function
/// </summary>
/// <param name="buffer"></param>
public static void DirectGetBytes(byte[] buffer)
{
using (var r = new RNGCryptoServiceProvider())
{
r.GetBytes(buffer);
}
}
/// <summary>
/// Main expected method to be called by user. Underlying random data is cached from RNGCryptoServiceProvider for best performance
/// </summary>
/// <param name="buffer"></param>
public static void GetBytes(byte[] buffer)
{
if (buffer.Length > byteCache.Length)
{
DirectGetBytes(buffer);
return;
}
lock (byteCache)
{
if (buffer.Length > remaining)
{
DirectGetBytes(byteCache);
lastPosition = 0;
remaining = byteCache.Length;
}
Buffer.BlockCopy(byteCache, lastPosition, buffer, 0, buffer.Length);
lastPosition += buffer.Length;
remaining -= buffer.Length;
}
}
/// <summary>
/// Return a single byte from the cache of random data.
/// </summary>
/// <returns></returns>
public static byte GetByte()
{
lock (byteCache)
{
return UnsafeGetByte();
}
}
/// <summary>
/// Shared with public GetByte and GetBytesWithMax, and not locked to reduce lock/unlocking in loops. Must be called within lock of byteCache.
/// </summary>
/// <returns></returns>
static byte UnsafeGetByte()
{
if (1 > remaining)
{
DirectGetBytes(byteCache);
lastPosition = 0;
remaining = byteCache.Length;
}
lastPosition++;
remaining--;
return byteCache[lastPosition - 1];
}
/// <summary>
/// Rejects bytes which are equal to or greater than max. This is useful for ensuring there is no bias when you are modulating with a non power of 2 number.
/// </summary>
/// <param name="buffer"></param>
/// <param name="max"></param>
public static void GetBytesWithMax(byte[] buffer, byte max)
{
if (buffer.Length > byteCache.Length / 2) //No point caching for larger sizes
{
DirectGetBytes(buffer);
lock (byteCache)
{
UnsafeCheckBytesMax(buffer, max);
}
}
else
{
lock (byteCache)
{
if (buffer.Length > remaining) //Recache if not enough remaining, discarding remaining - too much work to join two blocks
DirectGetBytes(byteCache);
Buffer.BlockCopy(byteCache, lastPosition, buffer, 0, buffer.Length);
lastPosition += buffer.Length;
remaining -= buffer.Length;
UnsafeCheckBytesMax(buffer, max);
}
}
}
/// <summary>
/// Checks buffer for bytes equal and above max. Must be called within lock of byteCache.
/// </summary>
/// <param name="buffer"></param>
/// <param name="max"></param>
static void UnsafeCheckBytesMax(byte[] buffer, byte max)
{
for (int i = 0; i < buffer.Length; i++)
{
while (buffer[i] >= max)
buffer[i] = UnsafeGetByte(); //Replace all bytes which are equal or above max
}
}
}
对于历史-我对这个答案的旧解决方案,使用随机对象:
private static char[] charSet =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".ToCharArray();
static rGen = new Random(); //Must share, because the clock seed only has Ticks (~10ms) resolution, yet lock has only 20-50ns delay.
static int byteSize = 256; //Labelling convenience
static int biasZone = byteSize - (byteSize % charSet.Length);
static bool SlightlyMoreSecurityNeeded = true; //Configuration - needs to be true, if more security is desired and if charSet.Length is not divisible by 2^X.
public string GenerateRandomString(int Length) //Configurable output string length
{
byte[] rBytes = new byte[Length]; //Do as much before and after lock as possible
char[] rName = new char[Length];
lock (rGen) //~20-50ns
{
rGen.NextBytes(rBytes);
for (int i = 0; i < Length; i++)
{
while (SlightlyMoreSecurityNeeded && rBytes[i] >= biasZone) //Secure against 1/5 increased bias of index[0-7] values against others. Note: Must exclude where it == biasZone (that is >=), otherwise there's still a bias on index 0.
rBytes[i] = rGen.NextByte();
rName[i] = charSet[rBytes[i] % charSet.Length];
}
}
return new string(rName);
}
性能:
securefastrrandom -第一次运行= ~9-33ms。听不清。持续:5毫秒(有时高达13毫秒)超过10,000次迭代,单次平均迭代= 1.5微秒。注意:通常需要2个缓存刷新,但偶尔需要8个缓存刷新——这取决于有多少单个字节超出了偏置区域 随机-第一次运行= ~0-1ms。听不清。正在进行:5毫秒超过10,000次迭代。单次平均迭代= 0.5微秒。速度差不多。
还可以看看:
https://bitbucket.org/merarischroeder/number-range-with-no-bias/src https://stackoverflow.com/a/45118325/887092
这些联系是另一种方法。缓冲可以添加到这个新的代码库中,但最重要的是探索不同的方法来消除偏差,并对速度和利弊进行基准测试。
如果你的值不是完全随机的,但实际上可能依赖于某些东西——你可以计算出“某个东西”的md5或sha1哈希,然后将其截断为你想要的任何长度。
你也可以生成和截断一个guid。
对于加密和非加密,有效地:
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); }
}