Utilities
UUID and random tokens
UUID v4, hex, base64, and PIN — one at a time or by the hundreds.
122 bits: 128 random bits minus 6 bits for version and variant.
What is UUID v4
UUID (universally unique identifier) is a 128-bit identifier, which is written with thirty-six characters: eight groups separated by a hyphen, for example
3f2a9c1e-7b4d-4f6a-9e21-8c5d0b7a4e13. The fourth version of the standard means that almost all bits in it are random.
Out of 128 bits, six are reserved: four bits go to the version number (in the third group it is always 4), two — to the RFC 4122 variant (the fourth group begins with 8, 9, a or b). That leaves 122 random bits—that's about 5.3 × 10³⁶ options.
The main property of a UUID is that it can be created anywhere without coordination with a server. Two independent applications almost never generate the same identifier, so it is convenient to generate a UUID on the client even before saving it to the database.
Where are UUIDs and tokens used
- primary keys of tables, when auto-increment gets in the way or gives the database size;
- request identifiers for logs and tracing between services;
- idempotency keys for repeated API requests;
- names of temporary files, folders, and sessions;
- hex and base64 tokens for password reset and invitation links;
- PIN codes for local testing — for example, in a demo stand.
How is a UUID different from a random string
A random string is just a set of characters without obligations. UUID is a standard: fixed length, canonical representation, a version and variant number inside, ready support in libraries of any language. If the value needs to be read by standard parsers and stored in a column uuid, take the UUID.
If you specifically need a token — for a link, API key, or file name — the format is more flexible. Hex is convenient because it consists only of digits and Latin letters a–f and does not require escaping. Base64 is denser: six bits per character instead of four, so a string of the same strength is a quarter shorter.
How much entropy is in the token
The entropy of the token is calculated as length × log₂(alphabet). For a PIN code, the alphabet is ten digits, so even 12 characters give only about 40 bits: such a code protects against random selection, but not against targeted brute force.
| Type | Calculation | Entropy |
|---|---|---|
| UUID v4 | 122 random bits | 122 bits |
| HEX, 16 bytes | 16 × 8 | 128 bits |
| HEX, 32 bytes | 32 × 8 | 256 bits |
| Base64, 32 characters | 32 × 6 | 192 bits |
| PIN, 6 digits | 6 × log₂(10) | ≈ 20 bits |
| Custom string, 24 of 32 characters | 24 × 5 | 120 bits |
How to handle tokens
- for sessions and APIs — no less than 128 bits of entropy;
- for disposable links — a short lifespan is more important than length;
- store the hash of the token on the server, not the token itself;
- do not write tokens in logs and analytics;
- PIN — for local verification only, not for data access.