如何在C#中生成随机的8个字符的字母数字字符串?
Random
该类的任何方法来生成密码。的播种的Random
熵极低,因此并不十分安全。对密码使用加密的PRNG。
如何在C#中生成随机的8个字符的字母数字字符串?
Random
该类的任何方法来生成密码。的播种的Random
熵极低,因此并不十分安全。对密码使用加密的PRNG。
Answers:
我听说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
如果需要强大的随机数生成器,请使用该类。)
return new string(Enumerable.Range(1, length).Select(_ => chars[random.Next(chars.Length)]).ToArray());
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var stringChars = new char[8];
var random = new Random();
for (int i = 0; i < stringChars.Length; i++)
{
stringChars[i] = chars[random.Next(chars.Length)];
}
var finalString = new String(stringChars);
不如Linq解决方案优雅。
(注意:使用Random
该类使该类不适用于任何与安全相关的事情,例如创建密码或令牌。RNGCryptoServiceProvider
如果需要强大的随机数生成器,请使用该类。)
GetRandomFileName
解决方案速度更快,但不允许对所使用的字符进行任何控制,最大长度为11个字符。道格拉斯(Douglas)的Guid
解决方案是闪电般的,但字符限制为A-F0-9,最大可能长度为32个字符。
GetRandomFileName
但是(a)您将失去性能优势,并且(b)您的代码将变得更加复杂。
System.Random
不适合安全性。
根据评论已更新。原始实现产生了大约1.95%的时间,其余字符大约产生了1.56%的时间。此更新会在大约1.61%的时间内生成所有字符。
框架支持-.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 (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider())
{
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")}%");
}
}
}
}
RNGCSP
摆在首位?)使用MOD索引到chars
数组意味着,除非你会得到偏置输出chars.Length
恰好是256的一个除数
4*maxSize
随机字节,然后使用(UInt32)(BitConverter.ToInt32(data,4*i)% chars.Length
。我也会用GetBytes
代替GetNonZeroBytes
。最后,您可以删除对的第一个呼叫GetNonZeroBytes
。您没有使用它的结果。
解决方案1-最大的“范围”和最灵活的长度
string get_unique_string(int string_length) {
using(var rng = new RNGCryptoServiceProvider()) {
var bit_count = (string_length * 6);
var byte_count = ((bit_count + 7) / 8); // rounded up
var bytes = new byte[byte_count];
rng.GetBytes(bytes);
return Convert.ToBase64String(bytes);
}
}
与GUID相比,此解决方案具有更大的范围,因为GUID具有几个始终相同且因此不是随机的固定位,例如十六进制的13个字符始终为“ 4”-至少在版本6 GUID中。
该解决方案还允许您生成任意长度的字符串。
解决方案2-一行代码-最多可容纳22个字符
Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(0, 8);
只要解决方案1,您就无法生成字符串而且由于GUID中的固定位,该字符串的范围也不相同,但是在很多情况下,这样做就可以了。
解决方案3-代码少一点
Guid.NewGuid().ToString("n").Substring(0, 8);
主要出于历史目的将其保留在这里。它使用的代码少一点,但是以减少范围为代价-因为它使用十六进制而不是base64,与其他解决方案相比,它需要更多的字符来表示相同的范围。
这意味着更多的碰撞机会-用100,000个8个字符串的迭代进行测试以生成一个重复项。
这是我从Dot Net Perls的 Sam Allen例子中窃取的一个例子
如果只需要8个字符,则在System.IO名称空间中使用Path.GetRandomFileName()。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:谢谢山姆
我的代码的主要目标是:
第一个属性是通过将64位值乘以字母大小取模来实现的。对于小字母(例如问题中的62个字符),这导致可忽略的偏差。通过使用RNGCryptoServiceProvider
代替实现第二和第三属性System.Random
。
using System;
using System.Security.Cryptography;
public static string GetRandomAlphanumericString(int length)
{
const string alphanumericCharacters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"abcdefghijklmnopqrstuvwxyz" +
"0123456789";
return GetRandomString(length, alphanumericCharacters);
}
public static string GetRandomString(int length, IEnumerable<char> characterSet)
{
if (length < 0)
throw new ArgumentException("length must not be negative", "length");
if (length > int.MaxValue / 8) // 250 million chars ought to be enough for anybody
throw new ArgumentException("length is too big", "length");
if (characterSet == null)
throw new ArgumentNullException("characterSet");
var characterArray = characterSet.Distinct().ToArray();
if (characterArray.Length == 0)
throw new ArgumentException("characterSet must not be empty", "characterSet");
var bytes = new byte[length * 8];
var result = new char[length];
using (var cryptoProvider = new RNGCryptoServiceProvider())
{
cryptoProvider.GetBytes(bytes);
}
for (int i = 0; i < length; i++)
{
ulong value = BitConverter.ToUInt64(bytes, i * 8);
result[i] = characterArray[value % (uint)characterArray.Length];
}
return new string(result);
}
最简单的:
public static string GetRandomAlphaNumeric()
{
return Path.GetRandomFileName().Replace(".", "").Substring(0, 8);
}
如果对char数组进行硬编码并依赖,则可以获得更好的性能。 System.Random
:
public static string GetRandomAlphaNumeric()
{
var chars = "abcdefghijklmnopqrstuvwxyz0123456789";
return new string(chars.Select(c => chars[random.Next(chars.Length)]).Take(8).ToArray());
}
如果您担心英语字母有时会改变并且可能会失去业务,可以避免进行硬编码,但效果会稍差一些(与 Path.GetRandomFileName
方法)
public static string GetRandomAlphaNumeric()
{
var chars = 'a'.To('z').Concat('0'.To('9')).ToList();
return new string(chars.Select(c => chars[random.Next(chars.Length)]).Take(8).ToArray());
}
public static IEnumerable<char> To(this char start, char end)
{
if (end < start)
throw new ArgumentOutOfRangeException("the end char should not be less than start char", innerException: null);
return Enumerable.Range(start, end - start + 1).Select(i => (char)i);
}
如果可以将它们作为扩展方法,则后两种方法看起来更好 System.Random
实例。
chars.Select
很麻烦,因为它依赖于输出大小最多为字母大小。
'a'.To('z')
?
chars.Select()
.Take(n)`仅在chars.Count >= n
。在您实际上不使用的序列上进行选择有点不直观,尤其是在具有隐式长度约束的情况下。我宁愿使用Enumerable.Range
或Enumerable.Repeat
。2)错误消息“结束字符应小于开始字符”是错误的舍入方式/缺少a not
。
chars.Count
是way > n
。我也没有得到直觉的部分。那确实使所有用法都不合Take
常理吗?我不相信。感谢您指出错字。
只是此线程中各种答案的一些性能比较:
// what's available
public static string possibleChars = "abcdefghijklmnopqrstuvwxyz";
// optimized (?) what's available
public static char[] possibleCharsArray = possibleChars.ToCharArray();
// optimized (precalculated) count
public static int possibleCharsAvailable = possibleChars.Length;
// shared randomization thingy
public static Random random = new Random();
// http://stackoverflow.com/a/1344242/1037948
public string LinqIsTheNewBlack(int num) {
return new string(
Enumerable.Repeat(possibleCharsArray, num)
.Select(s => s[random.Next(s.Length)])
.ToArray());
}
// http://stackoverflow.com/a/1344258/1037948
public string ForLoop(int num) {
var result = new char[num];
while(num-- > 0) {
result[num] = possibleCharsArray[random.Next(possibleCharsAvailable)];
}
return new string(result);
}
public string ForLoopNonOptimized(int num) {
var result = new char[num];
while(num-- > 0) {
result[num] = possibleChars[random.Next(possibleChars.Length)];
}
return new string(result);
}
public string Repeat(int num) {
return new string(new char[num].Select(o => possibleCharsArray[random.Next(possibleCharsAvailable)]).ToArray());
}
// http://stackoverflow.com/a/1518495/1037948
public string GenerateRandomString(int num) {
var rBytes = new byte[num];
random.NextBytes(rBytes);
var rName = new char[num];
while(num-- > 0)
rName[num] = possibleCharsArray[rBytes[num] % possibleCharsAvailable];
return new string(rName);
}
//SecureFastRandom - or SolidSwiftRandom
static string GenerateRandomString(int Length) //Configurable output string length
{
byte[] rBytes = new byte[Length];
char[] rName = new char[Length];
SolidSwiftRandom.GetNextBytesWithMax(rBytes, biasZone);
for (var i = 0; i < Length; i++)
{
rName[i] = charSet[rBytes[i] % charSet.Length];
}
return new string(rName);
}
在LinqPad中测试。对于10的字符串大小,生成:
- 来自Linq = chdgmevhcy [10]
- 来自循环= gtnoaryhxr [10]
- 从选择= rsndbztyby [10]
- 来自GenerateRandomString = owyefjjakj [10]
- 来自SecureFastRandom = VzougLYHYP [10]
- 来自SecureFastRandom-NoCache = oVQXNGmO1S [10]
而业绩数字往往略有不同,非常偶然NonOptimized
其实是快,有时ForLoop
和GenerateRandomString
切换谁是处于领先地位。
- LinqIsTheNewBlack(10000x)= 96762滴答已过去(9.6762 ms)
- ForLoop(10000x)=经过28970个滴答声(2.897 ms)
- ForLoopNonOptimized(10000x)=经过33336个滴答声(3.3336 ms)
- 重复(10000x)=经过78547个滴答声(7.8547 ms)
- GenerateRandomString(10000x)=经过27416个滴答声(2.7416 ms)
- SecureFastRandom(10000x)=最低经过13176个滴答声(5毫秒)[不同的机器]
- SecureFastRandom-NoCache(10000x)=最少经过39541滴答(17毫秒)[不同的计算机]
var many = 10000; Assert.AreEqual(many, new bool[many].Select(o => EachRandomizingMethod(10)).Distinct().Count());
,在其中替换EachRandomizingMethod
为...每种方法
一行代码 Membership.GeneratePassword()
可以解决问题:)
这是相同的演示。
Eric J.编写的代码很草率(很明显这是6年前的东西了……他可能今天不会写该代码),甚至还有一些问题。
与提出的某些替代方案不同,此替代方案在密码上是合理的。
Untrue ...密码中存在偏见(如评论中所述),bcdefgh
比其他密码更有可能(a
不是因为GetNonZeroBytes
它没有生成值为零的字节,所以偏见因为它a
是平衡的),所以从密码学上来说这并不是真正的合理。
这应该纠正所有问题。
public static string GetUniqueKey(int size = 6, string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890")
{
using (var crypto = new RNGCryptoServiceProvider())
{
var data = new byte[size];
// If chars.Length isn't a power of 2 then there is a bias if
// we simply use the modulus operator. The first characters of
// chars will be more probable than the last ones.
// buffer used if we encounter an unusable random byte. We will
// regenerate it in this buffer
byte[] smallBuffer = null;
// Maximum random number that can be used without introducing a
// bias
int maxRandom = byte.MaxValue - ((byte.MaxValue + 1) % chars.Length);
crypto.GetBytes(data);
var result = new char[size];
for (int i = 0; i < size; i++)
{
byte v = data[i];
while (v > maxRandom)
{
if (smallBuffer == null)
{
smallBuffer = new byte[1];
}
crypto.GetBytes(smallBuffer);
v = smallBuffer[0];
}
result[i] = chars[v % chars.Length];
}
return new string(result);
}
}
我们还使用自定义字符串random,但是我们将其实现为字符串的助手,因此它提供了一些灵活性...
public static string Random(this string chars, int length = 8)
{
var randomString = new StringBuilder();
var random = new Random();
for (int i = 0; i < length; i++)
randomString.Append(chars[random.Next(chars.Length)]);
return randomString.ToString();
}
用法
var random = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".Random();
要么
var random = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".Random(16);
我简单的一行代码对我有用:)
string random = string.Join("", Guid.NewGuid().ToString("n").Take(8).Select(o => o));
Response.Write(random.ToUpper());
Response.Write(random.ToLower());
以此扩展为任意长度的字符串
public static string RandomString(int length)
{
//length = length < 0 ? length * -1 : length;
var str = "";
do
{
str += Guid.NewGuid().ToString().Replace("-", "");
}
while (length > str.Length);
return str.Substring(0, length);
}
问题:为什么我要浪费时间Enumerable.Range
而不是输入"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
顶部的字符串中 ”吗?出于这个原因,我妈妈教我不要使用魔术弦。
nb 1:@dtb之类的其他人说,System.Random
如果您需要加密安全性,请不要使用...
nb 2:这个答案不是最有效或最短的,但我希望有空间将答案与问题分开。我的答案的目的更多是警告魔术字符串,而不是提供新颖的创新答案。
I
?”
[A-Z0-9]
。如果偶然地,您的随机字符串仅覆盖[A-HJ-Z0-9]
了结果而不能覆盖整个允许范围,则可能会出现问题。
I
。是否因为少了一个字符而使破解更容易?包含35个字符而不是36个字符的可破解密码的统计数据是什么。我想我宁愿冒险……还是只是证明字符范围……而不要在我的代码中包括所有这些额外的垃圾。但是,就是我。我的意思是,不是说一个屁股洞。有时,我认为程序员出于复杂性的考虑而倾向于走极端复杂的路线。
I
和之O
类的字符是很常见的,以避免人类将它们与1
和混淆0
。如果您不希望拥有人类可读的字符串,那么很好,但是如果有人可能需要键入它,那么删除那些字符实际上很聪明。
在查看了其他答案并考虑了CodeInChaos的评论之后,再加上CodeInChaos仍然有偏见(尽管更少),我认为需要最终的最终剪切和粘贴解决方案。因此,在更新答案时,我决定全力以赴。
有关此代码的最新版本,请访问Bitbucket上的新Hg存储库:https : //bitbucket.org/merarischroeder/secureswiftrandom。我建议您从以下位置复制并粘贴代码:https : //bitbucket.org/merarischroeder/secureswiftrandom/src/6c14b874f34a3f6576b0213379ecdf0ffc7496ea/Code/Alivate.SolidSwiftRandom/SolidSwiftRandom.cs?at=default&default-fileviewer= make-file-view-原始按钮可简化复制过程,并确保您具有最新版本,我认为此链接指向特定版本的代码,而不是最新版本)。
更新说明:
结束问题的解答:
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
}
}
}
对于历史记录-我对此答案的较旧解决方案使用了Random对象:
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);
}
性能:
还要签出:
这些链接是另一种方法。可以将缓冲添加到此新代码库中,但是最重要的是探索各种方法来消除偏差,并确定速度和优点/缺点。
charSet.Length
代替62
。2)Random
没有锁定的静态意味着此代码不是线程安全的。3)降低0-255 mod 62会引入可检测的偏差。4)您不能ToString
在始终返回的char数组上使用"System.Char[]"
。您需要new String(rName)
改用。
System.Random
)开始,然后小心地避免自己的代码出现任何偏差是有点愚蠢的。想到“抛光粪便”一词。
我知道这很可怕,但我无能为力:
namespace ConsoleApplication2
{
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
Random adomRng = new Random();
string rndString = string.Empty;
char c;
for (int i = 0; i < 8; i++)
{
while (!Regex.IsMatch((c=Convert.ToChar(adomRng.Next(48,128))).ToString(), "[A-Za-z0-9]"));
rndString += c;
}
Console.WriteLine(rndString + Environment.NewLine);
}
}
}
我一直在寻找一个更具体的答案,在这里我想控制随机字符串的格式,并发现这篇文章。例如:(汽车的)车牌有特定的格式(每个国家/地区),我想创建随机的车牌。
我决定为此编写自己的Random扩展方法。(这是为了重用相同的Random对象,因为在多线程方案中可能会加倍)。我创建了一个要点(https://gist.github.com/SamVanhoutte/808845ca78b9c041e928),但还将在此处复制扩展类:
void Main()
{
Random rnd = new Random();
rnd.GetString("1-###-000").Dump();
}
public static class RandomExtensions
{
public static string GetString(this Random random, string format)
{
// Based on http://stackoverflow.com/questions/1344221/how-can-i-generate-random-alphanumeric-strings-in-c
// Added logic to specify the format of the random string (# will be random string, 0 will be random numeric, other characters remain)
StringBuilder result = new StringBuilder();
for(int formatIndex = 0; formatIndex < format.Length ; formatIndex++)
{
switch(format.ToUpper()[formatIndex])
{
case '0': result.Append(getRandomNumeric(random)); break;
case '#': result.Append(getRandomCharacter(random)); break;
default : result.Append(format[formatIndex]); break;
}
}
return result.ToString();
}
private static char getRandomCharacter(Random random)
{
string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
return chars[random.Next(chars.Length)];
}
private static char getRandomNumeric(Random random)
{
string nums = "0123456789";
return nums[random.Next(nums.Length)];
}
}
现在具有一线风味。
private string RandomName()
{
return new string(
Enumerable.Repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 13)
.Select(s =>
{
var cryptoResult = new byte[4];
using (var cryptoProvider = new RNGCryptoServiceProvider())
cryptoProvider.GetBytes(cryptoResult);
return s[new Random(BitConverter.ToInt32(cryptoResult, 0)).Next(s.Length)];
})
.ToArray());
}
RNGCryptoServiceProvider
使用后应丢弃。
尝试结合两个部分:唯一性(序列,计数器或日期)和随机性
public class RandomStringGenerator
{
public static string Gen()
{
return ConvertToBase(DateTime.UtcNow.ToFileTimeUtc()) + GenRandomStrings(5); //keep length fixed at least of one part
}
private static string GenRandomStrings(int strLen)
{
var result = string.Empty;
var Gen = new RNGCryptoServiceProvider();
var data = new byte[1];
while (result.Length < strLen)
{
Gen.GetNonZeroBytes(data);
int code = data[0];
if (code > 48 && code < 57 || // 0-9
code > 65 && code < 90 || // A-Z
code > 97 && code < 122 // a-z
)
{
result += Convert.ToChar(code);
}
}
return result;
}
private static string ConvertToBase(long num, int nbase = 36)
{
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //if you wish make algorithm more secure - change order of letter here
// check if we can convert to another base
if (nbase < 2 || nbase > chars.Length)
return null;
int r;
var newNumber = string.Empty;
// in r we have the offset of the char that was converted to the new base
while (num >= nbase)
{
r = (int) (num % nbase);
newNumber = chars[r] + newNumber;
num = num / nbase;
}
// the last number to convert
newNumber = chars[(int)num] + newNumber;
return newNumber;
}
}
测试:
[Test]
public void Generator_Should_BeUnigue1()
{
//Given
var loop = Enumerable.Range(0, 1000);
//When
var str = loop.Select(x=> RandomStringGenerator.Gen());
//Then
var distinct = str.Distinct();
Assert.AreEqual(loop.Count(),distinct.Count()); // Or Assert.IsTrue(distinct.Count() < 0.95 * loop.Count())
}
<=
和>=
而不是<
和>
。3)我会在表达式周围添加不必要的括号,&&
以明确它们的优先级,但这当然只是一种样式选择。
这是Eric J解决方案的一种变体,即WinRT(Windows Store App)的加密声音:
public static string GenerateRandomString(int length)
{
var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
var result = new StringBuilder(length);
for (int i = 0; i < length; ++i)
{
result.Append(CryptographicBuffer.GenerateRandomNumber() % chars.Length);
}
return result.ToString();
}
如果性能很重要(尤其是长度较长时):
public static string GenerateRandomString(int length)
{
var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
var result = new System.Text.StringBuilder(length);
var bytes = CryptographicBuffer.GenerateRandom((uint)length * 4).ToArray();
for (int i = 0; i < bytes.Length; i += 4)
{
result.Append(BitConverter.ToUInt32(bytes, i) % chars.Length);
}
return result.ToString();
}
我知道这不是最好的方法。但是您可以尝试一下。
string str = Path.GetRandomFileName(); //This method returns a random file name of 11 characters
str = str.Replace(".","");
Console.WriteLine("Random string: " + str);
我不知道这在密码上听起来有多好,但是它比到目前为止(imo)更复杂的解决方案更具可读性和简洁性,它应该比System.Random
基于基础的解决方案更“随机” 。
return alphabet
.OrderBy(c => Guid.NewGuid())
.Take(strLength)
.Aggregate(
new StringBuilder(),
(builder, c) => builder.Append(c))
.ToString();
我不确定我是否认为此版本或下一个版本“更漂亮”,但它们给出的结果完全相同:
return new string(alphabet
.OrderBy(o => Guid.NewGuid())
.Take(strLength)
.ToArray());
当然,它并没有针对速度进行优化,因此,如果每秒生成数百万个随机字符串的任务至关重要,请尝试另一个!
注意:此解决方案不允许字母中的符号重复,并且字母的大小必须等于或大于输出字符串,这使得此方法在某些情况下不太理想,这完全取决于您的用例。
public static class StringHelper
{
private static readonly Random random = new Random();
private const int randomSymbolsDefaultCount = 8;
private const string availableChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
private static int randomSymbolsIndex = 0;
public static string GetRandomSymbols()
{
return GetRandomSymbols(randomSymbolsDefaultCount);
}
public static string GetRandomSymbols(int count)
{
var index = randomSymbolsIndex;
var result = new string(
Enumerable.Repeat(availableChars, count)
.Select(s => {
index += random.Next(s.Length);
if (index >= s.Length)
index -= s.Length;
return s[index];
})
.ToArray());
randomSymbolsIndex = index;
return result;
}
}
random.Next
直接使用直接结果有什么意义?使代码复杂,并且没有实现任何有用的功能。
这是一种无需定义字母和数字即可生成随机字母数字字符串(我用它来生成密码和测试数据)的机制,
CleanupBase64将删除字符串中的必要部分,并继续递归添加随机的字母数字字母。
public static string GenerateRandomString(int length)
{
var numArray = new byte[length];
new RNGCryptoServiceProvider().GetBytes(numArray);
return CleanUpBase64String(Convert.ToBase64String(numArray), length);
}
private static string CleanUpBase64String(string input, int maxLength)
{
input = input.Replace("-", "");
input = input.Replace("=", "");
input = input.Replace("/", "");
input = input.Replace("+", "");
input = input.Replace(" ", "");
while (input.Length < maxLength)
input = input + GenerateRandomString(maxLength);
return input.Length <= maxLength ?
input.ToUpper() : //In my case I want capital letters
input.ToUpper().Substring(0, maxLength);
}
GenerateRandomString
并拨打电话,以GetRandomString
从内部SanitiseBase64String
。您还可以声明SanitiseBase64String
和呼叫CleanUpBase64String
在GenerateRandomString
。
不是100%肯定,因为我没有在这里测试所有选项,但是在我测试过的选项中,这是最快的。用秒表计时,并显示9-10滴答,因此,如果速度比安全性更重要,请尝试以下操作:
private static Random random = new Random();
public static string Random(int length)
{
var stringChars = new char[length];
for (int i = 0; i < length; i++)
{
stringChars[i] = (char)random.Next(0x30, 0x7a);
return new string(stringChars);
}
}