验证码及密码加密在java中使用

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了验证码及密码加密在java中使用相关的知识,希望对你有一定的参考价值。

 

package com.huawei.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.huawei.po.Users;


public class LoginFilter implements Filter{

@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub

}

@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
/**
* 如果请求是登录过的 那就 直接通过 不然就跳转到登录页面
*/
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
//得到session 判断session中是否有用户
HttpSession session = req.getSession();

String uri = req.getRequestURI();

Object users = session.getAttribute("admin");
//登录过的
if(users!=null && users instanceof Users){
chain.doFilter(request, response);
}else{
if(uri.endsWith("login.jsp") || uri.endsWith("loginController") || uri.endsWith(".css") || uri.endsWith(".js") || uri.endsWith(".jpg") || uri.endsWith("image.jsp")){
chain.doFilter(request, response);
}else{
resp.sendRedirect(req.getContextPath()+"/views/login.jsp");
}
}
}

@Override
public void destroy() {
// TODO Auto-generated method stub

}

}

 

 

login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

<title>后台管理 | 登录</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<link href="assets/css/bootstrap.min.css" rel="stylesheet">

<style type="text/css">
body{
background-image: url(‘assets/images/bg1.jpg‘)
}
.login-form{
margin: 0 auto;
margin-top:200px;
max-width: 300px !important;
}
.login-form label{
color:#fff;
}
.valicode:hover{
cursor: pointer;
}
</style>
</head>

<body>

<div class="container">


<form class="form-horizontal login-form" action="login/loginController" method="post">

<div class="form-group">
<label class="control-label col-sm-3 text-right">用户名</label>
<div class="col-sm-9">
<input type="text" name="username" class="form-control" placeholder="用户名" value="${username }">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3 text-right">密 码</label>
<div class="col-sm-9">
<input type="password" name="password" class="form-control" placeholder="密码" value="${password }">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3 text-right">验证码</label>
<div class="col-sm-9">
<div class="input-group">
<input type="text" name="valicode" class="form-control" placeholder="验证码">
<div class="input-group-addon" style="padding:0 2px;">
<img src="views/image.jsp" class="valicode" alt="看不清?换一张!" title="看不清?换一张!" onclick="change(this)"/>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-10">
<div class="checkbox">
<label>
<input type="checkbox" name="remember" value="remember" ${remember ==‘remember‘?‘checked="checked"‘:‘‘ }> 记住密码
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-9 col-sm-offset-3">
<button class="btn btn-default" type="submit">登 录</button>
</div>
</div>
<c:if test="${!empty msg }">
<div class="alert alert-danger alert-dismissible fade in">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
${msg }
</div>
</c:if>
</form>
</div>
</body>
<script type="text/javascript" src="assets/js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="assets/js/bootstrap.min.js"></script>
<script type="text/javascript">
function change(_dom){
_dom.src="views/image.jsp?d="+new Date().getTime();
}
</script>
</html>

 

 

 

LoginController.java

package com.huawei.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.huawei.dao.UsersDAO;
import com.huawei.po.Users;
import com.huawei.service.UsersService;
import com.huawei.utils.EncoderUtil;

/**
* Servlet implementation class LoginController
*/
public class LoginController extends HttpServlet {
private static final long serialVersionUID = 1L;

//private Database database = Database.getDatabase();

//private UsersDAO usersDAO = new UsersDAO();
private UsersService usersService = new UsersService();
/**
* @see HttpServlet#HttpServlet()
*/
public LoginController() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doPost(request, response);
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//处理登录请求
//获取用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
String valicode = request.getParameter("valicode");
//得到状态
String remember = request.getParameter("remember");

if(request.getSession().getAttribute("rand").toString().equalsIgnoreCase(valicode)){
//用户名不能为空
if(username!=null && username.trim()!=""){
//得到一个用户
//User u = (User) this.database.get(username);
// User u = this.usersDAO.findByUsernameAndPassword(username, password);
Users u = this.usersService.findByUsername(username);

if(u!=null && u.getPassword().equals(EncoderUtil.MD5.encode(password))){
//if(u!=null){
//处理成功的情况
HttpSession session = request.getSession();
session.setAttribute("admin", u);
//操作cookie 设置cookie的时候 remember = username:password:state


Cookie []cookies = request.getCookies();
//只是为了找到我要的cookie
Cookie cookie = null;

if(cookies!=null && cookies.length>0){
for(Cookie c:cookies){
if(c.getName().equals("remember")){
cookie = c;
break;
}
}
}

if("remember".equals(remember)){
//处理有cookie和没有cookie的情况
/*if(cookie!=null){

}else{

}*/

cookie = new Cookie("remember", username+":"+password);
cookie.setMaxAge(60*60*24*7);
cookie.setPath(request.getContextPath());
response.addCookie(cookie);

}else{
if(cookie!=null){
cookie.setMaxAge(0);
cookie.setPath(request.getContextPath());
response.addCookie(cookie);
}
}
response.sendRedirect("../users/usersController?_method=findAll");
return ;
}
}
request.setAttribute("msg", "用户名或密码错误,请重试!");
}else{
request.setAttribute("msg", "验证码错误,请重试!");
}
request.setAttribute("username", username);
request.setAttribute("password", password);
request.setAttribute("remember", remember);
request.getRequestDispatcher("/views/login.jsp").forward(request, response);
return ;
}

}

 

 

image.jsp(生成验证码)

<%@page import="java.net.URL" %>
<%@page import="java.io.InputStream" %>
<%@ page language="java" import="java.util.*" pageEncoding="gbk" %>
<%@ page contentType="image/jpeg" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" %>
<%!
Color getRandColor(int fc, int bc) {//给定范围获得随机颜色
Random random = new Random();
if (fc > 255) fc = 255;
if (bc > 255) bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
%>
<%
out.clear();
//设置页面不缓存
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);

// 在内存中创建图象
int width = 70, height = 30;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

// 获取图形上下文
Graphics g = image.getGraphics();

//生成随机类
Random random = new Random();

// 设定背景色
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);

//设定字体
g.setFont(new Font("宋体", Font.PLAIN, 18));
//g.setFont(new Font("Tahoma",Font.PLAIN,18));
//URL url = new URL("http://127.0.0.1:8080/crm/resource/font/SIMSUN.TTC");
//InputStream is = url.openStream();
/* InputStream is = this.getClass().getClassLoader().getResourceAsStream("COURI.TTF");

System.out.println(is);
Font f = Font.createFont(Font.PLAIN, is); */
//f.deriveFont(30);
/* f.deriveFont(Font.PLAIN, 18);
is.close();
g.setFont(f); */

//画边框
g.setColor(Color.black);
g.drawRect(0, 0, width - 1, height - 1);

// 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 155; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}

char[] cs = new char[]{‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘, ‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, ‘g‘, ‘h‘, ‘i‘, ‘j‘, ‘A‘, ‘B‘, ‘M‘};

// 取随机产生的认证码(4位数字)
String sRand = "";
for (int i = 0; i < 4; i++) {
char c = cs[random.nextInt(cs.length)];//[0,4)
String rand = new Character(c).toString();
sRand += rand;
// 将认证码显示到图象中
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
//调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
//g.drawString(rand, 13 * i + 6, 16);
g.drawString(rand, 13 * i + 6, 20);
}

// 将认证码存入session
session.setAttribute("rand", sRand); //这行代码使我们关注的重点
// 图象生效
g.dispose();

// 输出图象到页面
try {
ImageIO.write(image, "JPEG", response.getOutputStream());
} catch (Exception e) {
e.getMessage();
} finally {

//解决以调用错误
out = pageContext.pushBody();

}
%>

以上是关于验证码及密码加密在java中使用的主要内容,如果未能解决你的问题,请参考以下文章

Java关于md5+salt盐加密验证

Java通过BCrypt加密

在 mysql 中使用加密存储密码进行摘要身份验证

在 Java 中使用 PBKDF2 进行密码验证

在 Pyramid 中存储和验证用于登录的加密密码

SCrypt对密码进行加密及密码验证