Skip to content

Instantly share code, notes, and snippets.

@swkwon
Last active January 1, 2016 06:58
Show Gist options
  • Save swkwon/8108226 to your computer and use it in GitHub Desktop.
Save swkwon/8108226 to your computer and use it in GitHub Desktop.
generate random unique key
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
namespace ConsoleApplication32
{
class Program
{
static HashSet<string> set = new HashSet<string>();
static void Main(string[] args)
{
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
for (int i = 0; i < 10000000; i++)
{
if (false == set.Add(GetUniqueKey()))
{
System.Diagnostics.Debugger.Break();
}
}
sw.Stop();
Console.WriteLine(sw.Elapsed);
System.Diagnostics.Debugger.Break();
}
private static string GetUniqueKey()
{
RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
byte[] data = new byte[uniqueKeySize];
crypto.GetNonZeroBytes(data);
StringBuilder result = new StringBuilder(uniqueKeySize);
foreach (byte b in data)
{ result.Append(chars[b % (chars.Length - 1)]); }
return result.ToString();
}
private const int uniqueKeySize = 16;
private static readonly char[] chars = new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment