zoukankan      html  css  js  c++  java
  • 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);
            }
        }
    }
  • 相关阅读:
    接口报错mixed content blocked
    重拾单片机
    部署ajax服务-支持jsonp
    linkageSystem--串口通信、socket.io
    node安装问题
    jshint之对!的检验
    node之websocket
    调试node服务器-过程
    oracle取某字符串字段的后4位
    vmware 共享文件夹
  • 原文地址:https://www.cnblogs.com/michealyang/p/14089934.html
Copyright © 2011-2022 走看看