提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
- hutool
- 1.简介
- 2.pom.xml
- 3.Hutool-crypto概述
- 4.MD5 加密
- 案例1
- 1.hutool依赖
- 2.用户表
- 3.加密方法
- 4.业务代码
hutool
https://www.hutool.cn/docs/#/
1.简介
2.pom.xml
<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.16</version>
</dependency>
3.Hutool-crypto概述
4.MD5 加密
public static void main(String[] args) throws IOException {String testStr="123456";//DigesterDigester md5 = new Digester(DigestAlgorithm.MD5);String digestHex = md5.digestHex(testStr);System.out.println(digestHex);//DigestUtilString md5Hex1 = DigestUtil.md5Hex(testStr);System.out.println(md5Hex1); //e10adc3949ba59abbe56e057f20f883e}
案例1
1.hutool依赖
<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>4.5.2</version></dependency>
2.用户表
- password
- salt
- hash_iterations
3.加密方法
/*** 对密码进行md5加密**/private String md5Password(String salt, int hashCount, String password) {return MD5.create().setSalt(salt.getBytes()).setDigestCount(hashCount).digestHex(password);}
4.业务代码
- 新增账号
String salt = String.valueOf(new Random().nextInt(rangNum) + 1);int hashIterations = 3;//新增String encryptNewPwd = MD5.create().setSalt(salt.getBytes()).setDigestCount(hashIterations).digestHex(reqDTO.getPassword());dbUserModel.setPassword(encryptNewPwd);userMapper.insert(dbUserModel);
- 登录
@Overridepublic AuthSessionEntity login(UserLoginReqDTO reqDTO) {String userName = reqDTO.getUserName();String password = reqDTO.getPassword();UserModel userModel = getValidUser(userName);if(userModel==null){throw new AppException("账号不存在,请联系管理员创建账号");}//检查账号是否被锁住verifyUserAccountLock(userModel.getUserId());String encryptPwd = md5Password(userModel.getSalt(), userModel.getHashIterations(), password);if (!StringUtils.equals(encryptPwd, userModel.getPassword())) {//如果密码错误,记录密码连续错误的次数,次数达到指定的阈值,锁住用户的账号addLoginErrorCountOrLocked(userModel.getUserId());throw new AppException("账号或密码错误,请重新输入");}//登录成功,删除连续登录失败的记录resetErrorLoginCount(userModel.getUserId());return createAuthSessionEntity(userModel);}/*** 对密码进行md5加密**/private String md5Password(String salt, int hashCount, String password) {return MD5.create().setSalt(salt.getBytes()).setDigestCount(hashCount).digestHex(password);}