我正在尝试使用SHA384
在Java中生成48个字符的哈希字符串,输出应类似于以下内容:
PÊ&¿a»@óæS0iÛ6në0Ê`o€X·„ \Kâ¢ï¼fÖ…)nE @ó^ s
我当前的实现如下:
public static String getHash(byte[] inputBytes, String algorithm) throws Exception{
String hashValue = "";
try {
MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
messageDigest.update(inputBytes);
byte[] digestedBytes = messageDigest.digest();
hashValue =
DatatypeConverter.printHexBinary(digestedBytes).toLowerCase();
} catch(Exception e) {
e.printStackTrace();
}
return hashValue;
}
public static void main(String[] args) throws Exception {
System.out.println(getHash("The quick brown fox Jumps over the lazy dog".getBytes(), "SHA-384"));
}
输出:
b94a2179d90daf662f2ae8e41f92c2831eb0eea5a352f81ac7b0a80a07b2c357d88d0e3fc12bf4f0d888335508b09c41
观察到,输出字符串是96个字符串,而不是48个字符串,我在做什么错了?
答案 0 :(得分:1)
您可以尝试以下操作:
import java.security.MessageDigest;
public class Main {
public static String getHash(byte[] inputBytes, String algorithm) throws Exception{
try {
MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
messageDigest.update(inputBytes);
byte[] digestedBytes = messageDigest.digest();
return new String(digestedBytes, "UTF-8");
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws Exception {
System.out.println(getHash("The quick brown fox Jumps over the lazy dog".getBytes(), "SHA-384"));
}
}
这将使用UTF-8编码将48字节数组转换为字符串。但是,并非所有字节都代表可打印的字符,因此您最终得到的字符数会略少一些。
答案 1 :(得分:0)
package com.journaldev.examples;
import java.util.UUID;
/**
* Java UUID randomUUID Example
*
*/
public class UUIDExample {
public static void main(String[] args) {
//initialize uuid
UUID uuid = UUID.randomUUID();
System.out.println(uuid);
}
}
尝试使用此方法生成随机ID