Java随机UUID是否可预测? [英] Are Java random UUID's predictable?

查看:889
本文介绍了Java随机UUID是否可预测?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对数据库中的敏感数据使用加密安全主键 - 这是无法猜测/可预测的,并且它不能由数据库生成(我需要在持久化对象之前使用密钥)。

I would like to use a cryptographically secure primary key for sensitive data in a database - this cannot be guessable/predictable and it cannot be generated by the database (I need the key before the object is persisted).

我理解Java使用带有加密安全随机数生成器的4型UUID,但是我知道UUID不是完全随机的所以我的问题是假设uuids不能安全可以从一组现有的预测中得到预测吗?

I understand Java uses a type 4 UUID with a cryptographically secure random number generator, however I know the UUID isn't completely random so my question is how safe is it to assume that uuids cannot be predicted from a set of existing ones?

推荐答案

如果你想知道UUID是多么随机,你必须要看一下来源。

Well if you want to know how random a UUID is you have to look onto the source.

以下代码部分取自 OpenJDK7 (在 OpenJDK6 ):

The following code section is taken from OpenJDK7 (and it is identical in OpenJDK6):

public static UUID randomUUID() {
        SecureRandom ng = numberGenerator;
        if (ng == null) {
            numberGenerator = ng = new SecureRandom();
        }

        byte[] randomBytes = new byte[16];
        ng.nextBytes(randomBytes);
        randomBytes[6]  &= 0x0f;  /* clear version        */
        randomBytes[6]  |= 0x40;  /* set to version 4     */
        randomBytes[8]  &= 0x3f;  /* clear variant        */
        randomBytes[8]  |= 0x80;  /* set to IETF variant  */
        return new UUID(randomBytes);
    }

正如您所看到的,16个字节中只有2个不是完全随机的。在第六个字节中,您将丢失8个中的4个,在字节8上,您将丢失2位随机性。

As you can see only 2 of 16 bytes are not completely random. In the sixth byte you lose 4 of 8 bits and on byte 8 you loose 2 bits of randomness.

因此,您将获得具有122位随机性的128位值。

Therefore you will get an 128 bit value with 122 bit randomness.

操作可能产生的唯一问题是,您的数据很有可能被识别为UUID。因此,如果您想将其隐藏在其他随机数据中,这将无效...

The only problem that may arise from the manipulation is that with a high chance your data can be identified as an UUID. Therefore if you want to hide it in other random data this will not work...

这篇关于Java随机UUID是否可预测?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆