跳到主要内容
uencoder

如何Generate UUIDs

Create universally 唯一 identifiers (UUIDs/GUIDs) 在 various versions.

问题

你 need 唯一 identifier 为记录, 会话, 或事件该 是 guaranteed 唯一无 中心 coordination.

前置条件

  • Understanding 的唯一 identifiers
  • Knowledge 的 UUID versions

步骤

  1. 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.

    输入
    version: 4 (random)
    输出
    version selected
  2. 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.

    输入
    generate v4
    输出
    550e8400-e29b-41d4-a716-446655440000
  3. 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.

    输入
    UUID for database record
    输出
    unique key assigned

预期结果

有效 UUID 在 specified version, 具有正确格式化和 version bits.

常见错误

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.

排障指引

  • 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.

安全限制

  • 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.

相关工具

参考链接