需要导入的依赖
<!-- MD5加密依赖 -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
MD5Utils工具类(参考别人代码写的)
package cn.tedu.kawasaki.utils;
import org.apache.commons.codec.digest.DigestUtils;
/**
* md5工具类
*
* @author Edgar
* @version 1.0.0
* @date 2022/12/27
*/
public class MD5Utils {
public static String md5(String src) {
//用的是Md5消息摘要加密(没有用盐值)
return DigestUtils.md5Hex(src);
}
//默认盐值
private static final String salt = "1a2b3c4d";
/**
* 采用默认盐值(其实也是自己定义的)加密
*
* @param inputPass 输入的密码
* @return {@link String}
*/
public static String inputPassToFormPass(String inputPass) {
String str = ""+salt.charAt(0)+salt.charAt(2) + inputPass +salt.charAt(5) + salt.charAt(4);
System.out.println(str);
return md5(str);
}
/**
* 采用自定义盐值加密
*
* @param formPass 密码
* @param salt 盐
* @return {@link String}
*/
public static String formPassToDBPass(String formPass, String salt) {
String str = ""+salt.charAt(0)+salt.charAt(2) + formPass +salt.charAt(5) + salt.charAt(4);
return md5(str);
}
/**
* 自定义加密(未采用Md5)
*
* @param inputPass 密码
* @param saltDB 盐
* @return {@link String}
*/
public static String inputPassToDbPass(String inputPass, String saltDB) {
String formPass = inputPassToFormPass(inputPass);
String dbPass = formPassToDBPass(formPass, saltDB);
return dbPass;
}
}
service层密码加密后保存
//验证邮箱是否注册过
UserVO userVO = userMapper.selectByEmail(email);
if (userVO==null){
//将密码进行加密
pwd = MD5Utils.inputPassToFormPass(pwd);
//先将一个未激活的用户插入到数据库中
User user = User.builder()
.email(email)
.password(pwd)
.state(0)
.build();
int rows = userMapper.insert(user);
.....
如何验证密码是否正确
public void userLogin(String email, String pwd) {
UserVO userVO = userMapper.selectByEmail(email);
if (userVO==null){
String message = "登录失败,您输入的用户不存在!";
throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
}
//将从数据库查出的密码与用户输入加密后的密码进行比较
if (!userVO.getPassword().equals(MD5Utils.inputPassToFormPass(pwd))){
String message = "登录失败,密码错误";
throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
}
}