select sha256 decrypt and md5 conversion postgresql and java

Viewed 848

Good afternoon, I need to convert a UUID to sha256 and later to md5, in java it worked, but if I do it by pgadmin(postgres) 1 character is different

in 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);
    }
}

result d5fabb45-dbd1-399b-a6c1-515367b8a2d4

in pgadmin postgres

select uuid_in(md5(digest('a1d347fc-094f-49de-91b9-f2765c58b94d', 'sha256'))::cstring) from tb_paciente

result d5fabb45-dbd1-b99b-a6c1-515367b8a2d4

what is problem? thxx

  1. d5fabb45-dbd1-399b-a6c1-515367b8a2d4
  2. d5fabb45-dbd1-b99b-a6c1-515367b8a2d4
1 Answers

There's problem with your Java method in that it doesn't include the namespace required by UUID v3. You need to prepend the namespace to the name before calling 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();
}

I've used the nil namespace in the above example, but it could be anything.

The test above prints

96e17d7a-ac89-38cf-95e1-bf5098da34e1

Which matches the output of the equivalent postgres query:

select uuid_generate_v3(uuid_nil(), 'test');
Related