java中的md5加密 字典排序
时间: 2024-09-05 14:00:39 浏览: 41
MD5是一种广泛使用的哈希函数,在Java中,你可以使用`java.security.MessageDigest`类及其`getInstance()`方法来生成MD5散列值。例如:
```java
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
public class MD5Example {
public static String computeMD5(String input) {
try {
Mac mac = Mac.getInstance("HmacSHA256");
byte[] keyBytes = "your-secret-key".getBytes(StandardCharsets.UTF_8);
SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "HmacSHA256");
mac.init(secretKey);
byte[] hashBytes = mac.doFinal(input.getBytes(StandardCharsets.UTF_8));
return bytesToHex(hashBytes);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static String bytesToHex(byte[] bytes) {
StringBuilder result = new StringBuilder();
for (byte b : bytes) {
result.append(String.format("%02x", b & 0xff));
}
return result.toString();
}
// 示例
public static void main(String[] args) {
String input = "Hello World";
String md5 = computeMD5(input);
System.out.println("MD5 Hash: " + md5);
}
}
```
字典排序(也称为自然排序或基数排序)通常用于整数数组的排序,Java本身并不内置对字符串进行字典排序的功能。但在实际编程中,你可以通过比较字符的Unicode编码来实现基本的字典顺序。例如:
```java
public int compareStrings(String s1, String s2) {
for (int i = 0; i < Math.min(s1.length(), s2.length()); i++) {
if (s1.charAt(i) != s2.charAt(i)) {
return Integer.compare(s1.charAt(i), s2.charAt(i));
}
}
return s1.length() - s2.length();
}
// 示例
String[] words = {"banana", "apple", "cherry"};
Arrays.sort(words, compareStrings);
System.out.println(Arrays.toString(words)); // 输出: [apple, banana, cherry]
```
阅读全文