java hash算法
时间: 2023-06-24 11:07:51 浏览: 172
Java 中常用的 Hash 算法有以下几种:
1. MD5(Message Digest Algorithm 5):MD5 是一种单向加密算法,不可逆,常用于验证数据的完整性和一致性。
```java
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class HashAlgorithms {
public static void main(String[] args) throws NoSuchAlgorithmException {
String input = "hello world";
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] mdBytes = md.digest(input.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : mdBytes) {
hexString.append(String.format("%02x", b));
}
System.out.println(hexString.toString());
}
}
```
2. SHA(Secure Hash Algorithm):SHA 也是一种单向加密算法,主要用于数字签名和验证数据的完整性。
```java
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class HashAlgorithms {
public static void main(String[] args) throws NoSuchAlgorithmException {
String input = "hello world";
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] mdBytes = md.digest(input.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : mdBytes) {
hexString.append(String.format("%02x", b));
}
System.out.println(hexString.toString());
}
}
```
3. MurmurHash:MurmurHash 是一种高性能 Hash 算法,适用于大规模数据集的 Hash 计算。
```java
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
public class HashAlgorithms {
public static void main(String[] args) {
String input = "hello world";
HashFunction hf = Hashing.murmur3_128();
HashCode hc = hf.hashBytes(input.getBytes());
System.out.println(hc.toString());
}
}
```
4. CRC32(Cyclic Redundancy Check):CRC32 是一种循环冗余校验算法,常用于数据传输或存储时的错误检测。
```java
import java.util.zip.CRC32;
public class HashAlgorithms {
public static void main(String[] args) {
String input = "hello world";
CRC32 crc32 = new CRC32();
crc32.update(input.getBytes());
System.out.println(crc32.getValue());
}
}
```
以上 Hash 算法都有其特定的应用场景,具体选择哪种算法需要根据具体的需求来决定。
阅读全文
相关推荐















