MD5加密(亲测有用)

一、示例:MD5对用户密码进行加密

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mengmeng2222222/article/details/85071118
亲测有效,可以转发共享资源,但是请备注上我的博客地址谢谢。
1、LoginController 类:
通过MD5Util类中的encode方法来进行对密码进行加密(本示例是添加盐值加密)

public class LoginController {
	 public String login(@RequestParam(value = "username")String username,@RequestParam(value="password")String password,HttpServletRequest request) {
	        if (!MD5Util.encode(password, username).matches(user.getPassword())) {
	            return MarkUtil.markRetunMsg(false, "密码错误");
	        }
	   }
}

2、MD5Util类:

public class MD5Util {

    public static String encode(String password,String salt) {
        if(null==salt||StringUtils.isEmpty(salt)) {
            password = password + ContentUtil.SALT; //添加盐值加密
        }else{
            password = password + salt;
        }
        return processEncode(password);  //加密
    }

 public static String processEncode(String password) {
        try {
          //生成一个MD5加密计算摘要
          MessageDigest   md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        char[] charArray = password.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++)
           	byteArray[i] = (byte) charArray[i];
	        byte[] md5Bytes = md5.digest(byteArray);
	        StringBuffer hexValue = new StringBuffer();
	        for (int i = 0; i < md5Bytes.length; i++) {
	        int val = ((int) md5Bytes[i]) & 0xff;
	         if (val < 16) {
	             hexValue.append("0");
	         }
	         hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }
}

你可能感兴趣的:(java开发,MD5加密算法)