这个Java UUID5实现没有通过单元测试 [英] this Java UUID5 implementation not passing unit test

查看:151
本文介绍了这个Java UUID5实现没有通过单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到Java的自包含UUID5实现,所以我尝试在下面推广这个解决方案。它通过我的一些单元测试,但其他人失败。这有明显的错误吗?

I couldn't find a self-contained UUID5 implementation for Java, so I tried rolling this solution below. It passes some of my unit tests but fails others. Any obvious bugs in this?

public static UUID UUID5(UUID namespace, String name) {
    MessageDigest md;
    try {
        md = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException nsae) {
        throw new InternalError("SHA-1 not supported");
    }

    byte[] namespaceBytes = ByteBuffer.allocate(16).putLong(namespace.getMostSignificantBits()).putLong(namespace.getLeastSignificantBits()).array();
    byte[] nameBytes;
    try {
        nameBytes = name.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new InternalError("UTF-8 encoding not supported");
    }

    byte[] toHashify = new byte[namespaceBytes.length + nameBytes.length];
    System.arraycopy(namespaceBytes, 0, toHashify, 0, namespaceBytes.length);
    System.arraycopy(nameBytes, 0, toHashify, namespaceBytes.length, nameBytes.length);

    byte[] data = md.digest(toHashify);
    data = Arrays.copyOfRange(data, 0, 16); // Wikipedia says "Note that the 160 bit SHA-1 hash is truncated to 128 bits to make the length work out."

    data[6]  &= 0x0f;  /* clear version        */
    data[6]  |= 0x50;  /* set to version 5     TODO is this the correct way to do it     */
    data[8]  &= 0x3f;  /* clear variant        */
    data[8]  |= 0x80;  /* set to IETF variant  */

    long msb = 0;
    long lsb = 0;
    assert data.length == 16 : "data must be 16 bytes in length";
    for (int i=0; i<8; i++)
        {msb = (msb << 8) | (data[i] & 0xff);}
    for (int i=8; i<16; i++)
        {lsb = (lsb << 8) | (data[i] & 0xff);}

    return new UUID(msb, lsb);
}


推荐答案

使用 Apache Commons Id ,更具体地说是 UUID.nameUUIDFromString

UUID uuid5 = UUID.nameUUIDFromString("www.ford.com", 
       UUID.fromString("078d4e79-244f-440e-844d-9454eadfd411"),
       UUID.SHA1_ENCODING);

UUID.SHA1_ENCODING 将生成版本5 UUID 。

UUID.SHA1_ENCODING will generate version 5 UUIDs.

这篇关于这个Java UUID5实现没有通过单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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