Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate 8 byte GUID value in c#? [duplicate]

Tags:

c#

.net

asp.net

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# ?

like image 453
Linney Avatar asked Jul 19 '11 15:07

Linney


3 Answers

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();
        }   
    }
}
like image 110
Peter Bromberg Avatar answered Oct 21 '22 02:10

Peter Bromberg


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.

like image 3
LiborV Avatar answered Oct 21 '22 02:10

LiborV


Generate a random long, and then convert it to a hex string.

Alternatively, just sequentially allocate from unsigned long.

like image 2
jason Avatar answered Oct 21 '22 04:10

jason