使用MD5对密码进行加密和加盐
1 public class MD5Utils {
2 private static final int SIGNUM = 1;
3 /**
4 * hex值
5 */
6 private static final int HEX_FLAG = 16;
7 /**
8 * 签名的长度
9 */
10 private static final int SIGN_LENGTH = 32;
11 /**
12 * 填充值
13 */
14 private static final String FILL_CHAR = "0";
15 /**
16 * md5 32位加密方法
17 *
18 * @param input
19 * @return
20 */
21 public static String getMd5(String input) {
22 try {
23 MessageDigest md = MessageDigest.getInstance("MD5");
24 byte[] messageDigest = md.digest(input.getBytes(Charset.forName("UTF-8")));
25 BigInteger number = new BigInteger(SIGNUM, messageDigest);
26 String hashtext = number.toString(HEX_FLAG);
27 while (hashtext.length() < SIGN_LENGTH) {
28 hashtext = FILL_CHAR + hashtext;
29 }
30 return hashtext.toUpperCase();
31 } catch (NoSuchAlgorithmException e) {
32 throw new RuntimeException(e);
33 }
34 }
35
36 public static void main(String[] args) {
37
38 // 方式一: 使用自定义的MD5加密工具类
39 String password = MD5Utils.getMd5("abc123ABC");
40 System.out.println("password:"+ password);
41
42 // 加盐,随机生成6位数字和字母混合的字符串
43 String salt = RandomStringUtils.randomAlphanumeric(6);
44 System.out.println("salt:" + salt);
45
46 String saltPassword = MD5Utils.getMd5("abc123ABC" + salt);
47 System.out.println("saltPassword:" + saltPassword);
48
49 // 方式二: 使用springboot自带的MD5加密封装类DigestUtils
50 String pwd = DigestUtils.md5DigestAsHex("abc123ABC".getBytes());
51 System.out.println("pwd:" + pwd.toUpperCase());
52 }
53 }
输出结果: