使用 Hutool 工具库中的 Bcrypt 类实现密码加密。
导入依赖(pom.xml):
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.3.8</version>
</dependency>
密码加密工具类:
import cn.hutool.crypto.digest.BCrypt;
/* 密码加密工具类 */
public class BcryptUtil {
// 加密
public static String encode(String password) {
return BCrypt.hashpw(password, BCrypt.gensalt());
}
// 验证
public static boolean match(String password, String encodePassword) {
return BCrypt.checkpw(password, encodePassword);
}
}
注册 + 密码加密:
@Service
public class MerchantServiceImpl implements MerchantService {
@Autowired
private MerchantDao merchantDao;
@Override
public Result<Merchant> register(Merchant merchant) {
Merchant existMerchant = merchantDao.selectByPrimaryKey(merchant.getMid());
if (existMerchant != null)
return Result.fail("用户已存在!");
merchant.setPassword(BcryptUtil.encode(merchant.getPassword())); // 密码加密
merchantDao.addMerchant(merchant);
return Result.success("注册成功!", merchant);
}
}
参考文章:springboot+shiro实现自定义密码加密及验证(Bcrypt)_shiro修改bcrypt-CSDN博客