加密工具类
package com.manager.util;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* EncoderByMd5
*/
public class MD5Util {
public static String EncoderByMd5(String str) {
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
// 这句是关键
md5.update(str.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
byte b[] = md5.digest();
int i;
StringBuffer buf = new StringBuffer();
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if (i < 0)
i += 256;
if (i < 16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
System.out.println(buf.toString());
return buf.toString();
}
public static void main(String[] args) {
System.out.println(MD5Util.EncoderByMd5("Simon"));
}
}
数据库插入语句,密码字段MD5加密:
INSERT INTO employees(id,uname,uloginname,upwd,urealname,role,phone) VALUES(DEFAULT,'ZHB007','admin',MD5('admin'),'尚鸿运',1,'13312341234',1,1,1,1,NOW(),1,NOW(),NULL,NULL); /*其中upwd密码值用MD5括起来*/
插入后的值加密(32位):
登录的代码:
@RequestMapping(value = "/login", method = RequestMethod.POST)
@ResponseBody
public Object loginajax(HttpSession session, Employees employees) {
Map<String, String> map = new HashMap<>();
Employees employee = employeesService.getEmployees(employees);
if (employee != null) {
String pwd = MD5Util.EncoderByMd5(employees.getE_Pwd()); //调用加密工具类方法将输入的密码加密和数据库的密码字段值相对应
if (pwd.equals(employee.getE_Pwd())) { //判断密码是否相同
session.setAttribute("loginEmployee", employee);//登陆成功保存会话
employee.setE_LastLoginTime(new Date());
employeesService.alterEmployees(employee);
} else {
map.put("msg", "false");
}
} else {
map.put("msg", "null");
}
return map;
}