簡體   English   中英

選擇sha256解密和md5轉換postgresql和java

[英]select sha256 decrypt and md5 conversion postgresql and java

下午好,我需要將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

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

您的Java方法存在問題,因為它不包含UUID v3所需的名稱空間。 在調用UUID.nameUUIDFromBytes之前,需要在名稱空間之前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');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM