Comment en Générer UUIDs
Créer universally unique identifiers (UUIDs/GUIDs) en various versions.
问题
You besoin un unique identifier pour un record, session, ou event ce est guaranteed unique sans central coordination.
Prérequis
- Understanding of unique identifiers
- Knowledge of UUID versions
Étapes
-
1. Choose the UUID version
Version 4 (random) is the most common — it uses random bits and has an extremely low collision probability. Version 7 is time-ordered, useful for databases. Version 5 is deterministic (name-based with SHA-1). Version 1 is time-based with a node ID.
entréeversion: 4 (random)输出version selected -
2. Generate the UUID
Generate a UUID of the chosen version. A v4 UUID has the format xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where y is 8, 9, a, or b. The generation uses a cryptographically secure RNG for v4. The output is a 36-character string with hyphens.
entréegenerate v4输出550e8400-e29b-41d4-a716-446655440000 -
3. Use and store the UUID
Use the UUID as a unique key for database records, session IDs, or event identifiers. UUIDs are 128 bits, providing sufficient uniqueness for virtually all applications. Store as a UUID type in databases (more efficient than string) or as a 36-character string.
entréeUUID for database record输出unique key assigned
Résultat attendu
Un valide UUID en le specified version, avec le correct formater et version bits.
Erreurs courantes
- Using Math.random for UUID generation
- Math.random is not cryptographically secure. Use crypto.randomUUID() or a CSPRNG for v4 UUIDs to ensure unpredictability.
- UUID stored as VARCHAR(36) when a native type exists
- Many databases have a native UUID type that is more efficient (16 bytes vs 37 characters) and indexed faster. Use the native type when available.
Dépannage指引
- If UUIDs collide (extremely unlikely for v4), verify the RNG is working correctly.
- For time-ordered UUIDs (v7), ensure the clock is monotonic to avoid ordering issues.
Limites de sécurité
- UUID v4 values are unpredictable and suitable for session tokens. However, they are not cryptographically strong — use a dedicated token generator for security-critical purposes.
- All generation is local.