Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shorten UUID V4 without making it non-unique/guessable

I have to generate unique URL part which will be "unguessable" and "resistant" to brute force attack. It also has to be as short as possible :) and all generated values has to be of same length. I was thinking about using UUID V4 which can be represented by 32 (without hyphens) hex chars de305d5475b4431badb2eb6b9e546014 but it's a bit too long. So my question is how to generate something unqiue, that can be represented with url charcters with same length for each generated value and shorter than 32 chars. (In node.js or pgpsql)

like image 558
user606521 Avatar asked Jul 30 '15 13:07

user606521


People also ask

Can a UUID be shortened?

You can use the short-uuid package to generate v4 UUIDs and shorten them for your application's use cases.

Are UUIDs globally unique?

They're globally unique, so the chances of encountering a duplicate ID even in external data are very, very small. They can be generated without the need to check against a central node, so in a distributed system, each node can generate UUIDs autonomously without fear of duplication or consistency issues.

Is NanoID better than UUID?

Fact Check: NanoID is 60% faster and has over 11,769K weekly NPM downloads than UUID. In this article, you will get to know the difference between NanoID vs UUID.

Should I use UUID v1 or v4?

If you don't know what to go with, go with v4. It's good enough, and the chances of collision are practically none. If you actually want your UUID to give some indication of the date and computer in which it was created, then UUID v1 may be for you (although it is).


2 Answers

v4() will generate a large number which is translated into a hexadecimal string. In Node.js you can use Buffer to convert the string into a smaller base64 encoding:

import { v4 } from 'uuid';

function getRandomName() {

    let hexString = v4();
    console.log("hex:   ", hexString);
    
    // remove decoration
    hexString = hexString.replace(/-/g, "");
    
    let base64String = Buffer.from(hexString, 'hex').toString('base64')
    console.log("base64:", base64String);
    
    return base64String;
}

Which produces:

hex:    6fa1ca99-a92b-4d2a-aac2-7c7977119ebc
base64: b6HKmakr

hex:    bd23c8fd-0f62-49f4-9e51-8b5c97601a16
base64: vSPI/Q9i
like image 95
Kees C. Bakker Avatar answered Sep 18 '22 04:09

Kees C. Bakker


UUID v4 itself does not actually guarantee uniqueness. It's just very, very unlikely that two randomly generated UUIDs will clash. That's why they need to be so long - that reduces the clashing chance. So you can make it shorter, but the shorter you make it, the more likely that it won't actually be unique. UUID v4 is 128 bit long because that is commonly considered "unique enough".

like image 22
ralh Avatar answered Sep 19 '22 04:09

ralh