Possible Duplicate:
How to generate 8 bytes unique id from GUID?
I need a unique key to identify a user at universal and key's length is just 8 byte, How can I do this in c# ?
the following code will generate cryptographically unique 8 character strings:
using System;
using System.Security.Cryptography;
using System.Text;
namespace JustForFun
{
public class UniqueId
{
public static string GetUniqueKey()
{
int maxSize = 8;
char[] chars = new char[62];
string a;
a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
chars = a.ToCharArray();
int size = maxSize;
byte[] data = new byte[1];
RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
crypto.GetNonZeroBytes(data);
size = maxSize;
data = new byte[size];
crypto.GetNonZeroBytes(data);
StringBuilder result = new StringBuilder(size);
foreach (byte b in data)
{ result.Append(chars[b % (chars.Length - 1)]); }
return result.ToString();
}
}
}
8 bytes is a size of a long integer in .net. You may start with a key of zero, increasing it by one for each user as they come. That would generate unique keys for more users than there are people on the Earth. If this does not solve your problem, please tell us more about your constraints.
Generate a random long, and then convert it to a hex string.
Alternatively, just sequentially allocate from unsigned long
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With