找回密码
 立即注册→加入我们

QQ登录

只需一步,快速开始

搜索
热搜: 下载 VB C 实现 编写
查看: 5261|回复: 3

【C】根据UUID的标准(部分)造一个简单易用的标准UUID生成器

[复制链接]

1109

主题

1649

回帖

7万

积分

用户组: 管理员

一只技术宅

UID
1
精华
244
威望
743 点
宅币
24180 个
贡献
46222 次
宅之契约
0 份
在线时间
2294 小时
注册时间
2014-1-26
发表于 2019-7-2 15:19:59 | 显示全部楼层 |阅读模式

欢迎访问技术宅的结界,请注册或者登录吧。

您需要 登录 才可以下载或查看,没有账号?立即注册→加入我们

×
UUID(Universally unique identifier,宇宙唯一标识符,也叫GUID,Globally unique identifier,地球唯一标识符,虽说后者这个名字是微软起的)是用来给东西起名的(虽说也有其它作用)。典型例子,Windows的COM架构的每个类都有个自己的字符串名字和UUID名字,用来确定这个类是谁。一个典型的UUID看起来是这个样子的:

    123e4567-e89b-12d3-a456-426655440000
    xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx

它其实是一个128bit的数值,用十六进制来表示(字节顺序为LE),并且中间插入了一些横杠以便于阅读和比对。那么它是如何保证它的“宇宙惟一性”呢?其实,一个UUID的数值虽然看起来随机,但它是有结构的,而且有不同的版本。

版本1
从概念上来说,UUID的原始版本使用计算机MAC地址和1970年以来以百纳秒为单位的时间戳来表示空间中的单个点(计算机)和时间(间隔的数量)。理论上碰撞几率为零。

然而这个计划被喷了,因为它“不透明”。它暴露了生成UUID的机器和它所执行的时间。虽说只要MAC地址不重复,它就能确保惟一性,但MAC地址可以被修改,而且现代计算机的执行速度足以在相同的时间戳内连续生成多个相同的UUID。

攻击者可以通过利用这个漏洞,来预测之后可能会生成的UUID,然后占用它。

版本2
近似于版本1,但前4个字节被替换成了POSIX的用户UID或GID,而剩余部分的时间戳则被替换成了时钟序列(通常是clock()的返回值)。取样源现在是“本地域”。

然而,版本2并未在UUID规范中被明确定义,因此并未由所有UUID生成器实现。

版本3
通过一个给定的名称、未指定命名空间的名称、域名、URL等玩意儿的MD5值来派生出UUID。版本3 UUID的格式为xxxxxxxx-xxxx-3xxx-yxxx-xxxxxxxxxxxx,其中x是任意十六进制数位,y则是8、9、a、b的其中一个。根据规范,版本3存在向后兼容性,且如果向后兼容性并不重要的话,更偏向于使用SHA-1(即版本5)。

要生成一个版本3的UUID,先取得其命名空间的UUID,转换为十六进制表示的字符串,然后在尾部追加字符串的名称,再把一整个字符串用MD5进行哈希处理,得到一个128位的MD5值。再修改其中的4个bit来提示其版本号(0011表示版本3),以及把y的位置的高2bit设为10b来使y的值为8、9、a、b的其中一个。

命名空间
上文提到的所谓命名空间,它自身也是UUID。任何UUID都可以作为版本3或5的UUID的命名空间。

版本4
RFC 4122(“Leach-Salz”)定义,它的特点是主要取决于(伪)随机数。除了4位版本号和2位保留位,其余122位都被用伪随机数作为数据源来填充。它的格式是xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx,类似于版本3。其中的y是8、9、a、b中的一个。

版本5
和版本3类似,除了版本号是5,以及哈希算法是SHA-1而非MD5。注意SHA-1的长度是160位,解决长度问题的办法是将其截断为128位。


我随手写了一个版本4的C语言代码用于生成UUID。其中我使用了各种方式尽可能获得更多熵来生成更加随机的伪随机数。不过,随机数序列依然是可预测的。我只是用了一个包含熵比较多的随机数种子而已。
  1. #include<stdint.h>
  2. #include<stdlib.h>
  3. #include<time.h>

  4. void gen_uuid(void *puuid)
  5. {
  6.         uint32_t *u = puuid;
  7.         time_t t = time(NULL); // 时间戳
  8.         clock_t c = clock(); // 时钟值
  9.         uint64_t rs64 = t ^ (size_t)u ^ c ^ u[0] ^ u[1] ^ u[2] ^ u[3] ^ rand(); // 随机数种子(作为参数的那个指针的值也拿来用)
  10.        
  11.         // 折叠随机数种子为32位
  12.         srand((rs64 >> 32) ^ rs64);

  13.         // 产生16个8bit随机数。由于不同C库的rand()取值范围不同,这里只截取其低8位确保安全
  14.         u[0] = ((uint32_t)rand() & 0xFFU) | (((uint32_t)rand() & 0xFFU) << 8) | (((uint32_t)rand() & 0xFFU) << 16) | (((uint32_t)rand() & 0xFFU) << 24);
  15.         u[2] = ((uint32_t)rand() & 0xFFU) | (((uint32_t)rand() & 0xFFU) << 8) | (((uint32_t)rand() & 0xFFU) << 16) | (((uint32_t)rand() & 0xFFU) << 24);
  16.         u[1] = ((uint32_t)rand() & 0xFFU) | (((uint32_t)rand() & 0xFFU) << 8) | (((uint32_t)rand() & 0xFFU) << 16) | (((uint32_t)rand() & 0xFFU) << 24);
  17.         u[3] = ((uint32_t)rand() & 0xFFU) | (((uint32_t)rand() & 0xFFU) << 8) | (((uint32_t)rand() & 0xFFU) << 16) | (((uint32_t)rand() & 0xFFU) << 24);

  18.         // 插入4位版本号、2位的保留位
  19.         u[1] &= 0x0FFF3FFF;
  20.         u[1] |= 0x40008000;
  21. }
复制代码
参考资料:

https://en.wikipedia.org/wiki/Universally_unique_identifier
https://stackoverflow.com/questi ... uuid-version-to-use
https://ipfs.io/ipfs/QmXoypizjW3 ... que_identifier.html
回复

使用道具 举报

65

主题

113

回帖

1万

积分

用户组: 超级版主

OS与VM研究学者

UID
1043
精华
35
威望
789 点
宅币
8228 个
贡献
1094 次
宅之契约
0 份
在线时间
2047 小时
注册时间
2015-8-15
发表于 2019-7-4 11:55:51 | 显示全部楼层
发一个Windows内核里的UUID创建函数,代码来自WRK v1.2(对应32位Windows Server 2003,64位Windows XP)。
  1. NTSTATUS
  2. ExUuidCreate(
  3.     OUT UUID *Uuid
  4.     )

  5. /*++

  6. Routine Description:

  7.     This routine creates a DCE UUID and returns it in the caller's
  8.     buffer.

  9. Arguments:

  10.     Uuid - will receive the UUID.

  11. Return Value:

  12.     STATUS_SUCCESS is returned if the service is successfully executed.

  13.     STATUS_RETRY is returned if we're unable to reserve a range of
  14.         UUIDs.  This will occur if system clock hasn't advanced
  15.         and the allocator is out of cached values.

  16. --*/

  17. {
  18.     NTSTATUS Status = STATUS_SUCCESS;

  19.     UUID_GENERATE  *UuidGen = (UUID_GENERATE *) Uuid;
  20.     ULONGLONG       Time;
  21.     LONG            Delta;

  22.     PAGED_CODE();

  23.     //
  24.     // Get a value from the cache.  If the cache is empty, we'll fill
  25.     // it and retry.  The first time cache will be empty.
  26.     //

  27.     for(;;) {

  28.         // Get the highest value in the cache (though it may not
  29.         // be available).
  30.         Time = ExpUuidCachedValues.Time;

  31.         // Copy the static info into the UUID.  We can't do this later
  32.         // because the clock sequence could be updated by another thread.

  33.         *(PULONG)&UuidGen->ClockSeqHiAndReserved =
  34.             *(PULONG)&ExpUuidCachedValues.ClockSeqHiAndReserved;
  35.         *(PULONG)&UuidGen->NodeId[2] =
  36.             *(PULONG)&ExpUuidCachedValues.NodeId[2];

  37.         // See what we need to subtract from Time to get a valid GUID.
  38.         Delta = InterlockedDecrement(&ExpUuidCachedValues.AllocatedCount);

  39.         if (Time != ExpUuidCachedValues.Time) {

  40.             // If our captured time doesn't match the cache then another
  41.             // thread already took the lock and updated the cache. We'll
  42.             // just loop and try again.
  43.             continue;
  44.             }

  45.         // If the cache hadn't already run dry, we can break out of this retry
  46.         // loop.
  47.         if (Delta >= 0) {
  48.             break;
  49.             }

  50.         //
  51.         // Allocate a new block of Uuids.
  52.         //

  53.         // Take the cache lock
  54.         KeEnterCriticalRegion();
  55.         ExAcquireFastMutexUnsafe(&ExpUuidLock);

  56.         // If the cache has already been updated, try again.
  57.         if (Time != ExpUuidCachedValues.Time) {
  58.             // Release the lock
  59.             ExReleaseFastMutexUnsafe(&ExpUuidLock);
  60.             KeLeaveCriticalRegion();
  61.             continue;
  62.             }

  63.         // Update the cache.
  64.         Status = ExpUuidGetValues( &ExpUuidCachedValues );

  65.         if (Status != STATUS_SUCCESS) {
  66.             // Release the lock
  67.             ExReleaseFastMutexUnsafe(&ExpUuidLock);
  68.             KeLeaveCriticalRegion();
  69.             return(Status);
  70.             }

  71.         // The sequence number may have been dirtied, see if it needs
  72.         // to be saved.  If there's an error, we'll ignore it and
  73.         // retry on a future call.

  74.         ExpUuidSaveSequenceNumberIf();

  75.         // Release the lock
  76.         ExReleaseFastMutexUnsafe(&ExpUuidLock);
  77.         KeLeaveCriticalRegion();

  78.         // Loop
  79.         }

  80.     // Adjust the time to that of the next available UUID.
  81.     Time -= Delta;

  82.     // Finish filling in the UUID.

  83.     UuidGen->TimeLow = (ULONG) Time;
  84.     UuidGen->TimeMid = (USHORT) (Time >> 32);
  85.     UuidGen->TimeHiAndVersion = (USHORT)
  86.         (( (USHORT)(Time >> (32+16))
  87.         & UUID_TIME_HIGH_MASK) | UUID_VERSION);

  88.     ASSERT(Status == STATUS_SUCCESS);

  89.     if (ExpUuidCacheValid == CACHE_LOCAL_ONLY) {
  90.         Status = RPC_NT_UUID_LOCAL_ONLY;
  91.         }

  92.     return(Status);
  93. }
复制代码
回复 赞! 1 靠! 0

使用道具 举报

1

主题

60

回帖

201

积分

用户组: 中·技术宅

UID
4683
精华
0
威望
0 点
宅币
140 个
贡献
0 次
宅之契约
0 份
在线时间
31 小时
注册时间
2019-2-11
发表于 2019-7-6 11:12:58 | 显示全部楼层
第一次了解这个东西。
回复 赞! 靠!

使用道具 举报

12

主题

32

回帖

830

积分

用户组: 大·技术宅

UID
5148
精华
2
威望
7 点
宅币
732 个
贡献
30 次
宅之契约
0 份
在线时间
74 小时
注册时间
2019-7-17
发表于 2019-8-4 20:40:34 | 显示全部楼层
微软起的名字还行x 笑了
回复 赞! 靠!

使用道具 举报

QQ|Archiver|小黑屋|技术宅的结界 ( 滇ICP备16008837号 )|网站地图

GMT+8, 2024-3-19 11:58 , Processed in 0.040255 second(s), 33 queries , Gzip On.

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表