需求:将中文字符串转为对应的hash值
package util;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* @Author: ZD
* @Date: 2023/8/29
*/
public class HashUtil {
public static long chineseSentenceToHash(String sentence) throws NoSuchAlgorithmException {
// 将中文语句编码为字节序列
byte[] encodedBytes = sentence.getBytes(StandardCharsets.UTF_8);
// 创建SHA-256哈希算法实例
MessageDigest digest = MessageDigest.getInstance("SHA-256");
// 计算哈希值
byte[] hashBytes = digest.digest(encodedBytes);
// 将哈希值转换为长整型
long hashValue = byteArrayToLong(hashBytes);
return hashValue;
}
private static long byteArrayToLong(byte[] bytes) {
long value = 0;
for (int i = 0; i < 8 && i < bytes.length; i++) {
value |= ((long) (bytes[i] & 0xFF)) << (8 * i);
}
return value;
}
public static void main(String[] args) throws NoSuchAlgorithmException {
String chineseSentence = "";
long hashValue = chineseSentenceToHash(chineseSentence);
System.out.println(hashValue);
}
}
标签:java,long,哈希,import,字符串,hash,byte,digest
From: https://blog.51cto.com/u_16199760/7470883