[{"data":1,"prerenderedAt":170},["ShallowReactive",2],{"article-uuid-v1-v4-v5-mac-random-collision":3},{"article":4,"relatedArticles":125},{"slug":5,"category":6,"date":7,"readingMinutes":8,"tags":9,"relatedTool":15,"cn":16,"en":65,"author":113,"reviewedBy":116,"reviewedDate":118,"updatedDate":118,"sources":119,"noIndex":124},"uuid-v1-v4-v5-mac-random-collision","实现原理","2026-07-28",7,[10,11,12,13,14],"UUID","UUID v4","Collision","MAC Address","Crypto","/tools/dev/uuid",{"title":17,"description":18,"intro":19,"sections":20},"UUID v1、v4、v5 如何选择？节点标识、随机性与确定性映射","依据 RFC 9562 对比 UUID v1 的时间与节点字段、v4 的 122 位随机字段和 v5 的 Namespace + SHA-1 确定性映射，说明隐私、碰撞与数据库取舍。","UUID 的“全局唯一”是正确生成策略下的工程概率与协调属性，不是数据库约束的替代品。v1 的节点字段可能来自 MAC，也可使用随机节点标识；v4 依赖随机源质量；v5 对相同 Namespace 与 Name 产生相同结果。本文按 RFC 9562 修正这些常见绝对化说法。",[21,25,30,34,38,43,47,51,55,61],{"heading":22,"paragraphs":23},"一、问题概述：UUID 版本的输入、排序与隐私属性不同",[24],"RFC 9562 定义了多个 UUID 版本。v1 组合 60 位 Gregorian 时间戳、时钟序列与 48 位节点字段；节点字段可以来自 IEEE 802 MAC，也可以按规范生成随机节点 ID。v4 的 122 个非版本/变体位来自随机或伪随机源。v5 把 Namespace 与 Name 经 SHA-1 映射成确定性 UUID。三者解决的问题不同。",{"heading":26,"paragraphs":27,"code":29},"二、最小复现：不同 UUID 版本的生成结构对比",[28],"下面的对比展示了 UUID v1、v4 与 v5 的字符串结构特点与确定性差异：","/* 1. UUID v1: 时间戳、时钟序列与节点字段 */\n// \"6c84fb90-12c4-11ee-be56-0242ac120002\"\n// 版本 nibble 为 1；末尾节点字段可能来自 MAC，也可能是规范允许的随机节点 ID\n\n/* 2. UUID v4: 122 位完全密码学随机数 (最常用) */\n// \"f47ac10b-58cc-4372-a567-0e02b2c3d479\"\n// 版本 nibble 为 4；variant nibble 为 8、9、a 或 b\n\n/* 3. UUID v5: 基于 Namespace + Name 的 SHA-1 确定性哈希 */\n// 同一 Namespace 下传入相同 \"user_123\" 永远生成固定的 UUID v5 字符串！",{"heading":31,"paragraphs":32},"三、根因分析：节点隐私、生日界与确定性映射",[33],"1. **v1 隐私取决于节点来源**：若实现使用真实 MAC，UUID 会暴露节点厂商线索与生成时间；使用规范允许的随机节点 ID 可降低这类风险。2. **v4 碰撞是概率事件**：122 位随机空间约为 $2^{122}$，接近 $2^{61}$ 次生成时碰撞概率才进入生日界量级，但概率永远不是零，持久化层仍应保留唯一约束并处理重试。3. **v5 是确定性映射**：相同 Namespace 与 Name 必得相同 UUID；它适合稳定映射，不应当被当作不可猜测的安全令牌。",{"heading":35,"paragraphs":36},"四、推荐方案：按语义选择并保留数据库约束",[37],"1. 无需排序的随机标识：使用密码学安全实现生成 v4。2. Namespace 内的稳定名称映射：使用 v5，并固定 Name 的编码与规范化规则。3. 时间有序且希望改善索引局部性：评估 RFC 9562 v7，但仍要测试暴露生成时间、同毫秒单调策略和数据库实现。4. 所有版本都不自动成为认证 Token；敏感令牌应使用专门的高熵随机方案，数据库主键仍设唯一约束。",{"heading":39,"paragraphs":40,"code":42},"五、完整代码：基于 Web Crypto API 模拟确定性 UUID v5 生成器",[41],"下面的 TypeScript 代码示范如何利用字符串与 Namespace 生成符合 RFC 4122 规范的确定性 UUID v5 字符串。","async function generateUUIDv5(name: string, namespaceHex: string): Promise\u003Cstring> {\n  const cleanNs = namespaceHex.replace(/-/g, \"\");\n  const nsBytes = new Uint8Array(16);\n  for (let i = 0; i \u003C 16; i++) {\n    nsBytes[i] = parseInt(cleanNs.substr(i * 2, 2), 16);\n  }\n\n  const encoder = new TextEncoder();\n  const nameBytes = encoder.encode(name);\n  const data = new Uint8Array(nsBytes.length + nameBytes.length);\n  data.set(nsBytes, 0);\n  data.set(nameBytes, nsBytes.length);\n\n  const hashBuffer = await crypto.subtle.digest(\"SHA-1\", data);\n  const hashBytes = new Uint8Array(hashBuffer);\n\n  hashBytes[6] = (hashBytes[6] & 0x0f) | 0x50;\n  hashBytes[8] = (hashBytes[8] & 0x3f) | 0x80;\n\n  const hex = Array.from(hashBytes.subarray(0, 16))\n    .map((b) => b.toString(16).padStart(2, \"0\"))\n    .join(\"\");\n\n  return [\n    hex.substring(0, 8),\n    hex.substring(8, 12),\n    hex.substring(12, 16),\n    hex.substring(16, 20),\n    hex.substring(20, 32),\n  ].join(\"-\");\n}\n\ngenerateUUIDv5(\"user_1001\", \"6ba7b810-9dad-11d1-80b4-00c04fd430c8\").then(console.log);",{"heading":44,"paragraphs":45},"六、常见错误方案",[46],"认为 UUID v4 是加密密钥（UUID 只是不重复的随机标识，不可代替对称加密 Token）；假设 UUID v4 会在短时间内频繁发生碰撞；混淆 v4 随机生成与 v5 幂等调用的应用界限。",{"heading":48,"paragraphs":49},"七、边界条件：随机源质量与唯一性检测",[50],"`Math.random()` 不提供密码学不可预测性，但具体状态空间和碰撞表现由引擎实现决定，不能笼统说只剩“几千种组合”。生成 v4 应使用 `crypto.randomUUID()`、`crypto.getRandomValues()` 或成熟平台库；安全随机源仍不免除唯一索引与冲突处理。",{"heading":52,"paragraphs":53},"八、如何验证 UUID 的格式与生成策略",[54],"可用 `/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i` 验证 RFC 9562 已定义版本的常见文本形式，再分别断言版本与变体位。批量无重复测试只能发现明显实现错误，不能证明未来绝不碰撞；还应检查随机 API、v5 测试向量和数据库冲突路径。",{"heading":56,"paragraphs":57},"九、FAQ",[58,59,60],"问：UUID v4 会碰撞吗？答：使用高质量随机源时概率极低但不为零，数据库仍需唯一约束。","问：v5 使用 SHA-1 是否能当安全标识？答：不能。v5 的目的为确定性名称映射，不承诺不可猜测性或抗恶意碰撞；安全边界应使用适合的密码学构造。","问：v7 会替代自增主键吗？答：不一定。v7 提供按毫秒时间有序的布局和随机/单调字段选项，可能改善分布式生成与索引局部性，但存储宽度、页分裂、时间暴露和生态支持仍需实测。",{"heading":62,"paragraphs":63},"十、总结",[64],"v4 适合随机标识，v5 适合稳定名称映射，v7 适合需要时间排序的分布式场景；v1 是否泄露 MAC 取决于节点字段实现。无论选择哪一版，都要保留唯一约束，并把认证 Token 与业务 ID 分开设计。",{"title":66,"description":67,"intro":68,"sections":69},"Choosing UUID v1, v4, and v5: Node IDs, Randomness, and Deterministic Mapping","Use RFC 9562 to compare v1 time/node fields, v4's 122 random bits, and v5 namespace/name mapping, including privacy, collision, and database tradeoffs.","UUID uniqueness is an engineering probability and coordination property under a correct generator, not a replacement for database constraints. A v1 node field may use a MAC or a random node ID, v4 depends on random-source quality, and v5 repeats for an equal namespace/name pair. This guide applies RFC 9562 without those common absolutes.",[70,74,79,83,87,91,95,99,103,109],{"heading":71,"paragraphs":72},"1. Problem: UUID versions have different inputs, ordering, and privacy properties",[73],"RFC 9562 defines v1 using a 60-bit Gregorian timestamp, clock sequence, and 48-bit node field. That node can derive from an IEEE 802 MAC address or be randomly generated as the specification permits. v4 fills 122 non-version/variant bits from a random or pseudorandom source. v5 deterministically maps a namespace and name through SHA-1.",{"heading":75,"paragraphs":76,"code":78},"2. Minimal reproduction: UUID version structural comparison",[77],"This comparison illustrates string layout and determinism differences across UUID v1, v4, and v5:","/* 1. UUID v1: timestamp, clock sequence, and node field */\n// \"6c84fb90-12c4-11ee-be56-0242ac120002\"\n// Version nibble is 1; the node may come from a MAC or a compliant random node ID\n\n/* 2. UUID v4: 122-bit Cryptographic Pseudo-Randomness (Most common) */\n// \"f47ac10b-58cc-4372-a567-0e02b2c3d479\"\n// Version nibble is 4; variant nibble is 8, 9, a, or b\n\n/* 3. UUID v5: Namespace + Name SHA-1 Deterministic Hash */\n// Passing \"user_123\" under the same Namespace always yields an identical UUID v5!",{"heading":80,"paragraphs":81},"3. Root cause: node privacy, the birthday bound, and deterministic mapping",[82],"1. **v1 privacy depends on the node source**: a real MAC can expose vendor clues and generation time, while a compliant random node ID reduces that risk. 2. **v4 collisions are probabilistic**: the 122-bit space reaches birthday-bound scale near $2^{61}$ generations, but probability is never zero; keep a unique constraint and retry path. 3. **v5 is deterministic**: equal namespace/name inputs yield equal output, making it useful for stable mapping but unsuitable as an unguessable token.",{"heading":84,"paragraphs":85},"4. Recommendation: choose by semantics and retain database constraints",[86],"1. Random identifiers without ordering: generate v4 from a cryptographically secure implementation. 2. Stable names within a namespace: use v5 and fix the name's encoding and normalization. 3. Time ordering and index locality: evaluate RFC 9562 v7, including timestamp exposure, same-millisecond monotonicity, and database behavior. 4. No UUID version automatically becomes an authentication token; retain unique constraints for identifiers.",{"heading":88,"paragraphs":89,"code":42},"5. Complete code: Web Crypto API deterministic UUID v5 generator",[90],"This TypeScript snippet demonstrates generating RFC 4122 compliant deterministic UUID v5 strings from namespaces and names using Web Crypto APIs.",{"heading":92,"paragraphs":93},"6. Incorrect approaches",[94],"Treating UUID v4 as an encryption secret (UUIDs are unique identifiers, not symmetric tokens). Assuming UUID v4 will collide in small-scale systems. Confusing v4 random generation with v5 idempotent lookup.",{"heading":96,"paragraphs":97},"7. Boundaries: random-source quality and uniqueness handling",[98],"`Math.random()` is not cryptographically unpredictable, but its exact state space and collision behavior are implementation-dependent; it does not universally degrade to only a few thousand values. Generate v4 through `crypto.randomUUID()`, `crypto.getRandomValues()`, or a mature platform library, and still enforce uniqueness in storage.",{"heading":100,"paragraphs":101},"8. Verification",[102],"Validate the common RFC 9562 text form with `/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i`, then assert version and variant bits separately. A large no-duplicate sample catches obvious defects but cannot prove future uniqueness; inspect the random API, v5 test vectors, and database conflict path too.",{"heading":104,"paragraphs":105},"9. FAQ",[106,107,108],"Can UUID v4 collide? The probability is extremely low with a sound random source but not zero, so a database unique constraint still matters.","Is v5 safe because it uses SHA-1? v5 is for deterministic naming, not unguessability or adversarial collision resistance; use an appropriate security construction at trust boundaries.","Does v7 replace auto-increment keys? Not universally. Its millisecond-ordered layout and random/monotonic fields can improve distributed generation and index locality, but storage width, page behavior, timestamp exposure, and ecosystem support require measurement.",{"heading":110,"paragraphs":111},"10. Summary",[112],"Use v4 for random identifiers, v5 for stable name mapping, and consider v7 for time-ordered distributed IDs. Whether v1 exposes a MAC depends on its node-field implementation. Every choice still needs a unique constraint, and authentication tokens should be designed separately from business IDs.",{"name":114,"url":115},"Tiny's Tool Editorial Team","https://tinystool.org/about",{"name":117,"url":115},"Tiny's Tool Technical Review","2026-08-08",[120],{"title":121,"url":122,"publisher":123},"RFC 9562 — Universally Unique IDentifiers","https://www.rfc-editor.org/rfc/rfc9562","RFC Editor",false,[126,140,155],{"slug":127,"noIndex":128,"category":129,"date":7,"updatedDate":118,"reviewedDate":118,"readingMinutes":8,"tags":130,"relatedTool":15,"cn":134,"en":137},"uuid-crypto-randomuuid-secure-context",true,"踩坑避坑",[10,131,132,133],"crypto.randomUUID","Secure Context","HTTPS",{"title":135,"description":136},"在 HTTPS 环境下使用 `crypto.randomUUID()` 遭遇非安全上下文 (Non-secure context) 报错","分析 W3C Secure Context 规范对 `window.crypto.randomUUID()` 的安全限制，讲解在 HTTP 开发环境或旧版浏览器下的密码学安全 Polyfill 降级方案。",{"title":138,"description":139},"Fixing crypto.randomUUID() Non-Secure Context Errors in HTTP Environments","Analyze W3C Secure Context restrictions on `window.crypto.randomUUID()`, offering cryptographically secure polyfill fallbacks for HTTP environments.",{"slug":141,"noIndex":128,"category":142,"date":7,"updatedDate":118,"reviewedDate":118,"readingMinutes":143,"tags":144,"relatedTool":15,"cn":149,"en":152},"uuid-mysql-b-tree-clustered-index-performance","最佳实践",6,[10,145,146,147,148],"MySQL","B+Tree","Clustered Index","Performance",{"title":150,"description":151},"为什么不推荐把 UUID 作为 MySQL 数据库的聚簇索引主键？深入探讨 B+Tree 页分裂","剖析随机 UUID v4 作为 InnoDB 聚簇索引引发的 B+Tree 50/50 页分裂、Buffer Pool 缓存碎片与磁盘随机 I/O 问题，对比 BINARY(16) 与 UUID v7 时序优化。",{"title":153,"description":154},"Why Random UUID Primary Keys Degrade MySQL B+Tree Performance: Page Splits and Index Fragmentation","Examine random UUID v4 performance degradation on InnoDB clustered indexes, detailing 50/50 page splits, Buffer Pool churn, BINARY(16), and UUID v7.",{"slug":156,"noIndex":128,"category":6,"date":7,"updatedDate":118,"reviewedDate":118,"readingMinutes":157,"tags":158,"relatedTool":163,"cn":164,"en":167},"base64-padding-equal-url-safe-variants",5,[159,160,161,162],"Base64","Padding","URL-Safe","Algorithm","/tools/dev/base64",{"title":165,"description":166},"Base64 编解码算法原理：3字节转4字节、`=` 填充符根因与 URL-Safe (RFC 4648) 变种","深度拆解 Base64 3 字节 (24bit) 转 4 字符 (4 * 6bit) 算法推导，解释末尾 `=` 与 `==` 填充符的生成条件，以及 URL-Safe (`-` 与 `_`) 替换规则与无 padding 还原。",{"title":168,"description":169},"Base64 Algorithm Explained: 3-Byte to 4-Char Math, `=` Padding Rules, and URL-Safe (RFC 4648) Variants","Deconstruct Base64 24-bit to 4x6-bit group conversions, explaining `=` / `==` padding conditions and RFC 4648 URL-Safe (`-` / `_`) replacement rules.",1786725508531]