Mahoni
Mahoni

Reputation: 7466

Derive random seed from UUID

To produce deterministic randomization for subsequent requests of clients I need to seed a random generator based on an UUID.

Is there a good way for doing this? The approach I am currently considering taking would be:

number := new(big.Int)
target := new(big.Int)
number.SetBytes(uuid.Bytes())
seed := number.Mod(target, big.NewInt(math.MaxInt64)).Int64()

Which is flawed in the sense that it makes collisions more likely but okay right now given there are only few requests coming in.

Upvotes: 0

Views: 1009

Answers (1)

Hymns For Disco
Hymns For Disco

Reputation: 8395

In general I think you should at least hash the UUID bytes before using them as a seed.

(You should know, I'm not a cryptography or security expert. This is just my analysis based on my understanding and some quick googling).

number := new(big.Int)
target := new(big.Int)
// Get hash of the UUID
sum := md5.Sum(uuid.Bytes())[:]
number.SetBytes(sum)
seed := number.Mod(target, big.NewInt(math.MaxInt64)).Int64()

Taking the modulus is essentially just taking a certain number of least significant bits. UUID format has a layout where groups of bytes are for specific information.

If using google's UUID, you're actually only getting about 15 bits of entropy here. This is because of the UUID format.

By taking on mod math.MaxInt64, you're taking in the least significant 63 bits (~8 bytes) of the UUID. However, the last 6 bytes (48 bits) are dedicated to the "Node id". This is an identifier associated with which "node" generated the UUID. This means that for any UUIDs generated on the same node, those 48 bits will be the same. The next higher 2 bytes are clock sequence values, which should be a decent source of entropy, but you're only getting 15 bits (63 - 48) of it.

After hashing the UUID, you've essentially "mixed the entropy around", so that you don't have to worry if particular spans of bits are relatively static or not.

See the original RFC declaring the layout standard https://www.rfc-editor.org/rfc/rfc4122#section-4.1.2

If you are using some other UUID library, you should verify that they are actually following this standard.

Upvotes: 2

Related Questions