Generating 8-character only UUIDs

后端 未结 8 1510
[愿得一人]
[愿得一人] 2020-11-27 03:22

UUID libraries generate 32-character UUIDs.

I want to generate 8-character only UUIDs, is it possible?

8条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 04:02

    First: Even the unique IDs generated by java UUID.randomUUID or .net GUID are not 100% unique. Especialy UUID.randomUUID is "only" a 128 bit (secure) random value. So if you reduce it to 64 bit, 32 bit, 16 bit (or even 1 bit) then it becomes simply less unique.

    So it is at least a risk based decisions, how long your uuid must be.

    Second: I assume that when you talk about "only 8 characters" you mean a String of 8 normal printable characters.

    If you want a unique string with length 8 printable characters you could use a base64 encoding. This means 6bit per char, so you get 48bit in total (possible not very unique - but maybe it is ok for you application)

    So the way is simple: create a 6 byte random array

     SecureRandom rand;
     // ...
     byte[] randomBytes = new byte[16];
     rand.nextBytes(randomBytes);
    

    And then transform it to a Base64 String, for example by org.apache.commons.codec.binary.Base64

    BTW: it depends on your application if there is a better way to create "uuid" then by random. (If you create a the UUIDs only once per second, then it is a good idea to add a time stamp) (By the way: if you combine (xor) two random values, the result is always at least as random as the most random of the both).

提交回复
热议问题