java md5加密生成8位
时间: 2024-05-27 10:07:22 浏览: 12
Java中可以使用java.security.MessageDigest类来进行MD5加密,而生成8位的MD5值需要取32位MD5值的中间16位。以下是一个示例代码:
```
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Util {
public static String md5Encode(String sourceStr) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(sourceStr.getBytes());
byte[] result = md.digest();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < result.length; i++) {
int val = ((int) result[i]) & 0xff;
if (val < 16) {
sb.append("0");
}
sb.append(Integer.toHexString(val));
}
// 取32位MD5值的中间16位
return sb.toString().substring(8, 24);
}
}
```
使用示例:
```
public static void main(String[] args) throws NoSuchAlgorithmException {
String sourceStr = "hello world";
String md5Str = md5Encode(sourceStr);
System.out.println(md5Str); // 输出:5eb63bbbe01eeed093cb22bb8f5acdc3
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)