下午好,我需要将UUID转换为sha256,然后再转换为md5,在Java中它可以工作,但是如果我通过pgadmin(postgres)做到这一点,则1个字符不同
在Java中
public class outro {
public static void main(String[] args) {
String prontuarioBaseUUID = "a1d347fc-094f-49de-91b9-f2765c58b94d";
System.out.println(uuidSha2Encrypt(prontuarioBaseUUID));
}
public static String uuidSha2Encrypt(String uuid) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(uuid.getBytes());
return UUID.nameUUIDFromBytes(md.digest()).toString();
} catch (NoSuchAlgorithmException ns) {
throw new RuntimeException("Algoritmo SHA-256 não disponível", ns);
}
}
结果 d5fabb45-dbd1-399b-a6c1-515367b8a2d4
在pgadmin postgres中
从tb_paciente中选择uuid_in(md5(digest('a1d347fc-094f-49de-91b9-f2765c58b94d','sha256')):: cstring)
结果 d5fabb45-dbd1-b99b-a6c1-515367b8a2d4
什么问题? thxx
答案 0 :(得分:4)
您的Java方法有一个问题,因为它不包含UUID v3所需的名称空间。您需要在调用UUID.nameUUIDFromBytes
之前在名称空间前添加名称:
private static final UUID NAMESPACE = UUID.fromString("00000000-0000-0000-0000-000000000000");
public static void main(String[] args) {
// Charset should match SERVER_ENCODING
System.out.println(uuidV3(NAMESPACE, "test".getBytes(StandardCharsets.UTF_8)));
}
public static UUID uuidV3(UUID namespace, byte[] name) {
byte[] ns = toBytes(namespace);
byte[] nsAndName = concatenate(ns, name);
return UUID.nameUUIDFromBytes(nsAndName);
}
public static byte[] concatenate(byte[] a, byte[] b) {
byte[] result = new byte[a.length + b.length];
System.arraycopy(a, 0, result, 0, a.length);
System.arraycopy(b, 0, result, a.length, b.length);
return result;
}
public static byte[] toBytes(UUID uuid) {
ByteBuffer buffer = ByteBuffer.wrap(new byte[16]);
buffer.putLong(uuid.getMostSignificantBits());
buffer.putLong(uuid.getLeastSignificantBits());
return buffer.array();
}
在上面的示例中,我使用了nil命名空间,但是它可以是任何东西。
上面的测试打印
96e17d7a-ac89-38cf-95e1-bf5098da34e1
与等效的postgres查询的输出匹配:
select uuid_generate_v3(uuid_nil(), 'test');