定义加密的工具类
package com.ctgu.yxr.utils;import java.io.UnsupportedEncodingException;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;/*** @author yxr*/public class EncodeBySHA256 {public static String encodeBySHA(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");messageDigest.update(password.getBytes("UTF-8"));return byte2Hex(messageDigest.digest());}private static String byte2Hex(byte[] bytes){StringBuffer stringBuffer = new StringBuffer();String temp = null;for (int i = 0; i < bytes.length; i++) {temp = Integer.toHexString(bytes[i] & 0xFF);if (temp.length() == 1) {// 1得到一位的进行补0操作stringBuffer.append("0");}stringBuffer.append(temp);}return stringBuffer.toString();}}
注册新用户
service实现类:
/*** 注册新用户* @param user 用户信息* @return 存储后的信息*/@Overridepublic User addOne(User user) throws NoSuchAlgorithmException, UnsupportedEncodingException {String password = user.getPassword();String encodePwd = EncodeBySHA256.encodeBySHA(password);user.setPassword(encodePwd);return userDao.save(user);}
用户登录
登录逻辑:根据用户的用户名查到对应加密后的密码,然后把用户输入进来的密码进行同样的加密,将加密后得到的字符串和数据库中存的字符串进行比对,如果一样,则登录成功。反之,登陆失败。
/*** 登录* @param userName 用户名* @param pwd 密码* @return 是否成功*/@Overridepublic Boolean login(String userName, String pwd) throws UnsupportedEncodingException, NoSuchAlgorithmException {String pwdByName = userDao.getPwdByName(userName);String encodePwd = EncodeBySHA256.encodeBySHA(pwd);return encodePwd.equals(pwdByName);}
