Spring Boot项目开发(四)——用户注册密码加密

1、编写MD5加密工具类

加密过程需要对密码加盐,否则可以通过网络工具轻易解密出密码

package com.learn.mall.util;

import com.learn.mall.common.Constant;
import org.apache.tomcat.util.codec.binary.Base64;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5加密工具
 */
public class MD5Utils {
    public static String getMD5Str(String val) throws NoSuchAlgorithmException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        return Base64.encodeBase64String(md5.digest((val+Constant.SALT).getBytes()));
    }

    public static void main(String[] args) {
        try {
            System.out.println(getMD5Str("yang"+Constant.SALT));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
}

 2、定义盐的常量类

定义盐时尽量复杂,否则加盐没有任何意义

package com.learn.mall.common;

/**
 * 常量值
 */
public class Constant {
    //加盐
    public static final String SALT = "2wef65h#$%JVG<:}{>";
   
}

3、使用方法

package com.learn.mall.service.impl;

import com.learn.mall.exception.LearnMallException;
import com.learn.mall.exception.LearnMallExceptionEnum;
import com.learn.mall.model.dao.UserMapper;
import com.learn.mall.model.pojo.User;
import com.learn.mall.service.UserService;
import com.learn.mall.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public void register(String username, String password) throws LearnMallException {
        //查询用户是否存在,不允许重名
        User result = userMapper.selectByName(username);
        if (result != null) {
            throw new LearnMallException(LearnMallExceptionEnum.USERNAME_EXISTED);
        }
        //用户不存在,执行插入操作
        User user = new User();
        user.setUsername(username);
        //对密码进行MD5加密并加盐
        try {
            user.setPassword(MD5Utils.getMD5Str(password));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        int count = userMapper.insertSelective(user);
        if(count == 0){
            throw new LearnMallException(LearnMallExceptionEnum.INSERT_FAILED);
        }
    }
}

 

posted @ 2020-12-05 15:46  michealyangblog  阅读(477)  评论(0编辑  收藏  举报