MD5工具类

实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package cn.idea360.demo.modules.sign;


import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
* @author 当我遇上你
* @公众号 当我遇上你
* @since 2020-08-30
*/
public class MD5Utils {

public static void main(String[] args) throws Exception{
String content = "当我遇上你";

// 方式1
System.out.println(org.springframework.util.DigestUtils.md5DigestAsHex(content.getBytes()).toUpperCase()); // B50E55687698915F9F70C7470DBA6E2F

// 方式二
System.out.println(getMd5(content));

// 方式三
System.out.println(org.apache.commons.codec.digest.DigestUtils.md5Hex(content).toUpperCase());

}

public static String getMd5(String input)
{
try {

// Static getInstance method is called with hashing MD5
MessageDigest md = MessageDigest.getInstance("MD5");

// digest() method is called to calculate message digest
// of an input digest() return array of byte
byte[] messageDigest = md.digest(input.getBytes());

// Convert byte array into signum representation
BigInteger no = new BigInteger(1, messageDigest);

// Convert message digest into hex value
String hashtext = no.toString(16);
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
return hashtext.toUpperCase();
}

// For specifying wrong message digest algorithms
catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
}

最后

本文到此结束,感谢阅读。如果您觉得不错,请关注公众号【当我遇上你】,您的支持是我写作的最大动力。