c# - Cryptograhically random unique strings -


in this answer, below code posted creating unique random alphanumeric strings. clarify me how ensured unique in code , extent these unique? if rerun method on different occasions still unique strings?

or did misunderstand reply , these not generating unique keys @ all, random?

i asked in comment answer user seems inactive.

    public static string getuniquekey()     {         int maxsize = 8;         char[] chars = new char[62];         string 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();     }    

there nothing in code guarantees result unique. unique value either have keep previous values can check duplicates, or use lot longer codes duplicates practically impossible (e.g. guid). code contains less 48 bits of information, lot less 128 bits of guid.

the string random, , although crypto strength random generator used, ruined how code generated random data. there issues in code:

  • a char array created, thrown away , replaced another.
  • a 1 byte array of random data created no apparent reason @ all, it's not used anything.
  • the getnonzerobytes method used instead of getbytes method, adds skew distribution of characters code nothing handle lack of 0 values.
  • the modulo (%) operator used reduce random number down number of characters used, random number can't evenly divided number of characters, adds skew distribution of characters.
  • chars.length - 1 used instead of chars.length when number reduced, means 61 of predefined 62 characters can occur in string.

although issues minor, important when dealing crypo strength randomness.

a version of code produce string without issues, , give code enough information considered practically unique:

public static string getuniquekey() {   int size = 16;   byte[] data = new byte[size];   rngcryptoserviceprovider crypto = new rngcryptoserviceprovider();   crypto.getbytes(data);   return bitconverter.tostring(data).replace("-", string.empty); } 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -