java 生成随机校验码

时间:2023-03-08 17:04:38

  1 import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import java.awt.FontMetrics;
import javax.imageio.ImageIO; public class CreateRandomCode {
14 static String Path = "XXXXXX"; // 用户用户存放验证码的库 用户可以从库中加载验证码
15 static int RandomCount = 5; // 随机数字的位数
16 static int Width = 120; // 验证码的宽度 当校验码显示不全的时候请调整此宽度
17 static int Height = 40; // 验证码的高度
18 static int FontSize = 30; // 字体的大小 当校验码显示字体太小的时候请调整此大小 public static Color getRandColor(int fc, int bc) {// 给定范围获得随机颜色
Random random = new Random();
fc = fc > 255 ? 255 : fc;
bc = bc > 255 ? 255 : bc;
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);
} public static void getCode() {
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); // 设定字体
Font font = new Font("Times New Roman", Font.PLAIN, FontSize); // 当校验码显示字体不好看的时请调整此大小 g.setFont(font);
FontMetrics fm = g.getFontMetrics(font); // System.out.println("字体大小:"+font.getSize());
// System.out.println("字体宽度:"+fm.getAscent());
// System.out.println("字体高度:"+fm.getHeight()); // 画边框
g.setColor(new Color(30, 20, 10)); // 设置边框的颜色
g.drawRect(0, 0, Width - 1, Height - 1); // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
for (int i = 0; i < 155; i++) {
g.setColor(getRandColor(160, 200)); // 设置线条的颜色
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); } // 取随机产生的认证码(4位数字) RandomCount = 4 String sRand = "";
for (int i = 0; i < RandomCount; i++) {
String rand = String.valueOf(random.nextInt(10));
sRand += rand;
// 将认证码显示到图象中
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));// 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
// 将数字画到画板上
g.drawString(rand, (int) (Width * i * 0.2 + 6), (int) (Height * 0.8)); // 参数一:字符 参数二: x坐标 参数三:y坐标
}
g.dispose(); File file = new File(Path + sRand + ".png");
OutputStream output = null;
try {
if (!file.exists()) {
file.createNewFile();
} else {
System.out.println("验证码:" + sRand + "已存在!");
}
output = new FileOutputStream(file, true); ImageIO.write(image, "png", output);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} public static void main(String[] args) {
// 随机产生一百张验证码图片 验证码库 生成一个验证码库,用户从验证码库中随机挑选一个
for (int i = 0; i < 100; i++) {
getCode();
} }
}

以上为方案一:

生成的随机验证码附图如下:

  java 生成随机校验码

当需要使用验证码时,提供两种思路:

思路一:

采用OutputStream流逻辑,将验证码的文件流推送给response的流,这样Web界面上就可以显示验证码,提供参考代码如下:

image.jsp

 <%@ 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);
}%>
<%
//设置页面不缓存
response.flushBuffer();
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0); // 在内存中创建图象
int width = 60, height = 20;
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("Times New Roman", Font.PLAIN, 18)); //画边框
g.setColor(new Color(30, 20, 10));
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);
} // 取随机产生的认证码(4位数字)
String sRand = "";
for (int i = 0; i < 4; i++) {
String rand = String.valueOf(random.nextInt(10));
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);
}
// 将认证码存入SESSION
session.setAttribute("rand", sRand); // 图象生效
g.dispose();
// 输出图象到页面
ServletOutputStream output = null;
try {
output = response.getOutputStream();
ImageIO.write(image, "JPEG", output); } catch (Exception e) {
e.printStackTrace();
} finally {
try {
output.flush();
output.close();
response.getOutputStream().close();
response.getOutputStream().flush(); } catch (Exception e) {
e.printStackTrace();
}
}
%>

index.jsp

 <%@page import="javax.websocket.Session"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>标题</title>
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Cache-Control" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="0">
<script>
function refreshCode() {
//alert("刷新验证码");
location.reload();
}
</script>
</head>
<body>
<form method="post" action="check.jsp">
<table>
<tr>
<td align=left>系统产生的认证码:</td>
<td> <img border=0 src="data:image.jsp">
<a href="#" onclick="refreshCode()">点击刷新</a>
</td>
</tr>
<tr>
<td align=left>输入上面的认证码:</td>
<td><input type=text name=rand maxlength=4
value="<%=request.getSession().getAttribute("rand")%>"></td>
</tr>
<%-- <tr>
<td colspan=2 align=center><input type=submit value="提交检测"></td>
<td>当前系统语言为:<%=response.getLocale()%><br> 当前地址为为:<%=request.getContextPath()%>
</td>
</tr> --%>
</table>
</form>
</body>
</html>

思路二:每次Web上从验证码库中加载验证码显示在web页面,这样做的效率比较低,但安全性较高,用户只能从已有的库中校验。

用在Web上效果如下:

java 生成随机校验码