【问题标题】:mysql expression for random uuid4?随机uuid4的mysql表达式?
【发布时间】:2020-04-08 21:20:40
【问题描述】:

Mysql 提供了一个UUID() 函数, 它返回一个 rfc 4122 版本 1 guid。 这是一个容易猜到的时间戳 + node_id 位串。

我们如何插入随机的version4 guid?

(定义新函数需要权限并且超出范围。 Ben Johnson 提供了一个非常好的 expression,但有点冗长。)

【问题讨论】:

    标签: mysql random cryptography guid


    【解决方案1】:

    这会插入一个版本 4 的随机字符串,不带破折号。 为了简洁起见,它使用了略微减少的密钥空间部分, 只有 120 位。 (所以 8 位是可预测的,它们是恒定的。)

    -- Produces version 4 guids for mysql, as its UUID() only offers version 1.
    --
    -- See https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_(random)
    -- We consider variant 1 only, ignoring the Microsoft proprietary variant 2.
    -- Version 1 is predictable timestamp.
    -- Version 4 is 122 random bits + 6 constant bits.
    --
    -- The nil guid comes out like this:
    -- UUID('00000000-0000-4000-8000-000000000000')  # 8-4-4-4-12
    -- The nybble '4' is constant version.
    -- The nybble '8' has hi bit set, next bit cleared, plus two wasted bits.
    -- We deliberately choose to emit just 120 random bits, for simplicity.
    -- The RAND() function returns about 53 bits of entropy in the mantissa,
    -- so for 15 nybbles we call it twice to obtain 106 ( > 60 ) unguessable bits.
    -- The standard spelling of a guid, with four '-' dashes, is 36 characters.
    -- We emit 32 hex characters, sans dashes.
    
    INSERT INTO guid_test (guid) VALUES (
      concat(substr(sha2(rand(), 256),                 1, 12),
        '4', substr(sha2(rand(), 256),                 1,  3),
        '8', substr(sha2(concat(rand(), rand()), 256), 1, 15)
      )
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-10
      • 1970-01-01
      • 2018-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多