Unique random string generation

2019-01-03 11:49发布

I'd like to generate random unique strings like the ones being generated by MSDN library:

http://msdn.microsoft.com/en-us/library/t9zk6eay.aspx, for example. A string like 't9zk6eay' should be generated.

标签: c# random
13条回答
女痞
2楼-- · 2019-01-03 12:41

This has been asked for various languages. Here's one question about passwords which should be applicable here as well.

If you want to use the strings for URL shortening, you'll also need a Dictionary<> or database check to see whether a generated ID has already been used.

查看更多
【Aperson】
3楼-- · 2019-01-03 12:43

This works perfect for me

    private string GeneratePasswordResetToken()
    {
        string token = Guid.NewGuid().ToString();
        var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(token);
        return Convert.ToBase64String(plainTextBytes);
    }
查看更多
三岁会撩人
4楼-- · 2019-01-03 12:45

Try combination between Guid and Time.Ticks

 var randomNumber = Convert.ToBase64String(Guid.NewGuid().ToByteArray()) + DateTime.Now.Ticks;
     randomNumber = System.Text.RegularExpressions.Regex.Replace(randomNumber, "[^0-9a-zA-Z]+", "");
查看更多
疯言疯语
5楼-- · 2019-01-03 12:46

If you want an alphanumeric strings with lowercase and uppercase characters ([a-zA-Z0-9]), you can use Convert.ToBase64String() for a fast and simple solution.

As for uniqueness, check out the birthday problem to calculate how likely a collission is given (A) the length of the strings generated and (B) the number of strings generated.

Random random = new Random();

int outputLength = 10;
int byteLength = (int)Math.Ceiling(3f / 4f * outputLength); // Base64 uses 4 characters for every 3 bytes of data; so in random bytes we need only 3/4 of the desired length
byte[] randomBytes = new byte[byteLength];
string output;
do
{
    random.NextBytes(randomBytes); // Fill bytes with random data
    output = Convert.ToBase64String(randomBytes); // Convert to base64
    output = output.Substring(0, outputLength); // Truncate any superfluous characters and/or padding
} while (output.Contains('/') || output.Contains('+')); // Repeat if we contain non-alphanumeric characters (~25% chance if length=10; ~50% chance if length=20; ~35% chance if length=32)
查看更多
甜甜的少女心
6楼-- · 2019-01-03 12:47

Using Guid would be a pretty good way, but to get something looking like your example, you probably want to convert it to a Base64 string:

    Guid g = Guid.NewGuid();
    string GuidString = Convert.ToBase64String(g.ToByteArray());
    GuidString = GuidString.Replace("=","");
    GuidString = GuidString.Replace("+","");

I get rid of "=" and "+" to get a little closer to your example, otherwise you get "==" at the end of your string and a "+" in the middle. Here's an example output string:

"OZVV5TpP4U6wJthaCORZEQ"

查看更多
ゆ 、 Hurt°
7楼-- · 2019-01-03 12:47

Update 2016/1/23

If you find this answer useful, you may be interested in a simple (~500 SLOC) password generation library I published:

Install-Package MlkPwgen

Then you can generate random strings just like in the answer below:

var str = PasswordGenerator.Generate(length: 10, allowed: Sets.Alphanumerics);

One advantage of the library is that the code is better factored out so you can use secure randomness for more than generating strings. Check out the project site for more details.

Original Answer

Since no one has provided secure code yet, I post the following in case anyone finds it useful.

string RandomString(int length, string allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") {
    if (length < 0) throw new ArgumentOutOfRangeException("length", "length cannot be less than zero.");
    if (string.IsNullOrEmpty(allowedChars)) throw new ArgumentException("allowedChars may not be empty.");

    const int byteSize = 0x100;
    var allowedCharSet = new HashSet<char>(allowedChars).ToArray();
    if (byteSize < allowedCharSet.Length) throw new ArgumentException(String.Format("allowedChars may contain no more than {0} characters.", byteSize));

    // Guid.NewGuid and System.Random are not particularly random. By using a
    // cryptographically-secure random number generator, the caller is always
    // protected, regardless of use.
    using (var rng = System.Security.Cryptography.RandomNumberGenerator.Create()) {
        var result = new StringBuilder();
        var buf = new byte[128];
        while (result.Length < length) {
            rng.GetBytes(buf);
            for (var i = 0; i < buf.Length && result.Length < length; ++i) {
                // Divide the byte into allowedCharSet-sized groups. If the
                // random value falls into the last group and the last group is
                // too small to choose from the entire allowedCharSet, ignore
                // the value in order to avoid biasing the result.
                var outOfRangeStart = byteSize - (byteSize % allowedCharSet.Length);
                if (outOfRangeStart <= buf[i]) continue;
                result.Append(allowedCharSet[buf[i] % allowedCharSet.Length]);
            }
        }
        return result.ToString();
    }
}

Thanks to Ahmad for pointing out how to get the code working on .NET Core.

查看更多
登录 后发表回答