Java代码把字符串转化为MD5的16进制形式
时间: 2023-12-22 16:06:24 浏览: 153
将字符串转换成MD5码
3星 · 编辑精心推荐
Sure! Here's an example Java code that converts a string to its MD5 hash in hexadecimal form:
```java
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class StringToMD5 {
public static void main(String[] args) {
String input = "Hello World";
String md5Hex = getMD5Hex(input);
System.out.println("MD5 Hash: " + md5Hex);
}
public static String getMD5Hex(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(input.getBytes());
BigInteger number = new BigInteger(1, messageDigest);
String md5Hex = number.toString(16);
while (md5Hex.length() < 32) {
md5Hex = "0" + md5Hex;
}
return md5Hex;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
}
```
In this code, we use the `MessageDigest` class from the `java.security` package to compute the MD5 hash of the input string. We convert the resulting byte array to a `BigInteger` and then convert it to a hexadecimal string using `number.toString(16)`. Finally, we add leading zeros if necessary to ensure that the resulting MD5 hash is 32 characters long.
Note: Make sure to handle the `NoSuchAlgorithmException` appropriately in your application.
阅读全文